[英]I'm trying to make a console based battleship game but I don't know how to set the ships
int randRow = rand.nextInt(rows-4);
int randColumn = rand.nextInt(columns);
Here I check if my new ship doesn't interfere with my first ship. 在这里,我检查我的新船是否不会干扰我的第一艘船。 The entire array is filled with objects which contain a '.' 整个数组都填充了包含'。'的对象。 char except for where the first ship is char除了第一艘船的位置
if(field[randRow][randColumn].value == '.' &&
field[randRow][randColumn+1].value == '.' &&
field[randRow][randColumn+2].value == '.' &&
field[randRow][randColumn+3].value == '.'){
field[randRow][randColumn] = new Square('b');
field[randRow+1][randColumn] = new Square('b');
field[randRow+2][randColumn] = new Square('b');
field[randRow+3][randColumn] = new Square('b');
} else{
If my new ship doesn't fit, I want to retry with different random values but I don't know how. 如果我的新船不合适,我想用不同的随机值重试,但我不知道如何。
Basically you are not sure how to generate the random number again. 基本上你不知道如何再次生成随机数。 Just use something like below 只需使用下面的内容
while(true) {
//generate random number here
if (can place battleship) {
place battleship
break //placed battleship so no need to retry. stop retrying
}
//else we will loop till we can place the battleship
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.