本质上,这是我 12 年级用 Java 编写的大型代码项目,目的是制作一艘战舰。我已经完成了大部分机械工作,我只是在与随机船生成器斗争。有时,它似乎几乎可以在尺寸变化的情况下工作,但是,我经常发现随机的团 block 与我想要的船不一样。基本上,二维网格上的每个点都是一个对象,它有一个名为 status 的 int 变量。如果status=0,则为水点。如果status=1,则为船点。我的代码有任何错误或者可能有更好的方法吗?谢谢您的帮助,我真的很感激:)
没有做过任何其他方法,因为我没有想到其他方法。
void addBoat(int x) {
int c=floor(random(4));//picks a random direction
int tx, ty;//target location in array
tx=floor(random(xs));//xs is x size of the array
ty=floor(random(ys));//ys is the y size of the array
for (int i=0; i<x; i++) {
//paramaters for conditions
if (c==0 && tx>=x-1 && sqr[tx-i][ty].status==0) {
sqr[tx-i][ty].status=1; //to the left of the target block, status is whether it is water or boat. water is status=0, boat is status=1.
} else if (c==1 && tx<=xs-x && sqr[tx+i][ty].status==0) {
sqr[tx+i][ty].status=1; //to the right of the target block
} else if (c==2 && ty>=x-1 && sqr[tx][ty-i].status==0) {
sqr[tx][ty-i].status=1; //above the target block
} else if (c==3 && ty<=ys-x && sqr[tx][ty+i].status==0) {
sqr[tx][ty+i].status=1; //below the target block
} else {
c=floor(random(4));
i=0;
//if position is not possible, run again
}
}
}
void makeBoat() {
addBoat(2);
addBoat(3);
addBoat(3);
addBoat(4);
addBoat(5);
}
我希望船的尺寸合适,并且可以垂直或水平,但我通常只会得到奇怪的团 block 。
最佳答案
在我看来,你在检查你的船是否可以完全放置之前就先放置了你的船件。当它检测到无法正确放置船时,它会重新开始而不删除已经生成的碎片。另一件事是,对于无法将船放置在选定的起始位置的情况,您似乎没有任何准备,此时它可能会陷入无限循环。
总而言之,我建议您首先生成一组位置、方向和长度,然后检查这是否是有效的船放置,然后才放置它(或生成新的集合),即将其分为三种方法。如果生成的船只无法放置下一艘,那么出现无限循环的可能性仍然很小,因此您可能需要进行一些检查来防止这种情况发生(如果尝试超过 10,000 次,则可能完全删除状态并重新开始)对于单船或其他东西)。
您还应该使用枚举而不是整数来表示您的状态/方向,以使其更具可读性。如果您的状态仅存储是否有水或船,您也可以使用 boolean 值。
关于java - 如何用java制作战舰产卵器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56275983/