2
注意:我爲文本牆道歉,但我堅持讓我自己的代碼工作。我已經挖掘了其他類似的問題,但我沒有看到爲什麼我無法通過這些代碼來搜索所有內容。我會接受半神祕的答案,至少在正確的方向指出我的感謝。掃雷 - 揭示所有空的瓦片而不是隻有一些
爲了練習java,並回答一個我正在運行的關於掃雷的問題,我決定嘗試構建一個掃雷機器人,以準確找出在給定的遊戲開始時最佳的勝率。儘管如此,我仍然努力在遊戲代碼中獲得正確的行爲,特別是在我有遊戲揭示沒有相鄰地雷的方格的情況下。我最終0的上透露空間的邊緣,而不是我的代碼搜索周圍的地磚,象下面這樣:
Printing Field:
-
-
-
-
-
-
-
-
-
- 1 1 2 1
- 0 0 0 0 0 1
- 1 0 0 0 1 2 3
- 1 0 0 0 0 0 0 0
- 2 1 0 0 0 0 0
- 1 0 0 0 0 0
- 1 0 0 0 0 0
我跟蹤2維字符數組的實際字段,然後跟蹤在相同大小的布爾數組中顯示空格。我包括下面的方法,一旦另一種方法找到了'0',這標誌着一個沒有炸彈的空間。我有另一種方法可以處理當前字段中顯示的部分,如果有人對此感興趣,可以分享。
private void checkAround(int x, int y)
{
//this pattern is used to parse out the comma to get the coordinates.
String regex = "[,]";
Pattern pat = Pattern.compile(regex);
ArrayList<String> to_check = new ArrayList<String>(); //the list of coordinates to check.
to_check.add("" + x + "," + y);
revealed_field[x][y] = true; //marking the coordinates as revealed.
do //iterates through the to_check list until nothing is in it.
{
//these next 2 sections handle pulling the next item from to_check
String temp = to_check.get(0);
to_check.remove(0);
String[] xy = pat.split(temp);
int a = Integer.parseInt(xy[0]); //local declaration of x
int b = Integer.parseInt(xy[1]); //local declaration of y
//if either a or b are outside the bounds of the respective axis, we skip the coordinate and move on.
if (b > height-1 || b < 0) continue;
if (a > width-1 || a < 0) continue;
if (bomb_field[b][a] == '0') //if this is not adjacent to a bomb
{
if (a > 0 && revealed_field[b][a-1] == false) //adds the square above to to_check
{
to_check.add("" + (b) + "," + (a-1));
revealed_field[b][a-1] = true;
}
if (b > 0 && revealed_field[b-1][a] == false) //adds the square left to to_check
{
to_check.add("" + (b-1) + "," + (a));
revealed_field[b-1][a] = true;
}
if (b < height-1 && revealed_field[b+1][a] == false) //adds the square right to to_check
{
to_check.add("" + (b+1) + "," + (a));
revealed_field[b+1][a] = true;
}
if (a < width-1 && revealed_field[b][a+1] == false) //adds the square below to to_check
{
to_check.add("" + (b) + "," + (a+1));
revealed_field[b][a+1] = true;
}
}
}
while (to_check.size() > 0); //ends once we have nothing to check.
}
你把「b,a」放在數組中,但是你把它看作「a,b」? – immibis 2015-03-25 04:22:11
順便說一句,如果你寫了一個Coordinate類,這段代碼會更簡單(但這不是codereview,這不是你問的)。 – immibis 2015-03-25 04:22:44
嘿,我會採取反饋意見,我知道我是新人,而且我知道使用a,b這樣的醜陋,但我不知道有更好的方法。 此外,謝謝你的神祕暗示,這是我所需要的。我編輯了代碼來保存a,b而不是b,並且它可以工作。謝謝!現在,如果只有我可以有2個小時的時間,我就盯着這個完成任何東西.... – 2015-03-25 04:32:16