In: Computer Science
In a game of Tic Tac Toe, two players take turns making an available cell in a 3 x 3 grid with their respective tokens (either X or O). When one player has placed three tokens in a horizontal, vertical, or diagonal row on the grid, the game is over and that player has won. A stalemate occurs when all the cells on the grid have been filled with tokens and neither player has achieved a win.
Write a program in Java that emulates a Tic Tac Toe game.
When you are done, a typical session will look like this:
Welcome to tic-tac-toe. Enter coordinates for your move following the X and O prompts. 1 2 3 A | | ----- B | | ----- C | | X:A2 1 2 3 A |X| ----- B | | ----- C | | O:B3 1 2 3 A |X| ----- B | |O ----- C | |
And so on. Illegal moves will prompt the user again for a new move. A win or a stalemate will be announced, mentioning the winning side if any. The program will terminate whenever a single game is complete.
This file has the general framework of the TicTacToe class. An object of this class will represent a tic-tac-toe "board". The board will be represented internally by a two dimensional array of characters (3 x 3), and by a character indicating who's turn it is ('X' or 'O'). These are stored in the class instance variables as follows.
private char[][] board; private char player; // 'X' or 'O'
You will need to define the following methods:
1. A constructor:
public TicTacToe()
to create an empty board, with initial value of a space (' ')
2. play method
public play(String position)
if position represents a valid move (e.g., A1, B3), add the current player's symbol to the board and return true. Otherwise, return false.
3. switchTurn method
public void switchTurn()
switches the current player from X to O, or vice versa.
4. won method
public boolean won()
Returns true if the current player has filled three in a row, column or either diagonal. Otherwise, return false.
5. stalemate method
public boolean stalemate()
Returns true if there are no places left to move;
6. printBoard method
public void printBoard()
prints the current board
7. Use the following test code in your main method to create a TicTacToe object and print it using the printBoard method given, so as to test your code. Your printBoard method should produce the first board in the example above.
public static void main(String[] args) { Scanner in = new Scanner(System.in); TicTacToe game = new TicTacToe(); System.out.println("Welcome to Tic-tac-toe"); System.out.println("Enter coordinates for your move following the X and O prompts"); while(!game.stalemate()) { game.printBoard(); System.out.print(game.getPlayer() + ":"); //Loop while the method play does not return true when given their move. //Body of loop should ask for a different move while(!game.play(in.next())) { System.out.println("Illegal move. Enter your move."); System.out.print(game.getPlayer() + ":"); } //If the game is won, call break; if(game.won()) break; game.printBoard(); //Switch the turn game.switchTurn(); } game.printBoard(); if(game.won()) { System.out.println("Player "+game.getPlayer()+" Wins!!!!"); } else { System.out.println("Stalemate"); } }
// TicTacToe.java : Java program to allow user to playe Tic Tac
Toe Game involving 2 players
import java.util.Scanner;
public class TicTacToe {
private char[][] board;
private char player; // 'X' or 'O'
// create an empty tic tac board and set starting
player to X
public TicTacToe()
{
board = new char[3][3];
for(int
i=0;i<board.length;i++)
for(int
j=0;j<board[i].length;j++)
board[i][j] = ' ';
player = 'X';
}
// If position represents a valid move (e.g., A1, B3),
add the current player's symbol
// to the board and return true. Otherwise, return
false.
public boolean play(String position)
{
position = position.trim(); //
remove white space if any
// check length of position is
2
if(position.length() == 2)
{
// get the
character for row an column
char row =
position.charAt(0);
char col =
position.charAt(1);
// convert
character to integer
int rowNum =
(int)(row-'A');
int colNum =
(int)(col-'1');
// check if
valid range and the position is not occupied
if(rowNum >=0
&& rowNum < 3 && colNum >=0 && colNum
< 3 && board[rowNum][colNum] == ' ')
{
// if valid and free space, set player to that
space and return true
board[rowNum][colNum] = player;
return true;
}
}
return false; // invalid
}
// switches the current player from X to O, or vice
versa.
public void switchTurn()
{
if(player == 'X')
player =
'O';
else
player =
'X';
}
// Returns true if the current player has filled three
in a row, column or either diagonal. Otherwise, return false.
public boolean won()
{
// check row-wise and
column-wise
for(int i=0;i<3;i++)
{
if((board[i][0]
== board[i][1]) && (board[i][0] == board[i][2]))
if(board[i][0] == player)
return true;
if((board[0][i]
== board[1][i]) && (board[0][i] == board[2][i]))
if(board[0][i] == player)
return true;
}
// check main diagonal
if((board[0][0] == board[1][1] )
&& (board[1][1] == board[2][2]))
if(board[0][0]
== player)
return true;
// check other diagonal
if((board[0][2] == board[1][1])
&& (board[1][1] == board[2][0]))
if(board[1][1]
== player)
return true;
return false;
}
//Returns true if there are no places left to
move;
public boolean stalemate()
{
for(int
i=0;i<board.length;i++)
{
for(int
j=0;j<board[i].length;j++)
if(board[i][j] == ' ')
return false;
}
return true;
}
// prints the current board
public void printBoard()
{
System.out.println();
System.out.printf("%3s","");
for(int
i=0;i<board.length;i++)
{
System.out.printf(" %d ",i+1);
}
for(int
i=0;i<board.length;i++)
{
System.out.printf("\n%3c",'A'+i);
for(int
j=0;j<board[i].length;j++)
{
if(j < board[i].length-1)
System.out.printf("
%c|",board[i][j]);
else
System.out.printf("
%c",board[i][j]);
}
if(i <
board.length-1)
System.out.printf("\n%3s---------","");
}
System.out.println("\n");
}
// method to return the current player
public char getPlayer()
{
return player;
}
public static void main(String[] args) {
// test the class
Scanner in = new
Scanner(System.in);
TicTacToe game = new TicTacToe();
System.out.println("Welcome to Tic-tac-toe");
System.out.println("Enter coordinates for your move
following the X and O prompts");
while(!game.stalemate())
{
game.printBoard();
System.out.print(game.getPlayer() + ":");
//Loop while the method play does not return true
when given their move.
//Body of loop should ask for a different move
while(!game.play(in.next()))
{
System.out.println("Illegal move. Enter your
move.");
System.out.print(game.getPlayer() + ":");
}
//If the game is won, call break;
if(game.won())
break;
//game.printBoard();
//Switch the turn
game.switchTurn();
}
game.printBoard();
if(game.won())
{
System.out.println("Player "+game.getPlayer()+"
Wins!!!!");
}
else
{
System.out.println("Stalemate");
}
}
}
//end of program
Output: