gpt4 book ai didi

java - 如何检查战列舰游戏中的舰船是否重叠?与算法混淆

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:31:38 28 4
gpt4 key购买 nike

我不是一个出色的程序员,所以我想知道是否有人可以帮助我。在我的战舰游戏中,我有 Rect 级的战舰,但我需要检查它们是否重叠。这是我目前所拥有的。

编辑:到底出了什么问题:我有两艘船,一艘是 2 号,另一艘是 5 号。所以说船 1 的坐标是 (0,0)(0,1),而船 2 的坐标是 (0,1) 到 (5, 1)。它非常适合检查点(0,1)上的第一艘船的两个坐标,但仅此而已。我希望这是有道理的。所以如果我在 (1,1) 上检查 (0,0) 和 (0,1) 它没有显示错误

   public boolean contains(Ship ship) {
int currentX = ship.getX();
int currentY = ship.getY();
int testX = xCoord;
int testY = yCoord;

if (rotated) { //if ship is horizontal enter
for (int j = 0; j < sizeOfShip; j++) {
for (int k = 0; k < ship.getSize(); k++) {
if (testX == currentX && testY == currentY) {
return false;
}
testX++;
}
if (ship.rotated)
currentX++;
else {
currentY++;
}
}
}
//
if (!rotated) {
for (int j = 0; j < sizeOfShip; j++) {
for (int k = 0; k < ship.getSize(); k++) {
if (testX == currentX && testY == currentY) {
return false;
}
testY++;
}
if (ship.rotated)
currentX++;
else {
currentY++;
} }
}
return true;

}

最佳答案

我认为问题出在这里(其他if也是一样):

...
testX++;
}
if (ship.rotated)
currentX++;
else {
currentY++;
}
...

我假设 testXthis ships x 值。您在 inner 循环中的每次迭代中递增 testX 并在外部循环中递增输入参数值 (currentX)。同时,您永远不会重置该值。假设 this ship 的长度为 5,输入参数的长度为 2,并且都是水平的。在外部循环 testX 的 3 次迭代后递增 6。

我认为您想在每次内部迭代后交换增量并重置 currentX/Y 值:

for (int j = 0; j < sizeOfShip; j++) {
for (int k = 0; k < ship.getSize(); k++) {
if (testX == currentX && testY == currentY) {
return false;
}
if (ship.rotated)
currentX++;
else {
currentY++;
}
}
currentX = ship.getX();
currentY = ship.getY();
testX++;
}

对于两个 if 都必须这样做。我不能尝试这个,所以试试看,如果我犯了错误,请告诉我。 :)


换个说法。你可以替换

}
//
if (!rotated) {
...

}
else {
...

关于java - 如何检查战列舰游戏中的舰船是否重叠?与算法混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15857418/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com