-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathTicTacToe.java
More file actions
80 lines (68 loc) · 2.83 KB
/
TicTacToe.java
File metadata and controls
80 lines (68 loc) · 2.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
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 gameOn = true;
while (gameOn) {
printBoard();
System.out.println("Player " + currentPlayer + "'s turn. Enter row and column (1-3 for both): ");
int row = scanner.nextInt() - 1;
int col = scanner.nextInt() - 1;
if (row < 0 || col < 0 || row > 2 || col > 2 || board[row][col] != ' ') {
System.out.println("Invalid move, try again.");
continue;
}
board[row][col] = currentPlayer;
if (checkWinner(currentPlayer)) {
printBoard();
System.out.println("Player " + currentPlayer + " wins!");
gameOn = false;
} else if (isBoardFull()) {
printBoard();
System.out.println("The game is a draw!");
gameOn = false;
} else {
currentPlayer = (currentPlayer == 'X') ? 'O' : 'X';
}
}
scanner.close();
}
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();
System.out.println("-------------");
}
}
public static boolean checkWinner(char player) {
// Check rows, columns, and diagonals
return (board[0][0] == player && board[0][1] == player && board[0][2] == player) || // Row 1
(board[1][0] == player && board[1][1] == player && board[1][2] == player) || // Row 2
(board[2][0] == player && board[2][1] == player && board[2][2] == player) || // Row 3
(board[0][0] == player && board[1][0] == player && board[2][0] == player) || // Column 1
(board[0][1] == player && board[1][1] == player && board[2][1] == player) || // Column 2
(board[0][2] == player && board[1][2] == player && board[2][2] == player) || // Column 3
(board[0][0] == player && board[1][1] == player && board[2][2] == player) || // Diagonal 1
(board[0][2] == player && board[1][1] == player && board[2][0] == player); // Diagonal 2
}
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;
}
}