我正在用 Java 编写一个炸弹人游戏,我已经为游戏地图(包含瓷砖)、玩家(以及他们在地图中的移动)编写了代码,现在我被困在炸弹爆炸的代码中.
我有一个Map
包含 2d 数组的类Tiles
,它可以包含Player
s、Block
s 和Bomb
s。该Player
对象有一个方法,该方法从对象(每个都有对象的引用)dropBomb
调用该方法,并带有炸弹和炸弹的位置。调用该方法时,地图将炸弹放入正确的. 我的问题是炸弹爆炸。谁应该关心它?炸弹本身?如果是,炸弹应该有包含它的参考吗?到目前为止,我的瓷砖还不需要参考。receiveBomb
Map
Player
Map
Map
receiveBomb
Tile
Tile
Map
我认为的一种可能性是Tile
在对象内部有引用Bomb
,因此,当炸弹爆炸(并且炸弹知道它应该何时爆炸)时,它会调用 tile 对象中的方法进行爆炸,而 tile 会调用地图中的方法. 顺便说一句,我不知道这是个好主意。我应该怎么办?
public class Tile {
private boolean available; //if the tile is not occupied by a indestructible block or bomb
private List<Entity> entities; //you can have more than one player at a tile
public boolean receiveEntity(Entity entity) {
boolean received = false;
if (available) {
this.entities.add(entity);
received = true;
if (entity instanceof Block || entity instanceof Bomb) {
available = false;
}
}
return received;
}
public boolean removePlayer(Player player) {
return entities.remove(player);
}
}
球员等级:
public class Player implements Entity {
private Map gameMap;
private int posX;
private int posY;
private int explosionRange; //the explosion range for bombs
public Player(int posX, int posY, Map gameMap) {
this.gameMap = gameMap;
this.posX = posX;
this.posY = posY;
this.explosionRange = 1;
}
public void dropBomb() {
gameMap.receiveBomb(new Bomb(explosionRange), posX, posY);
}
}
地图类:
public class Map {
private Grid<Tile> tileGrid;
private int width;
private int height;
public Map(int width, int height, BuildingStrategy buildingStrategy) {
this.width = width;
this.height = height;
this.tileGrid = new Grid<Tile>(width, height);
buildingStrategy.buildMap(this);
}
public void receiveBomb(Bomb bomb, int posX, int posY) {
tileGrid.get(posX, posY).receiveEntity(bomb);
}
}
我省略了运动方法,因为运动已经很好了。