我试图像普通的井字游戏一样,在每个回合之后使X和O交替出现,但是当我运行它时,所有发生的事情是在每个回合之后它一直输出X。为什么会这样呢?
import java.util.Scanner;
public class TicTacToe{
public static void main(String[] args){
Scanner reader = new Scanner(System.in);
Scanner numreader = new Scanner(System.in);
TicTacToeBoard board = new TicTacToeBoard(620,720);
board.setFiles("X.png", "O.jpeg");
int[][] lines = new int[4][4];
lines[0][0] = 0;
lines[0][1] = 200;
lines[0][2] = 600;
lines[0][3] = 200;
lines[1][0] = 0;
lines[1][1] = 400;
lines[1][2] = 800;
lines[1][3] = 400;
lines[2][0] = 200;
lines[2][1] = 600;
lines[2][2] = 200;
lines[2][3] = 0;
lines[3][0] = 400;
lines[3][1] = 600;
lines[3][2] = 400;
lines[3][3] = 0;
board.defineBoard(lines);
int counter = 0;
char[][] arr= {
{'-','-','-'},
{'-','-','-'},
{'-','-','-'},
};
board.setBoard(arr);
int a = 0;
for(int i = 0; i<9; i++){
System.out.println("Enter what row:");
int y = numreader.nextInt();
System.out.println("Enter what column:");
int z = numreader.nextInt();
if(arr[y][z]=='-'){
arr[y][z]='x';
board.setBoard(arr);
board.repaint();
counter ++;}
else
System.out.println("This is not allowed");
}
}
}
最佳答案
您的代码似乎将图块显式设置为x
。
arr[y][z]='x';
我怀疑你会想要像
arr[y][z]= counter % 2 == 0 ? 'x' : 'o';
另外,要当心。无论输入是否有效,您都将对“输入行/列”代码进行9次迭代。这意味着,如果您输入了无效的行/列组合,则最终将获得8回合的游戏。
关于java - 如何使X和O交替,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35660672/