我正在尝试用 Java 创建游戏 SeaBattle,请参阅下面的类图。
网格上船只的视觉表示是通过将船只覆盖的区域的单元格设置为深色来实现的。
为了放置一艘船,我将调用它的分段 place() 方法并为其提供坐标。为了便于稍后在通过单击其所在的单元格来选择正确的段时获取正确的段,我认为单元格最好包含对同一段的引用。
我面临的实现问题在于移除船只:应该可以根据船只的命令移除船只(简单:循环遍历其分段并取消放置它们,同时删除它们所在单元格中的引用in),但也可以通过单击船舶(即:网格中的其中一个部分)来实现。每当发生这种情况时,我都知道点击了哪个部分,但我需要弄清楚该部分属于哪艘船,以便也取消放置其他部分。
我可以获取单击的单元格坐标,循环遍历所有船只及其分段并检查坐标是否匹配,但我觉得会有更好的方法。也许以不同的方式设置类图的一部分会更好。
最佳答案
我们可以将 Ship
字段添加到 ShipSegment
中,并使 ShipSegment
成为 Cell
的子类。这是一种可能的实现:
public class Battlefield {
Cell[][] cells;
public Battlefield(int size) {
this.cells = new Cell[size][size];
for (int x = 0; x < size; x++) {
for (int y = 0; y < size; y++) {
cells[x][y] = new Cell();
}
}
}
public void add(Ship ship) {
int start = ship.horizontal ? ship.x : ship.y;
for (int i = 0; i < ship.size(); i++) {
cells[ship.horizontal ? i + start : ship.x][ship.horizontal ? ship.y : i + start] = ship.getSegment(i);
}
}
public void remove(Ship ship) {
int start = ship.horizontal ? ship.x : ship.y;
for (int i = start; i < start + ship.size(); i++) {
cells[ship.horizontal ? i : ship.x][ship.horizontal ? ship.y : i] = new Cell();
}
}
public boolean shoot(int x, int y) {
return cells[x][y].shoot();
}
}
public class Cell {
private boolean isShot;
public Cell() {
this.isShot = false;
}
public boolean isEmpty(){
return true;
}
public boolean isShot(){
return isShot;
}
public boolean shoot() {
isShot = true;
return isEmpty();
}
}
public class ShipSegment extends Cell {
Ship ship;
public ShipSegment(Ship ship) {
super();
this.ship = ship;
}
@Override
public boolean isEmpty() {
return false;
}
public Ship getShip() {
return ship;
}
}
public class Ship {
int x, y;
boolean horizontal;
ShipSegment[] segments;
public Ship(int x, int y, int size, boolean horizontal) {
this.x = x;
this.y = y;
this.horizontal = horizontal;
segments = new ShipSegment[size];
for (int i = 0; i < size; i++) {
segments[i] = new ShipSegment(this);
}
}
public int size() {
return segments.length;
}
public boolean isDestroyed() {
for (ShipSegment segment : segments) {
if (!segment.isShot()) {
return false;
}
}
return true;
}
public ShipSegment getSegment(int index){
return segments[index];
}
}
关于java - 如何从保存子对象引用的类访问父对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49406367/