-
Notifications
You must be signed in to change notification settings - Fork 7
/
tic_tac_toe
82 lines (72 loc) · 2.44 KB
/
tic_tac_toe
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
81
82
//new contribution
import java.util.Scanner;
public class TicTacToe {
private static char[][] board = new char[3][3];
private static char currentPlayer = 'X';
private static boolean gameWon = false;
public static void main(String[] args) {
initializeBoard();
printBoard();
while (!gameWon) {
play();
printBoard();
checkWin();
switchPlayer();
}
if (gameWon) {
System.out.println("Player " + currentPlayer + " wins!");
} else {
System.out.println("It's a draw!");
}
}
private static void initializeBoard() {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
board[i][j] = ' ';
}
}
}
private 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-------------");
}
}
private static void play() {
Scanner scanner = new Scanner(System.in);
int row, col;
do {
System.out.print("Player " + currentPlayer + ", enter row (1-3) and column (1-3): ");
row = scanner.nextInt() - 1;
col = scanner.nextInt() - 1;
} while (row < 0 || row > 2 || col < 0 || col > 2 || board[row][col] != ' ');
board[row][col] = currentPlayer;
}
private static void switchPlayer() {
currentPlayer = (currentPlayer == 'X') ? 'O' : 'X';
}
private static void checkWin() {
// Check rows, columns, and diagonals
for (int i = 0; i < 3; i++) {
if (board[i][0] == currentPlayer && board[i][1] == currentPlayer && board[i][2] == currentPlayer) {
gameWon = true;
return;
}
if (board[0][i] == currentPlayer && board[1][i] == currentPlayer && board[2][i] == currentPlayer) {
gameWon = true;
return;
}
}
if (board[0][0] == currentPlayer && board[1][1] == currentPlayer && board[2][2] == currentPlayer) {
gameWon = true;
return;
}
if (board[0][2] == currentPlayer && board[1][1] == currentPlayer && board[2][0] == currentPlayer) {
gameWon = true;
}
}
}