2013-09-26 37 views
1

目前正在製作掃雷遊戲,並堅持能夠通過周圍8個單元循環查找周圍炸彈的數量。我有一個幫助器方法,我認爲它可以很好地檢查單元格(通過numberOfAdjacentBombs傳遞)是否包含炸彈。我如何去創建一個循環遍歷每個周圍單元格的嵌套for循環?例如(行-1,列-1),(行-1,列),(行-1,列+ 1)。Java編程 - 嵌套for循環掃雷遊戲

任何幫助或提示表示讚賞,謝謝! :-)

private int numberOfAdjacentBombs(int row, int col){ 
int count = 0; 
//nested for loop 
count += getIfBomb(int, int) 
} 

幫助程序方法檢查單元格是否包含炸彈,如果是,返回1,否則返回0。

private in getIfBomb(int row, int col){ 
if(cells[row][col].getHasBomb() == true){ 
    return 1; 
}else{ 
    return 0; 
} 
} 
+0

寫下它應該訪問的指數,你將有你的循環大綱。 –

回答

3

不考慮邊界檢查...

您需要檢查的行和列,實際的列和行後....

東西列和行像...

row - 1, col - 1 
row - 1, col 
row - 1, col + 1 
row, col - 1 
row, col 
row, col + 1 
row + 1, col - 1 
row + 1, col 
row + 1, col + 1 

這可能看起來像......

for (int visitRow = row - 1; visitRow < row + 1; visitRow++) { 
    for (int visitCol = col - 1; visitCol < col + 1; visitCol++) { 
     count += getIfBomb(visitRow, visitCol) 
    } 
} 

現在,您getIfBomb方法將需要範圍檢查它通過檢查,他們都不敢出數組的邊界值...但我想我能留給你......

+0

'(row,col)'不需要檢查 –

+0

@JimGarrison這是真的,我們可能想要考慮與方法調用相比,if語句的計算開銷,但這只是一個例子OP速度達到 – MadProgrammer

0

網格可能看起來有點像這樣:

(x-1, y+1) (x, y+1) (x+1, y+1) 
(x-1, y) (x, y) (x+1, y) 
(x-1, y-1) (x-1, y) (x+1, y-1) 

你可以做的是構建一個for循環,迭代從x-1x+1和內部,從y-1y+1另一個迴路(考慮採取的邊緣,當然),並且簡單地跳過案例w如果你正在看(x, y)

for(int i = x-1; i <= x+1; i++) { //x-values 
    for(int j = y-1; j <= y+1; j++) { //y-values 
     if(i != x && j != y) { 
      //do your snazzy minesweeper jazz here 
     } 
    } 
} 
+0

檢查比賽場地邊界上的細胞時怎麼辦? –

+0

只需在if語句中添加一個額外的檢查以確保您跳過這些:if(i!= x && j!= y && i 0 && j 0) '。你可以輕鬆地調整你的喜好。 – Bucket