我需要一些帮助来设计一个简单的人工智能的井字游戏。我需要电脑在他轮到的下一个空位上放2。这是一个初学者的eclipse编程课程,但是教授请了病假并停止了回答问题!任何帮助都将不胜感激!我在使用end 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[];
}
}发布于 2014-06-05 09:16:45
您使用一个值初始化了A。所以它的长度只有1,这意味着唯一的索引是0。您需要添加第二个缺省值或将声明更改为int a[] = new int2;
发布于 2014-06-05 09:30:54
您需要更改您的方法标头,以返回int[]而不是int。你的return语句应该只返回a。这应该可以解决这个问题。
https://stackoverflow.com/questions/24050077
复制相似问题