for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
visBoard[i][j] = "[ ]";
board[i][j] = 0;
check[i][j] = false;
}
}for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
System.out.print(visBoard[i][j]);
}System.out.print("\n");
}
//Getting Names
System.out.println("Player 1 - Enter your name");
play1 = sc.nextLine();
System.out.println("Player 2 - Enter your name");
play2 = sc.nextLine();
//
moves = 0;
symbol = " X ";
do{
do{
//Get Coords
System.out.println("X Coordinate");
xcoord = sc.nextInt() -1;
System.out.println("Y Coordinate");
ycoord = sc.nextInt() -1;
if(check[xcoord][ycoord] == true){
System.out.println("Not a valid move!");
}
}while(check[xcoord][ycoord] == true);
//Making move
check[xcoord][ycoord] = true;
visBoard[xcoord][ycoord] = symbol;
if(symbol.equals(" X ")){
board[xcoord][ycoord] = 1;
}else if(symbol.equals(" O ")){
board[xcoord][ycoord] = 5;
}else{
System.out.println("You've messed up James");
}
for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
System.out.print(visBoard[i][j]);
}System.out.print("\n");
}
//Check if game has won
//columns
total = 0;
for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
total = total + board[j][i];
}if(total == 15 || total == 3){
gamewon = true;
}
}total = 0;
//rows
for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
total = total + board[i][j];
}if(total == 15 || total == 3){
gamewon = true;
}
}total = 0;
//diagonals
for(int i = 0; i < 3; i++){
total = total + board[i][i];
}if(total == 15 || total == 3){
gamewon = true;
}total = 0;
diag = 2;
for(int i = 0; i < 3; i++){
total = total + board[i][diag];
diag--;
}if(total == 15 || total == 3){
gamewon = true;
}
moves++;
if(gamewon == false){
if(moves == 9){
System.out.println("Game has been drawn! No one wins!");
}else{
mod = moves % 2;
if(mod == 0){
symbol = " X ";
}else{
symbol = " O ";
}
}
}
}while(gamewon == false || moves != 9);
if(gamewon == true){
if(symbol.equals(" X ")){
System.out.println("Winner is "+play1);
}else{
System.out.println("Winner is "+play2);
}
}else{
System.out.println("Game is drawn");
}
}
}
这是我之前提出的问题的另一个问题。这个游戏不会在移动达到9之前结束,即使有人赢了也会停止while循环。布尔值将变为true,但它将继续循环。
如何通过保持while条件来修复此问题,并且可能不使用中断?
答案 0 :(得分:2)
你需要一个而不是一个或
while(gamewon == false && moves != 9);
读给自己说它虽然没有赢家,但我们没有进行第9步。但是通常更好的形式来编码你的循环来检查你是否已经超过界限而不是你完全击中了界限,直接测试布尔值也更好,所以下面更时尚:
while(!gamewon && moves < 9);
答案 1 :(得分:0)
while(gamewon == false || moves != 9)....
这告诉循环在游戏未获胜时执行,或者移动不是9.为了结束,两个条件需要改变,游戏需要结束并且移动需要为9。
更改你的||操作员和&amp;&amp ;.这样游戏将继续进行,而游戏没有赢,而且移动不是9.这似乎有点奇怪,但如果你能按照逻辑,你会发现你需要AND操作符。
因此,您正在寻找:
while(gamewon == false && moves != 9)