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!
*/