[英]How to make X's and O's alternate
I am trying to make the X's and O's alternate after each turn like in a normal tic tac toe game, but when I run it, all that happens is that it keeps outputting X after each turn. 我试图像普通的井字游戏一样,在每个回合之后交替设置X和O,但是当我运行它时,发生的一切是在每个回合之后它一直输出X。 Why is this happening?
为什么会这样呢?
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");
}
}
}
Your code seems to explicitly set the tile to x
. 您的代码似乎将图块显式设置为
x
。
arr[y][z]='x';
I suspect you'll want something like 我怀疑你会想要像
arr[y][z]= counter % 2 == 0 ? 'x' : 'o';
Also, watch out. 另外,要当心。 You will iterate 9 times on your "input a row/column" code, no matter if the input is valid.
无论输入是否有效,您都将在“输入行/列”代码上迭代9次。 This means that if you input an invalid row/column combination, you'll end up with an 8 turn game.
这意味着,如果您输入了无效的行/列组合,则最终将获得8回合的游戏。
You always change with 'x': 您总是用'x'更改:
arr[y][z]='x'
You could do this: 您可以这样做:
if(arr[y][z]=='-'){
if (counter % 2 == 0) arr[y][z]='x';
else arr[y][z]='o';
board.setBoard(arr);
board.repaint();
counter ++;
}
When counter is even, you change to 'x'. 当计数器为偶数时,您将更改为“ x”。 And when is odd, you change to 'o'.
如果是奇数,则更改为“ o”。
Try implementing something like the following instead of your arr[y][z]='x';
尝试实现如下所示的内容,而不是您的
arr[y][z]='x';
line : 行:
if (counter % 2 == 0)
arr[y][z]='x';
else
arr[y][z]='o';
So it would alternate based on the counter
value (ie if counter is even, then it's 'x's turn, else it's 'o') 因此,它将根据
counter
值进行替换(即,如果计数器为偶数,则为“ x”,否则为“ o”)
I hope that helps 希望对您有所帮助
Because you are always setting it to 'x' here: arr[y][z]='x';
因为您始终在此处将其设置为“ x”:
arr[y][z]='x';
. 。 You need to have a condition where you alternate this value to 'x' and 'o'.
您需要有一个条件,将此值替换为“ x”和“ o”。 Something like a flag which you set and reset on each iteration to determine if you want 'x' or 'o'.
诸如标志之类的东西,您可以在每次迭代中设置和重置以确定是否要使用“ x”或“ o”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.