This repository has been archived by the owner on Dec 4, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TicTacToe.java
89 lines (76 loc) · 2.69 KB
/
TicTacToe.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
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
package hw;
import java.util.Arrays;
import java.util.Objects;
import java.util.Scanner;
public class TicTacToe {
private char[][] board;
private char currentPlayer;
public String printBoard() {
StringBuilder result = new StringBuilder();
for (int i = 0; i < 3; i++) {
result.append("| ");
for (int j = 0; j < 3; j++) {
result.append(board[i][j]).append(" | ");
}
result.append("\n");
}
return result.toString();
}
public TicTacToe(char currentPlayer) {
board = new char[3][3];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
board[i][j] = ' ';
}
}
this.currentPlayer = currentPlayer;
}
public boolean move(int row, int col, boolean override) {
if (override || board[row][col] == ' ') {
board[row][col] = currentPlayer;
currentPlayer = (currentPlayer == 'X') ? 'O' : 'X';
return true;
}
return false;
}
public boolean checkPossiblePattern(char[] pattern) {
return Arrays.equals(pattern, new char[]{'X', 'X', 'X'}) || Arrays.equals(pattern, new char[]{'O', 'O', 'O'});
}
public boolean checkRow(int row) {
return checkPossiblePattern(board[row]);
}
public boolean checkColumn(int col) {
return checkPossiblePattern(new char[]{board[0][col], board[1][col], board[2][col]});
}
public boolean checkDiagonal() {
return checkPossiblePattern(new char[]{board[0][0], board[1][1], board[2][2]}) || checkPossiblePattern(new char[]{board[0][2], board[1][1], board[2][0]});
}
public char checkWin() {
boolean win = false;
for (int i = 0; i < 3; i++) {
if (checkRow(i) || checkColumn(i)) {
win = true;
break;
}
}
if (!win) {win = checkDiagonal();}
return win ? (currentPlayer == 'X' ? 'O' : 'X') : ' ';
}
public static void main(String[] args) {
TicTacToe game = new TicTacToe('X');
Scanner kb = new Scanner(System.in);
while (game.checkWin() == ' ') {
System.out.println("Current player: " + game.currentPlayer);
System.out.println(game.printBoard());
System.out.print("Enter the row: ");
int row = kb.nextInt();
System.out.print("Enter the column: ");
int col = kb.nextInt();
if (!game.move(row, col, false)) {
System.out.println("Invalid move");
}
}
System.out.println(game.printBoard());
System.out.println("Winner: " + game.checkWin());
}
}