-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcode.java
More file actions
57 lines (45 loc) · 1.79 KB
/
Copy pathcode.java
File metadata and controls
57 lines (45 loc) · 1.79 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
import java.util.Scanner;
public class TicTacToe {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
char[][] board = {
{' ', ' ', ' '},
{' ', ' ', ' '},
{' ', ' ', ' '}
};
char player = 'X';
boolean gameOver = false;
while (!gameOver) {
System.out.println("\nCurrent Board:");
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("--+---+--");
}
System.out.print("Player " + player + " enter row and column (0-2): ");
int row = sc.nextInt();
int col = sc.nextInt();
if (row < 0 || row > 2 || col < 0 || col > 2 || board[row][col] != ' ') {
System.out.println("Invalid move! Try again.");
continue;
}
board[row][col] = player;
// Check rows, columns, diagonals
for (int i = 0; i < 3; i++) {
if (board[i][0] == player && board[i][1] == player && board[i][2] == player)
gameOver = true;
if (board[0][i] == player && board[1][i] == player && board[2][i] == player)
gameOver = true;
}
if (board[0][0] == player && board[1][1] == player && board[2][2] == player)
gameOver = true;
if (board[0][2] == player && board[1][1] == player && board[2][0] == player)
gameOver = true;
if (gameOver) {
System.out.println("Player " + player + " wins!");
break;
}
player = (player == 'X') ? 'O' : 'X';
}
sc.close();
}
}