Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,943 questions

55,787 answers

573 users

How to write the Tic-Tac-Toe game in Java

1 Answer

0 votes
import java.util.Scanner;

/**
    A simple Tic‑Tac‑Toe game written in Java.

    Highlights:
      - The board is represented as a char[] of length 9.
      - Functions handle printing, move validation, win checking,
        and turn progression.
      - The game loop is straightforward and easy to follow.
      - Comments explain the reasoning behind each part of the program.
*/

public class TicTacToe {

    // Print the board in a 3×3 layout
    static void printBoard(char[] board) {
        System.out.println();
        for (int i = 0; i < 9; i++) {
            System.out.print(board[i]);
            if ((i + 1) % 3 == 0)
                System.out.println();
            else
                System.out.print(" | ");
        }
        System.out.println();
    }

    // Check if a player has won
    static boolean checkWin(char[] board, char player) {
        int[][] wins = {
            {0,1,2}, {3,4,5}, {6,7,8},   // rows
            {0,3,6}, {1,4,7}, {2,5,8},   // columns
            {0,4,8}, {2,4,6}             // diagonals
        };

        for (int[] w : wins) {
            if (board[w[0]] == player &&
                board[w[1]] == player &&
                board[w[2]] == player)
                return true;
        }
        return false;
    }

    // Check if the board is full (draw)
    static boolean boardFull(char[] board) {
        for (char c : board) {
            if (c == ' ')
                return false;
        }
        return true;
    }

    // Attempt to place a move; return true if successful
    static boolean placeMove(char[] board, int pos, char player) {
        if (pos < 0 || pos >= 9)
            return false;

        if (board[pos] != ' ')
            return false;

        board[pos] = player;
        return true;
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);

        // Board initialized with spaces
        char[] board = new char[9];
        for (int i = 0; i < 9; i++)
            board[i] = ' ';

        char currentPlayer = 'X';

        System.out.println("Tic-Tac-Toe");
        printBoard(board);

        while (true) {
            System.out.print("Player " + currentPlayer + ", enter position (0-8): ");
            int pos = in.nextInt();

            // Try to place the move
            if (!placeMove(board, pos, currentPlayer)) {
                System.out.println("Invalid move. Try again.");
                continue;
            }

            printBoard(board);

            // Check win
            if (checkWin(board, currentPlayer)) {
                System.out.println("Player " + currentPlayer + " wins!");
                break;
            }

            // Check draw
            if (boardFull(board)) {
                System.out.println("It's a draw!");
                break;
            }

            // Switch player
            currentPlayer = (currentPlayer == 'X') ? 'O' : 'X';
        }

        in.close();
    }
}



/*
run:

Tic-Tac-Toe

  |   |  
  |   |  
  |   |  

Player X, enter position (0-8): 4

  |   |  
  | X |  
  |   |  

Player O, enter position (0-8): 
5

  |   |  
  | X | O
  |   |  

Player X, enter position (0-8): 3

  |   |  
X | X | O
  |   |  

Player O, enter position (0-8): 5
Invalid move. Try again.
Player O, enter position (0-8): 8

  |   |  
X | X | O
  |   | O

Player X, enter position (0-8): 7

  |   |  
X | X | O
  | X | O

Player O, enter position (0-8): 1

  | O |  
X | X | O
  | X | O

Player X, enter position (0-8): 
3
Invalid move. Try again.
Player X, enter position (0-8): 4
Invalid move. Try again.
Player X, enter position (0-8): 0

X | O |  
X | X | O
  | X | O

Player O, enter position (0-8): 2

X | O | O
X | X | O
  | X | O

Player O wins!

*/

 



answered 5 days ago by avibootz
...