我正在尝试制作基于控制台的战舰游戏,但我不知道如何设置船只

时间:2016-01-01 15:40:36

标签: java loops if-statement console

int randRow = rand.nextInt(rows-4);
int randColumn = rand.nextInt(columns); 

我在这里检查我的新船是否不会干扰我的第一艘船。整个数组都填充了包含'。'的对象。 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{

如果我的新船不合适,我想用不同的随机值重试,但我不知道如何。

1 个答案:

答案 0 :(得分:6)

基本上你不确定如何再次生成随机数。只需使用下面的内容

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
}