我正在尝试从我拥有的书中制作“Tec Tac Toc”游戏。
问题是我在棋盘上没有玩家动作更新。我只会让电脑动起来。
我应该怎么做才能解决问题?
我试图使代码尽可能清晰。
我写的代码:
import java.util.Scanner;
public class TecTacToe {
Scanner input=new Scanner(System.in);
private char[][] squares ;
ddd
public TecTacToe() {
squares=new char[][]{{'.' , '.', '.'},
{'.' , '.', '.'} ,
{'.' , '.', '.'}};
}
dd
public String toString(){
String result="";
for(int row=0;row<3;row++){
for(int column=0;column<3;column++){
result+=squares[row][column];
}
result+="\n";
}
return result;
}
fff
public static void main(String[] args) {
TecTacToe game= new TecTacToe();
System.out.println("welcome to Tic Tac Toe");
game.play();
System.out.println(game);
System.out.println("Game over");
}
dd
public boolean gameOver(){
if(score()!=0){
return true;
}
for(int row=0;row<3;row++){
for(int column=0;column<3;column++){
if(squares[row][column]=='.'){
return false;
} //end of if statment
}//second loop
}// first loop
return true;
}// end of game over class
ff
public int score(){
int lineScore;
for(int i=0;i<3;i++){
lineScore=scoreLine(squares[i][0],squares[i][1],squares[i][2]);
if(lineScore!=0){
return lineScore;
}
lineScore=scoreLine(squares[0][i],squares[1][i],squares[2][i]);
if(lineScore!=0){
return lineScore;
}
}
lineScore=scoreLine(squares[0][0],squares[1][1],squares[2][2]);
if(lineScore!=0){
return lineScore;
}
return scoreLine(squares[0][2],squares[1][1],squares[2][0]);
}
ddd
protected int scoreLine(char a,char b, char c){
if( (a=='X') && (b=='X')&& (c=='X')){ return 1;}
if((a=='O')&&(b=='O')&&(c=='O')) {return -1;}
return 0;
}
ddd
public void play(){
char player ='X';
for(int move=0;move<9;move++){
if(gameOver()){
return;
}
if(player=='X'){
playbestMove();
player='0';
}
else{
System.out.println(this);
System.out.println("Enter the row: ");
int row=input.nextInt();
System.out.println("Enter the column: ");
int column=input.nextInt();
squares[row][column]='0';
player='X';
}
}
}
ddd
protected void playbestMove(){
int score;
int bestScore=-2;
int bestRow=-1;
int bestColumn=-1;
for(int row=0;row<3;row++){
for(int column=0;column<3;column++){
if(squares[row][column]=='.'){
squares[row][column]='X';
score=score();
bestRow=row;
bestColumn=column;
}
squares[row][column]='.';
}
}
squares[bestRow][bestColumn]='X';
}
ddd
}//end of tec tac toe class