In this post, you will learn how to write the Tic-Tac-Toe Game in Java. Tic-Tac-Toe, also known as “Noughts and Crosses” in some regions, is an iconic and timeless two-player game that has been captivating players of all ages for generations. This simple yet engaging game is played on a 3×3 grid, and its objective is to form a line of three matching symbols (either X or O) horizontally, vertically, or diagonally. Despite its apparent simplicity, Tic-Tac-Toe involves critical thinking, strategy, and anticipation, making it a perfect pastime for players of all skill levels.
A Quick Recap of the Rules:
Tic-Tac-Toe is played on a square grid, usually 3×3, where two players take turns marking empty cells with their respective symbols – ‘X’ for one player and ‘O’ for the other. The first player to create a row, column, or diagonal of three matching symbols wins the game. If all cells are filled without any player achieving a winning combination, the game ends in a draw.
Gameplay Overview:
The game begins with an empty grid, and the first player, traditionally using ‘X,’ starts by placing their symbol in any vacant cell. The second player, using ‘O,’ then makes their move, and the turns continue to alternate until a winner is declared or a draw is reached.
Tic-Tac-Toe Game Program Logic Building
Let’s go through the Tic-Tac-Toe program’s logic step by step:
- The program starts by importing the required classes and defining the main class (
TicTacToeGame
) where the game logic will be implemented. - We create a 2D array (
board
) to represent the Tic-Tac-Toe grid. This array will store the positions and movements of the X and O symbols during the game. - The
initializeBoard
method is used to set all elements of theboard
array to'-'
, representing empty positions on the grid. - The
printBoard
method is used to display the current state of the Tic-Tac-Toe board to the players. - The
isValidMove
method checks if a move made by a player is valid. It ensures that the selected row and column are within the range of the board (0-2) and that the chosen position is empty. - The
checkWin
method checks if the current player has won the game. It examines the rows, columns, and diagonals to see if there are three symbols in a row that belong to the same player (either ‘X’ or ‘O’). - The
isBoardFull
method checks if the entire board is filled with symbols, which means the game has ended in a tie. - Inside the
main
method, we initialize theboard
, set the current player as ‘X’, and start the game loop. - The game loop continues until someone wins or the board is full (tie).
- In each iteration of the loop, we display the current state of the board and ask the current player to enter their move by specifying the row and column numbers.
- The program checks if the move is valid using the
isValidMove
method. If it is, the program updates the board with the current player’s symbol at the chosen position. - After updating the board, the program checks if the current player has won using the
checkWin
method. If so, the game loop is terminated, and the current player is declared the winner. - If the board is full and no player has won, the program declares a tie and ends the game loop.
- If the game loop continues, the current player is switched (from ‘X’ to ‘O’ or vice versa), and the next iteration starts.
- The game ends, and the program terminates when there is a winner or a tie.
Java Program for Tic Tac Toe Game
package com.javacodepoint.games;
import java.util.Scanner;
public class TicTacToeGame {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
char[][] board = new char[3][3];
char currentPlayer = 'X';
initializeBoard(board);
while (true) {
printBoard(board);
System.out.println("Player " + currentPlayer + ", enter row (1-3) and column (1-3) separated by space: ");
int row = scanner.nextInt() - 1;
int col = scanner.nextInt() - 1;
if (isValidMove(board, row, col)) {
board[row][col] = currentPlayer;
if (checkWin(board, currentPlayer)) {
printBoard(board);
System.out.println("Player " + currentPlayer + " wins!");
break;
}
if (isBoardFull(board)) {
printBoard(board);
System.out.println("It's a tie!");
break;
}
currentPlayer = (currentPlayer == 'X') ? 'O' : 'X';
} else {
System.out.println("Invalid move! Try again.");
}
}
scanner.close();
}
private static void initializeBoard(char[][] board) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
board[i][j] = '-';
}
}
}
private static void printBoard(char[][] board) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
System.out.print(board[i][j] + " ");
}
System.out.println();
}
}
private static boolean isValidMove(char[][] board, int row, int col) {
return (row >= 0 && row < 3 && col >= 0 && col < 3 && board[row][col] == '-');
}
private static boolean checkWin(char[][] board, char player) {
for (int i = 0; i < 3; i++) {
if (board[i][0] == player && board[i][1] == player && board[i][2] == player) {
return true; // Check rows
}
if (board[0][i] == player && board[1][i] == player && board[2][i] == player) {
return true; // Check columns
}
}
return (board[0][0] == player && board[1][1] == player && board[2][2] == player) || // Check diagonals
(board[0][2] == player && board[1][1] == player && board[2][0] == player);
}
private static boolean isBoardFull(char[][] board) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (board[i][j] == '-') {
return false;
}
}
}
return true;
}
}
Conclusion
In this post, you have seen the Tic tac toe game program in Java example. Tic-Tac-Toe is more than just a simple game; it is a symbol of timeless entertainment and a testament to the power of strategy and critical thinking.
See also: Generating OTP in Java. | Search Matrix. | Pattern programs [Tricks]