-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTictactoe.java
More file actions
75 lines (66 loc) · 1.91 KB
/
Tictactoe.java
File metadata and controls
75 lines (66 loc) · 1.91 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
import java.util.Scanner;
class Tictactoe {
public static void main(String[] args) {
char[][] board = new char[3][3];
for (int r = 0; r < board.length; r++) {
for (int c = 0; c < board[r].length; c++) {
board[r][c] = ' ';
}
}
char player = 'X';
Scanner sc = new Scanner(System.in);
int count=0;
while (count<9) {
printBoard(board);
System.out.print("Player " + player + " enter: ");
int r = sc.nextInt();
int c = sc.nextInt();
System.out.println();
if (board[r][c] == ' ') {
board[r][c] = player; // place the element
if (haveWon(board, player)) {
System.out.println("Player " + player + " has won: ");
break;
}
else if(count==9){
System.out.println("draw");
}
else {
count++;
player = (player == 'X') ? 'O' : 'X';
continue;
}
} else {
System.out.println("Invalid move. Try again!");
}
}
printBoard(board);
}
public static boolean haveWon(char[][] board, char player) {
for (int r = 0; r < board.length; r++) {
if (board[r][0] == player && board[r][1] == player && board[r][2] == player) {
return true;
}
}
for (int c = 0; c < board[0].length; c++) {
if (board[0][c] == player && board[1][c] == player && board[2][c] == player) {
return true;
}
}
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;
}
public static void printBoard(char[][] board) {
for (int r = 0; r < board.length; r++) {
for (int c = 0; c < board[r].length; c++) {
System.out.print(board[r][c] + " | ");
}
System.out.println();
}
}
}