Write a program that plays tic-tac-toe. The tic-tac-toe game is played on a 3x3
ID: 3557323 • Letter: W
Question
Write a program that plays tic-tac-toe. The tic-tac-toe game is played on a 3x3 grid the game is played by two players, who take turns. The first player marks moves with a circle, the second with a cross. The player who has formed a horizontal, vertical, or diag- onal sequence of three marks wins. Your program should draw the game board, ask the user for the coordinates of the next mark, change the players after every successful move, and pronounce the winner. every successful move, and pronounce the winner.
have to complete the program using these two classes and add the getWinner Method
Explanation / Answer
public class TicTacToe {
public static void main(String[] args) {
Game game = new Game();
}
}
-->Board.java
public class Board {
private int[][] Board= new int[3][3];
public Board(){
clearBoard();
}
public void clearBoard(){
for(int line=0 ; line<3 ; line++)
for(int column=0 ; column<3 ; column++)
Board[line][column]=0;
}
public void showBoard(){
System.out.println();
for(int line=0 ; line<3 ; line++){
for(int column=0 ; column<3 ; column++){
if(Board[line][column]==-1){
System.out.print(" X ");
}
if(Board[line][column]==1){
System.out.print(" O ");
}
if(Board[line][column]==0){
System.out.print(" ");
}
if(column==0 || column==1)
System.out.print("|");
}
System.out.println();
}
}
public int getPosition(int[] attempt){
return Board[attempt[0]][attempt[1]];
}
public void setPosition(int[] attempt, int player){
if(player == 1)
Board[attempt[0]][attempt[1]] = -1;
else
Board[attempt[0]][attempt[1]] = 1;
}
public int checkLines(){
for(int line=0 ; line<3 ; line++){
if( (Board[line][0] + Board[line][1] + Board[line][2]) == -3)
return -1;
if( (Board[line][0] + Board[line][1] + Board[line][2]) == 3)
return 1;
}
return 0;
}
public int checkColumns(){
for(int column=0 ; column<3 ; column++){
if( (Board[0][column] + Board[1][column] + Board[2][column]) == -3)
return -1;
if( (Board[0][column] + Board[1][column] + Board[2][column]) == 3)
return 1;
}
return 0;
}
public int checkDiagonals(){
if( (Board[0][0] + Board[1][1] + Board[2][2]) == -3)
return -1;
if( (Board[0][0] + Board[1][1] + Board[2][2]) == 3)
return 1;
if( (Board[0][2] + Board[1][1] + Board[2][0]) == -3)
return -1;
if( (Board[0][2] + Board[1][1] + Board[2][0]) == 3)
return 1;
return 0;
}
public boolean fullBoard(){
for(int line=0 ; line<3 ; line++)
for(int column=0 ; column<3 ; column++)
if( Board[line][column]==0 )
return false;
return true;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.