-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcli.java
59 lines (50 loc) · 1.99 KB
/
cli.java
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
import java.util.Scanner;
public class TicTacToe {
private static char[][] board = {{' ', ' ', ' '}, {' ', ' ', ' '}, {' ', ' ', ' '}};
private static char currentPlayer = 'X';
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (!isGameOver()) {
System.out.println("Current board:");
printBoard();
System.out.println("Player " + currentPlayer + ", enter your move (row[1-3] column[1-3]): ");
int row = scanner.nextInt() - 1;
int col = scanner.nextInt() - 1;
if (row >= 0 && row < 3 && col >= 0 && col < 3 && board[row][col] == ' ') {
board[row][col] = currentPlayer;
currentPlayer = (currentPlayer == 'X') ? 'O' : 'X';
} else {
System.out.println("Invalid move. Try again.");
}
}
System.out.println("Current board:");
printBoard();
char winner = (currentPlayer == 'X') ? 'O' : 'X';
System.out.println("Player " + winner + " wins!");
}
private static boolean isGameOver() {
for (int i = 0; i < 3; i++) {
if (board[i][0] == board[i][1] && board[i][1] == board[i][2] && board[i][0] != ' ') {
return true;
}
if (board[0][i] == board[1][i] && board[1][i] == board[2][i] && board[0][i] != ' ') {
return true;
}
}
if (board[0][0] == board[1][1] && board[1][1] == board[2][2] && board[0][0] != ' ') {
return true;
}
if (board[0][2] == board[1][1] && board[1][1] == board[2][0] && board[0][2] != ' ') {
return true;
}
return false;
}
private static void printBoard() {
for (int i = 0; i < 3; i++) {
System.out.println(" " + board[i][0] + " | " + board[i][1] + " | " + board[i][2]);
if (i != 2) {
System.out.println("---|---|---");
}
}
}
}