-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBoard.java
More file actions
108 lines (85 loc) · 2.45 KB
/
Board.java
File metadata and controls
108 lines (85 loc) · 2.45 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
class Board {
private int size;
private int count;
private char[][] board;
Board() {}
Board (int n) {
size = n;
count = n * n;
this.board = new char[n][n];
}
public void setSize(int n) {
size = n;
}
// 0 means updated, 1 means won, 2 means draw, 3 means invalid move
public int move(int x, int y, User user) {
if (!isValid(x, y)) {
printBoard();
System.out.println("Invalid move! "+ x + " " + y);
return 3;
}
board[x][y] = user.getMove();
this.count--;
printBoard();
if (userWon(user, x, y)) {
System.out.println(user.getName() + " won the game, well played!");
return 1;
}
if (count==0) {
System.out.println("The result is a draw!");
return 2;
}
return 0;
}
private boolean userWon(User user ,int x ,int y) {
boolean rowWin = true;
// row check
for(int i = 0; i < size; i++) {
if (board[x][i] != user.getMove()) {
rowWin = false;
}
}
boolean colWin = true;
for(int i = 0; i < size; i++) {
if (board[i][y] != user.getMove()) {
colWin = false;
}
}
boolean diagWin1 = true;
for(int i = 0; i < size; i++) {
if (board[i][i] != user.getMove()) {
diagWin1 = false;
}
}
boolean diagWin2 = true;
for(int i = 0; i < size; i++) {
if(board[i][size-i-1] != user.getMove()) {
diagWin2 = false;
}
}
if(colWin || rowWin || diagWin1 || diagWin2) {
return true;
}
return false;
}
private boolean isValid(int x, int y) {
if(x < 0 || x >= size || y < 0 || y >= size || (int)(board[x][y]) !=0 ) {
return false;
}
System.out.println();
return true;
}
private void printBoard() {
System.out.println("-----------");
for(int i=0; i<size; i++){
for(int j=0; j<size; j++){
if(((int)board[i][j]) != 0)
System.out.print(" "+ board[i][j] +" ");
else
System.out.print(" - ");
}
System.out.println();
}
System.out.println("-----------");
}
}