我开始用java创建战舰游戏。我有 5 艘船,长度为 5,4,3,3,2,还有一个int gameBoard[][] = new int[10][10];
我放置船只的阵列。我还创建了一个数组boolean BoardHits[][]= new boolean[10][10];
用于检查玩家的命中率。现在我想创建一个方法boolean getBoardStrike(int[] hit)
该方法,该方法将一个位置作为参数,并在 BoardHits 数组中添加一个命中,如果这个位置没有再次被命中。如果我们击中了一艘船,我们必须检查是否所有船只位置都被击中(船沉没(。有没有有效的方法来实现这一点?(当我在数组游戏板中放置一艘船时,我输入了船 ID,因此如果我在棋盘中放置长度为 5 的船,我有 5 个数字为 5 的单元格(。
public boolean getBoardStrike(int[] hit) {
boolean flag = true;
if (boardHits[hit[0]][hit[1]] = false) {
hits[hit[0]][hit[1]] = true;
//check if the whole ship is hitted
return true;
}
else {
return false;
}
}
我会尝试更多面向对象的方法,因为Java是面向对象的语言:
public interface Battleship {
public void hit(Point shot);
public List<Point> getCoordinates();
public boolean isSinked();
}
public class BattleshipPart {
private boolean hit;
private Point coordinate;
// getters and setters
}
public abstract class AbstractBattleship implements Battleship {
// these are for direction in constructors
public static int NORTH = 1;
public static int EAST = 2;
public static int SOUTH = 3;
public static int WEST = 4;
protected List<BattleshipPart> parts;
public void hit(Point shot) {
return parts.stream()
.findFirst(part -> part.coordinate.equals(shot))
.ifPresent(part -> part.setHit(true));
}
public List<Point> getCoordinates() {
return parts.stream()
.map(part -> part.getCoordinate())
.collect(Collectors.toList());
}
public boolean isSinked() {
return parts.stream()
.allMatch(BattleshipPart::isHit);
}
}
public final class SmallBattleship extends AbstractBattleship {
public SmallBattleship(Point start, int direction) {
// create parts or throw exception if parameters weren't valid
}
}
只需扩展AbstractBattleship
并在构造函数中创建新部件即可创建新船型。