2016-01-01 31 views
3
int randRow = rand.nextInt(rows-4); 
int randColumn = rand.nextInt(columns); 

在這裏我檢查我的新船是否不會干擾我的第一艘船。整個數組充滿了包含'。'的對象。除了在第一艘船是我試圖做一個基於控制檯的戰列艦遊戲,但我不知道如何設置船隻

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{ 

如果我的新船不適合字符,我想用不同的隨機值重試,但我不知道怎麼辦。

+0

我看到這是你的第一個問題。僅供將來參考,與代碼一起添加邏輯是一個好主意。像戰艦需要四個地方。同樣問題的切線是一個建議。使方法像'isLocationEmpty'和'placeBattleShip'。這會更容易閱讀代碼,然後 –

回答

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 
} 
+0

@dandeman如果這是你正在尋找的,然後upvote /接受答案。我希望你參加了巡迴演出http://stackoverflow.com/tour –

+0

@dandeman最後一件事。觀察並思考我留在這個問題上的評論。如果你的代碼很容易閱讀,你會看到像這個答案更容易的事情。否則,你將看到數組和循環而不是實際的邏輯。 –