Java
Java

 

 

Introduction and Objective

The goal of this project is to create a simple console-based Tic-Tac-Toe game using Java. This game will allow two players to take turns and play the game on a 3×3 grid, with the objective to get three of their marks (either ‘X’ or ‘O’) in a row, column, or diagonal.
The game will display the current board after every move and will announce the winner when a player achieves three consecutive marks.

Code: Java Tic-Tac-Toe Game

        import java.util.Scanner;

        public class TicTacToe {
            static char[][] board = new char[3][3];
            static char currentPlayer = 'X';
            static boolean gameWon = false;
            
            public static void main(String[] args) {
                initializeBoard();
                displayBoard();
                
                while (!gameWon) {
                    playerMove();
                    displayBoard();
                    checkWinner();
                    switchPlayer();
                }
            }
            
            // Initialize the Tic-Tac-Toe board
            public static void initializeBoard() {
                for (int i = 0; i < 3; i++) {
                    for (int j = 0; j < 3; j++) {
                        board[i][j] = ' ';
                    }
                }
            }
            
            // Display the current state of the board
            public static void displayBoard() {
                System.out.println("-------------");
                for (int i = 0; i < 3; i++) {
                    System.out.print("| ");
                    for (int j = 0; j < 3; j++) { System.out.print(board[i][j] + " | "); } System.out.println(); System.out.println("-------------"); } } // Handle the player's move public static void playerMove() { Scanner scanner = new Scanner(System.in); int row, col; System.out.println("Player " + currentPlayer + "'s turn."); while (true) { System.out.print("Enter row (0-2): "); row = scanner.nextInt(); System.out.print("Enter column (0-2): "); col = scanner.nextInt(); if (row >= 0 && row < 3 && col >= 0 && col < 3 && board[row][col] == ' ') {
                        board[row][col] = currentPlayer;
                        break;
                    } else {
                        System.out.println("Invalid move. Try again.");
                    }
                }
            }
            
            // Switch the player after each move
            public static void switchPlayer() {
                if (currentPlayer == 'X') {
                    currentPlayer = 'O';
                } else {
                    currentPlayer = 'X';
                }
            }
            
            // Check if there is a winner
            public static void checkWinner() {
                // Check rows, columns, and diagonals for a winner
                for (int i = 0; i < 3; i++) {
                    if (board[i][0] == currentPlayer && board[i][1] == currentPlayer && board[i][2] == currentPlayer ||
                        board[0][i] == currentPlayer && board[1][i] == currentPlayer && board[2][i] == currentPlayer) {
                        gameWon = true;
                        System.out.println("Player " + currentPlayer + " wins!");
                        return;
                    }
                }
                if (board[0][0] == currentPlayer && board[1][1] == currentPlayer && board[2][2] == currentPlayer ||
                    board[0][2] == currentPlayer && board[1][1] == currentPlayer && board[2][0] == currentPlayer) {
                    gameWon = true;
                    System.out.println("Player " + currentPlayer + " wins!");
                }
            }
        }

Explanation of the Program Structure

The program is divided into the following components:

  • initializeBoard(): Initializes the 3×3 Tic-Tac-Toe board with empty spaces (‘ ‘).
  • displayBoard(): Displays the current state of the Tic-Tac-Toe board on the console.
  • playerMove(): Handles a player’s move by taking the row and column input and placing the player’s mark (‘X’ or ‘O’) on the board.
  • switchPlayer(): Switches the current player after each move.
  • checkWinner(): Checks if the current player has won the game by checking all rows, columns, and diagonals.

The game continues until one of the players wins or if there are no more available moves (in which case, the game ends in a draw).

How to Run the Program

  1. Copy the provided Java code into a text editor or Integrated Development Environment (IDE) like Eclipse or IntelliJ IDEA.
  2. Save the file with the name TicTacToe.java.
  3. Open a terminal or command prompt.
  4. Navigate to the directory where you saved the file.
  5. Compile the Java file using the following command:
    javac TicTacToe.java
  6. Run the program using the following command:
    java TicTacToe
  7. The game will start, and you can begin playing by entering the row and column positions.

Sample Output

Here is a sample output of the game:

        -------------
        |   |   |   | 
        -------------
        |   |   |   | 
        -------------
        |   |   |   | 
        -------------
        
        Player X's turn.
        Enter row (0-2): 1
        Enter column (0-2): 1
        -------------
        |   |   |   | 
        -------------
        |   | X |   | 
        -------------
        |   |   |   | 
        -------------
        
        Player O's turn.
        Enter row (0-2): 0
        Enter column (0-2): 0
        -------------
        | O |   |   | 
        -------------
        |   | X |   | 
        -------------
        |   |   |   | 
        -------------
        ...

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)