【发布时间】:2018-06-07 22:34:18
【问题描述】:
我有一种方法可以尝试确定 AI 在井字游戏中的移动。目前我有一种方法,计算机随机选择一个按钮,但我希望它更聪明一点。我对如何做到这一点有一个想法,但在实施中需要一些指导。
基本上我希望计算机知道,如果有可能或赢或输,那么它会将他们的计数器放在方格上,这将帮助他们赢得或阻止玩家获胜。下面是一个使用 3x3 tic tac toe board 坐标网格的示例:
00 01 02
10 11 12 -- coordinates of all of the buttons in a tic tac toe board
20 21 22
if 00 is not empty and 01 is same as 00, then place 'O' on 02 -- helps win or prevent a win for 3 in a row
if 01 is not empty and 02 is same as 01, then place 'O' on 00 -- helps win or prevent a win for 3 in a row
if 01 is not empty and 21 is same as 01, then place 'O' on 11 -- helps win or prevent a win for 3 in a column
if 20 is not empty and 02 is same as 20, then place 'O' on 11 -- helps win or prevent a win for 3 in a diaganol
正如您所知,还有更多场景,但主要目的是如果有机会获胜或有机会阻止获胜,那么计算机将需要放置他们的“O”。如果条件不满足则基本上选择一个随机按钮。
所以我知道我需要一堆 else if 但是如何实现它来完成它需要做的事情?
下面是我试图做的一个框架,以防止在一行中连续 3 次获胜/获胜,并在上述任何条件不匹配时选择任何随机按钮:
private void computerMove() {
String[][] field = new String[3][3];
Random random = new Random(); //you may want to declare this as a class field
List<Button> emptyButtons = new ArrayList<>();
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
field[i][j] = buttons[i][j].getText().toString();
if (field[i][j].equals("")) {
emptyButtons.add(buttons[i][j]);
}
}
}
Button selectButton;
for (int i = 0; i < 3; i++) {
if (field[i][0].equals(field[i][1])
&& field[i][2].equals("")){
//prevent win/win on rows by selecting the correct button here
}
else if (field[i][0].equals(field[i][2])
&& field[i][1].equals("")){
//prevent win/win on rows by selecting the correct button here
}
else if (field[i][1].equals(field[i][2])
&& field[i][0].equals("")){
//prevent win/win on rows by selecting the correct button here
}
else {
selectButton = emptyButtons.get(random.nextInt(emptyButtons.size()));
}
selectButton.setText("O");
selectButton.setTextColor(playerO);
turnsCount++;
isGameOver();
}
【问题讨论】:
标签: java