-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTicTacToe.java
More file actions
115 lines (89 loc) · 3.08 KB
/
Copy pathTicTacToe.java
File metadata and controls
115 lines (89 loc) · 3.08 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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
import java.util.Scanner;
public class TicTacToe {
static char[][] board = {
{'1', '2', '3'},
{'4', '5', '6'},
{'7', '8', '9'}
};
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
char playAgain;
do {
resetBoard();
playGame();
System.out.print("\nDo you want to play again? (Y/N): ");
playAgain = sc.next().charAt(0);
} while (playAgain == 'Y' || playAgain == 'y');
System.out.println("Thanks for playing!");
sc.close();
}
static void playGame() {
char currentPlayer = 'X';
int moves = 0;
while (true) {
printBoard();
System.out.print("Player " + currentPlayer + ", enter your move (1-9): ");
int move = sc.nextInt();
if (placeMove(move, currentPlayer)) {
moves++;
if (checkWinner(currentPlayer)) {
printBoard();
System.out.println("Player " + currentPlayer + " wins!");
break;
}
if (moves == 9) {
printBoard();
System.out.println("It's a draw!");
break;
}
currentPlayer = (currentPlayer == 'X') ? 'O' : 'X';
} else {
System.out.println("Invalid move! Try again.");
}
}
}
static void printBoard() {
System.out.println();
System.out.println(board[0][0] + " | " + board[0][1] + " | " + board[0][2]);
System.out.println("--+---+--");
System.out.println(board[1][0] + " | " + board[1][1] + " | " + board[1][2]);
System.out.println("--+---+--");
System.out.println(board[2][0] + " | " + board[2][1] + " | " + board[2][2]);
System.out.println();
}
static boolean placeMove(int move, char player) {
int row = (move - 1) / 3;
int col = (move - 1) % 3;
if (move >= 1 && move <= 9 && board[row][col] != 'X' && board[row][col] != 'O') {
board[row][col] = player;
return true;
}
return false;
}
static boolean checkWinner(char player) {
// Rows
for (int i = 0; i < 3; i++) {
if (board[i][0] == player && board[i][1] == player && board[i][2] == player)
return true;
}
// Columns
for (int i = 0; i < 3; i++) {
if (board[0][i] == player && board[1][i] == player && board[2][i] == player)
return true;
}
// Diagonals
if (board[0][0] == player && board[1][1] == player && board[2][2] == player)
return true;
if (board[0][2] == player && board[1][1] == player && board[2][0] == player)
return true;
return false;
}
static void resetBoard() {
char count = '1';
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
board[i][j] = count++;
}
}
}
}