-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtask2.java
More file actions
91 lines (80 loc) · 2.66 KB
/
Copy pathtask2.java
File metadata and controls
91 lines (80 loc) · 2.66 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
81
82
83
84
85
86
87
88
89
90
91
import java.util.Scanner;
public class task2 {
private static char[][] board = new char[3][3];
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
initializeBoard();
displayBoard();
char currentPlayer = 'X';
boolean gameWon = false;
while (!gameWon && !isBoardFull()) {
playerMove(currentPlayer);
displayBoard();
gameWon = checkWin(currentPlayer);
if (!gameWon) {
currentPlayer = (currentPlayer == 'X') ? 'O' : 'X';
}
}
if (gameWon) {
System.out.println("Player " + currentPlayer + " wins!");
} else {
System.out.println("It's a tie!");
}
scanner.close();
}
private static void initializeBoard() {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
board[i][j] = '-';
}
}
}
private static void displayBoard() {
System.out.println("Current board:");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
System.out.print(board[i][j] + " ");
}
System.out.println();
}
}
private static void playerMove(char player) {
int row, col;
while (true) {
System.out.println("Player " + player + ", enter your move (row and column): ");
row = scanner.nextInt() - 1;
col = scanner.nextInt() - 1;
if (row >= 0 && row < 3 && col >= 0 && col < 3 && board[row][col] == '-') {
board[row][col] = player;
break;
} else {
System.out.println("This move is not valid");
}
}
}
private static boolean checkWin(char player) {
// Check rows and columns
for (int i = 0; i < 3; i++) {
if ((board[i][0] == player && board[i][1] == player && board[i][2] == player) ||
(board[0][i] == player && board[1][i] == player && board[2][i] == player)) {
return true;
}
}
// Check diagonals
if ((board[0][0] == player && board[1][1] == player && board[2][2] == player) ||
(board[0][2] == player && board[1][1] == player && board[2][0] == player)) {
return true;
}
return false;
}
private 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;
}
}