我需要一些帮助来为一个tic tac toe游戏设计一个简单的AI。我需要计算机在转弯时将2放在下一个可用的插槽上。这是初学者的日食编程课程,但教授休病假并停止回答问题!任何帮助将不胜感激!我在最后ComputerInput[][]
遇到了这个方法的问题。我收到a[0] = a[1]
;
package lab15;
public class WinnerCheck {
public static int PL_ONE = 1;
public static int PL_TWO = 2;
static Console console = new Console();
static final int PAUSE = 500;
public static int[][] b = { { 0, 0, 0 }, { 0, 0, 0 }, { 0, 0, 0 } };
public static void main(String[] args) {
boolean done = false;
while (!done) {
printBoard(b);
playerOneInput();
computerInput(b);
pause(PAUSE);
detectWinner(b);
console.clear();
}
}
public static void pause(int ms) {
try {
Thread.sleep(ms);
} catch (Exception ex) {
}
}
public static void placePiece(int[][] b, int r, int c, int player) {
b[r][c] = player;
}
public static boolean isWinner(int[][] b, int player) {
// check for a horizontal winner
for (int i = 0; i < b.length; i++) {
int count = 0;
for (int j = 0; j < b[i].length; j++) {
if (b[i][j] == player
|| b[j][i] == player ) {
count++;
}
}
if (count == b[i].length)
return true;
}
return false;
}
public static int detectWinner(int[][] b) {
if (isWinner(b, PL_ONE)) {
return 1;
} else if (isWinner(b, PL_TWO)) {
return 2;
} else {
return 0;
}
}
public static void printBoard(int[][] b) {
System.out.println("------");
for (int[] row : b) {
for (int element : row) {
System.out.print(element + " ");
}
System.out.println("");
}
System.out.println("------");
System.out.println("winner: " + detectWinner(b));
}
public static void playerOneInput() {
switch (console.getKey()) {
case '1':
placePiece (b, 0, 0, 1);
break;
case '2':
placePiece (b, 0, 1, 1);
break;
case '3':
placePiece (b, 0, 2, 1);
break;
case '4':
placePiece (b, 1, 0, 1);
break;
case '5':
placePiece (b, 1, 1, 1);
break;
case '6':
placePiece (b, 1, 2, 1);
break;
case '7':
placePiece (b, 2, 0, 1);
break;
case '8':
placePiece (b, 2, 1, 1);
break;
case '9':
placePiece (b, 2, 2, 1);
break;
}
}
public static int computerInput(int[][]b) {
int a[]= {-1};
for (int i = 0; i < b.length; i++) {
for (int j = 0; j < b[i].length; j++) {
if (b[i][j] == 0
|| b[i][j] == 1 ) {
a[0] = a[1];
}
}
}
return a[];
}
}
答案 0 :(得分:0)
您使用一个值初始化了A.所以它的长度只有1.这意味着唯一的索引为0.你需要添加一个默认的第二个值或者将声明更改为int a [] = new int [2];
答案 1 :(得分:0)
您需要更改方法标头以返回int []而不是int。你的return语句应该只返回一个。这应该可以解决这个问题。