Java Project – Tic Tac Toe Game
Get Job-ready: Java Course with 45+ Real-time Projects! - Learn Java
Program 1
import java.util.Scanner;
public class TicTacToe {
static char[][] board = {
{' ', ' ', ' '},
{' ', ' ', ' '},
{' ', ' ', ' '}
};
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
char currentPlayer = 'X';
boolean gameEnded = false;
System.out.println("Welcome to Tic Tac Toe!");
printBoard();
while (!gameEnded) {
System.out.println("Player " + currentPlayer + ", enter your move (row and column: 1-3): ");
int row = scanner.nextInt() - 1;
int col = scanner.nextInt() - 1;
// Check for valid input
if (row < 0 || col < 0 || row > 2 || col > 2) {
System.out.println("Invalid position. Try again.");
continue;
}
if (board[row][col] != ' ') {
System.out.println("Cell already taken. Try again.");
continue;
}
board[row][col] = currentPlayer;
printBoard();
// Check for a winner
if (checkWin(currentPlayer)) {
System.out.println("Player " + currentPlayer + " wins!");
gameEnded = true;
} else if (isBoardFull()) {
System.out.println("It's a draw!");
gameEnded = true;
} else {
// Switch players
currentPlayer = (currentPlayer == 'X') ? 'O' : 'X';
}
}
scanner.close();
}
// Method to print the board
public static void printBoard() {
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("\n-------------");
}
}
// Method to check for win
public static boolean checkWin(char player) {
// Check rows and columns
for (int i = 0; i < 3; i++) {
if (
(board[i][0] == player && board[i][1] == player && board[i][2] == player) ||
(board[0][i] == player && board[1][i] == player && board[2][i] == player) )
{
return true;
}
}
// Check diagonals
if (
(board[0][0] == player && board[1][1] == player && board[2][2] == player) ||
(board[0][2] == player && board[1][1] == player && board[2][0] == player) )
{
return true;
}
return false;
}
// Method to check if board is full
public 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;
}
}
Did you like this article? If Yes, please give DataFlair 5 Stars on Google

