- Home
- Archives forJuly 2023
Certainly! Here's a simple implementation of the Tic Tac Toe game in Java:
```java
import java.util.Scanner;
public class TicTacToe {
private char[][] board;
private char currentPlayer;
private boolean gameWon;
public TicTacToe() {
board = new char[3][3];
currentPlayer = 'X';
gameWon = false;
initializeBoard();
}
public void initializeBoard() {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
board[i][j] = '-';
}
}
}
public 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();
System.out.println("-------------");
}
}
public void playGame() {
Scanner scanner = new Scanner(System.in);
while (!gameWon) {
System.out.println("Player " + currentPlayer + "'s turn.");
System.out.print("Enter row (0-2): ");
int row = scanner.nextInt();
System.out.print("Enter column (0-2): ");
int col = scanner.nextInt();
if (isValidMove(row, col)) {
board[row][col] = currentPlayer;
printBoard();
if (checkWin(row, col)) {
System.out.println("Player " + currentPlayer + " wins!");
gameWon = true;
} else if (isBoardFull()) {
System.out.println("It's a tie!");
gameWon = true;
} else {
currentPlayer = (currentPlayer == 'X') ? 'O' : 'X';
}
} else {
System.out.println("Invalid move! Please try again.");
}
}
scanner.close();
}
public boolean isValidMove(int row, int col) {
if (row < 0 || row >= 3 || col < 0 || col >= 3) {
return false;
}
return board[row][col] == '-';
}
public boolean checkWin(int row, int col) {
// Check row
if (board[row][0] == board[row][1] && board[row][1] == board[row][2]) {
return true;
}
// Check column
if (board[0][col] == board[1][col] && board[1][col] == board[2][col]) {
return true;
}
// Check diagonals
if (board[0][0] == board[1][1] && board[1][1] == board[2][2] && board[1][1] != '-') {
return true;
}
if (board[0][2] == board[1][1] && board[1][1] == board[2][0] && board[1][1] != '-') {
return true;
}
return false;
}
public boolean isBoardFull() {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (board[i][j] == '-') {
return false;
}
}
}
return true;
}
public static void main(String[] args) {
TicTacToe game = new TicTacToe();
game.playGame();
}
}
```
To play the game, simply run the `main` method. Players will take turns entering the row and column numbers to place their mark ('X' or 'O') on the board. The game will continue until a player wins or the board is full, resulting in a tie.
