【问题标题】:How to check if a ship sank in battleship game java如何在战舰游戏java中检查一艘船是否沉没
【发布时间】:2018-04-07 23:16:07
【问题描述】:

我开始用java创建战舰游戏。我有 5 艘船,长度为 5,4,3,3,2 和一个数组 int gameBoard[][] = new int[10][10]; 我把船放在哪里。我还创建了一个数组boolean BoardHits[][]= new boolean[10][10];,在其中检查玩家的命中率。 现在我想创建一个方法boolean getBoardStrike(int[] hit),它将一个位置作为参数,如果该位置没有再次被击中,则在 BoardHits 数组中添加一个击中。如果我们击中一艘船,我们必须检查是否所有船位都被击中(船沉没)。有没有有效的方法来实现这一点? (当我将一艘船放入数组 gameBoard 中时,我输入了船 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;
    }
}

【问题讨论】:

  • 你如何确定一艘船是什么?
  • 致电myShip.isFloating()
  • 当我将一艘船放入板中时,我输入了船号。例如,如果我在游戏板中放置一艘长度为 4 的船,我将有 4 个单元格,分别为 4 4 4 4。所以我知道是什么样的船
  • 听起来你需要做更多的视图模型提取,包括创建 Ship 类,其实例填充板的类,它们具有 public boolean hit(int x, int y) 方法和 isFloating() 方法。当发生命中尝试时,遍历List<Ship> 找出是否有船被击中,然后调用其isFloating() 方法。
  • @LeeYaan 好的,所以,你需要比较boardhits 并确定hits 的占用空间覆盖了board 上的所有“船” - 我,就个人而言,我有一个“船”对象,其中包含“命中”。我会使用棋盘来确定每艘船的位置以及它们指向的方向 - 简单得多 - 但这就是我

标签: java arrays algorithm methods


【解决方案1】:

我会尝试更多面向对象的方法,因为 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 并在构造函数中创建新部件即可创建新船型。

【讨论】:

    猜你喜欢
    • 2021-03-05
    • 1970-01-01
    • 2019-07-05
    • 1970-01-01
    • 2014-01-18
    • 2021-11-30
    • 1970-01-01
    • 2022-01-02
    • 2018-01-05
    相关资源
    最近更新 更多