Java
Java

 

Introduction

Tic-Tac-Toe is a classic game that involves two players taking turns to place their marks (X or O) on a 3×3 grid. The goal is to get three of your marks in a row, column, or diagonal. While traditionally played by two human players, enhancing the game with a simple AI opponent can make the game more interesting for solo players.

In this example, we will write a Java program to create an enhanced version of the Tic-Tac-Toe game where one player competes against a simple AI opponent. The AI will make moves based on basic logic, such as blocking the opponent’s winning move or choosing the center or corners of the grid for optimal play.

Objective

The objective of this program is to create a playable Tic-Tac-Toe game with the following features:

  • Two players: one human player and one AI opponent.
  • Simple AI logic: the AI will block winning moves or make random valid moves.
  • Display the game board after each move, allowing players to visualize the game state.

Code

import java.util.Random;
import java.util.Scanner;

public class TicTacToeWithAI {

    private static char[][] board = new char[3][3];
    private static char currentPlayer = 'X'; // Human is X, AI is O
    private static char aiPlayer = 'O';
    private static char humanPlayer = 'X';

    public static void main(String[] args) {
        initializeBoard();
        printBoard();
        
        while (true) {
            playerMove();
            if (isWinner(humanPlayer)) {
                printBoard();
                System.out.println("You win!");
                break;
            }
            if (isBoardFull()) {
                printBoard();
                System.out.println("It's a tie!");
                break;
            }
            
            aiMove();
            if (isWinner(aiPlayer)) {
                printBoard();
                System.out.println("AI wins!");
                break;
            }
            if (isBoardFull()) {
                printBoard();
                System.out.println("It's a tie!");
                break;
            }
        }
    }

    private static void initializeBoard() {
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                board[i][j] = ' ';
            }
        }
    }

    private static void printBoard() {
        System.out.println("Current board:");
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                System.out.print(board[i][j]);
                if (j < 2) System.out.print("|");
            }
            System.out.println();
            if (i < 2) System.out.println("-----"); } } private static void playerMove() { Scanner sc = new Scanner(System.in); int row, col; while (true) { System.out.println("Enter row (0-2) and column (0-2) for your move:"); row = sc.nextInt(); col = sc.nextInt(); if (row >= 0 && row < 3 && col >= 0 && col < 3 && board[row][col] == ' ') {
                board[row][col] = humanPlayer;
                break;
            } else {
                System.out.println("Invalid move, try again.");
            }
        }
    }

    private static void aiMove() {
        Random rand = new Random();
        int row, col;
        while (true) {
            row = rand.nextInt(3);
            col = rand.nextInt(3);
            if (board[row][col] == ' ') {
                board[row][col] = aiPlayer;
                System.out.println("AI's move:");
                break;
            }
        }
    }

    private static boolean isBoardFull() {
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                if (board[i][j] == ' ') {
                    return false;
                }
            }
        }
        return true;
    }

    private static boolean isWinner(char player) {
        // Check rows, columns, and diagonals
        for (int i = 0; i < 3; i++) {
            if (board[i][0] == player && board[i][1] == player && board[i][2] == player)
                return true;
            if (board[0][i] == player && board[1][i] == player && board[2][i] == player)
                return true;
        }
        if (board[0][0] == player && board[1][1] == player && board[2][2] == player)
            return true;
        if (board[0][2] == player && board[1][1] == player && board[2][0] == player)
            return true;
        return false;
    }
}

Program Explanation

This Java program works as follows:

  • The game board is represented by a 3×3 array of characters. Initially, all positions are set to a space character (‘ ‘), indicating that they are empty.
  • The game alternates between the human player (X) and the AI player (O). The playerMove() method handles the human player’s move, while the aiMove() method handles the AI’s move. The AI picks a random available position on the board.
  • After each move, the program checks for a winner using the isWinner() method, which checks all rows, columns, and diagonals for three matching symbols.
  • The isBoardFull() method checks if the board is full, indicating a tie if no winner is found.
  • The game continues in a loop until there is a winner or the board is full, at which point the game ends and a message is displayed indicating whether the human player won, the AI won, or if it was a tie.

How to Run the Program

To run this program, follow these steps:

  1. Save the program code in a file named TicTacToeWithAI.java.
  2. Open a terminal or command prompt and navigate to the directory containing the file.
  3. Compile the program using the Java compiler:
    javac TicTacToeWithAI.java
  4. Run the compiled program:
    java TicTacToeWithAI
  5. The game will start, and you will play as the human player (X) against the AI (O). The board will be displayed after each move, and the game will end when there is a winner or a tie.
© 2024 Learn Programming

 

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 :)