背景
我有以下内容:
类火扩展元素,
木类扩展元素,
合成元素的Tile类。
Tile 类表示世界/屏幕/ Canvas 中的一个图 block ,其中包含一些图形和逻辑功能。 它合成了一个 Element 对象,因为“世界”中的每一 block 瓷砖都是由某种物质 (=element) 构成的。
我想实现火蔓延的功能——当火元素“接触”木元素时,我想让木元素变成火。 从逻辑上讲,这应该在火元素内完成,但是这样做,我无法更改给定的 Tile 元素(例如,从木头到火)。
“世界”被初始化为一个由木元素组成的方 block 网格,除了一个具有应该传播的火元素的方 block 。
我尝试了什么
我试过将元素链接在一起,这意味着每个元素都可以访问他的四个最近的邻居。这样火就可以接触到附近的一 block 木头。 这并没有解决当火碰到木头时改变 Tile 的元素类型的问题。
我已经尝试将整个功能移至 Tile 类。虽然它确实解决了问题,但我不喜欢它有两个原因:
从逻辑上讲,我希望火能够自主行动,这意味着蔓延的是火,而不是瓷砖。
因此,Tile 类有许多方法只与火相关(例如 spread()),这需要我检查 - “这个瓦片是由火元素组成的吗?”,这很糟糕练习。
代码示例
class Fire extends Element{
public void spread(){
// Move to all four neighbors and turn them into Fire elements
}
}
class Wood extends Element{
}
class Tile{
private Element _element;
}
深入了解
图 block 的“网格”由一个二维图 block 数组(逻辑部分)和一个由所有图 block 组成的 JavaFx Pane(视觉部分)组成。
当火碰到邻近的瓷砖并将其从木转为火时,火就会“蔓延”。火在消耗(=变为火)给定的木材阈值时停止蔓延,例如在它消耗了 30 block 木头之后。从某种意义上说,火可以记录它消耗的木材。
提前致谢!
最佳答案
我立即想到应该有一个类来管理火势蔓延。比方说,有一个 World
类,它知道瓷砖的网格及其性质。 Fire
对Wood
、它的位置、它的邻居一无所知。 Wood
也是如此。它们是独立的对象,过着自己的生活。 世界
由他们决定他们居住在哪里以及他们如何互动。
让我们想象一下 Fire
释放一个事件并告诉
I wanna spread. Here are the locations I'd like to occupy. My height/my intensity/my frequency/my [any other characteristic of fire] is ..."
World
接收消息,考虑到火的特性,并相应地修改网格。
OK. With this intensity/height/[any other characteristic] of the fire, this and this
Wood
elements are going to be burnt. I will replace them with newFire
instances (or I will make a copy the existingFire
object and put a reference to it into the expected-to-be-burnt cells).
拥有一个 Fire
实例并跟踪它燃烧的所有元素会很有趣。我可以看到复制构造函数的修改版本。
Fire(Fire current, Elements... newlyTakenElements)
不过,您可以自由地想出自己的方式来记录它。
有了这个,当火熄灭时,您将能够(全部或部分)恢复细胞。您还可以分析火势是如何发展的。我不确定这是否会派上用场,但设计起来很有趣。
我正在考虑替代方案...我仍然认为向 Fire
提供太多信息(整个图 block map )不是可行的方法,并且 Wood< 之间的任何交互
和 Fire
单元应该通过管理器类。
看看另一个场景,它表明 World
提供了自身的部分 View ,作为与火元素相邻的列表。
-I wanna spread.
-OK. Here's a list of adjacent burnable elements. I am not aware of your characteristics. It's up to you to decide how many cells (and which ones) you are going to burn.
-I've burned them all. Give me more!
The world gives another list until the fire is sated.
关于java - 两个对象的双向依赖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55800210/