-
Notifications
You must be signed in to change notification settings - Fork 0
/
TicTacToe.java
101 lines (99 loc) · 3.27 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
90
91
92
93
94
95
96
97
98
99
100
101
/*
* TicTacToe.java
* Constantine
* Feb.7, 2015
*/
package programmingactivities10;
import java.util.*;
/**
*
* @author 程博洋
*/
public class TicTacToe {
public static boolean checkRow(String[][] base, int rowNum) {
for (int i = 0; i < base.length - 1; i++) {
if (base[i][rowNum] != base[i + 1][rowNum] || base[i][rowNum] == null) {
return false;
}
}return true;
}
public static boolean checkColumn(String[][] base, int columnNum) {
for (int i = 0; i < base[0].length - 1; i++) {
if (base[columnNum][i] != base[columnNum][i + 1] || base[columnNum][i] == null) {
return false;
}
}return true;
}
public static boolean checkSlope(String[][]base, String XO) {
for (int i = 0; i < base[0].length - 1; i++) {
if (base[0][0] == base[1][1] && base[1][1] == base[2][2] && base[0][0] == XO) {
return true;
} else if (base[0][2] == base[1][1] && base[1][1] == base[2][0] && base[0][2] == XO) {
return true;
} else {
return false;
}
} return false;
}
public static boolean check(String[][] base) {
for (int i = 0; i < base.length; i++) {
if (checkRow(base, i) == true || checkColumn(base, i) == true) {
return true;
}
if (checkSlope(base, "X") == true) {
return true;
} else if (checkSlope(base, "O") == true) {
System.out.println("Winner is O");
return true;
}
}return false;
}
public static void change(String[][] base) {
for (int i = 0; i < base.length; i++) {
for (int a = 0; a < base[0].length; a++) {
if (base[a][i] == null) {
System.out.print("[ ]");
} else if (base[a][i] == "X") {
System.out.print("[X]");
} else {
System.out.print("[O]");
}
} System.out.print("\n");
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
String[][] base = new String[3][3];
Scanner sc = new Scanner(System.in);
int row, column;
change(base);
do {
do {
System.out.print("Enter row number: ");
row = sc.nextInt();
System.out.print("Enter column number: ");
column = sc.nextInt();
} while (base[row][column] != null);
base[row][column] = "X";
change(base);
if (check(base) == true) {
System.out.println("Winner is X");
break;
}
do {
System.out.print("Enter row number: ");
row = sc.nextInt();
System.out.print("Enter column number: ");
column = sc.nextInt();
} while (base[row][column] != null);
base[row][column] = "O";
change(base);
if (check(base) == true) {
System.out.println("Winner is O");
break;
}
} while (check(base) == false);
}
}