-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBoard.java
More file actions
82 lines (64 loc) · 2.53 KB
/
Board.java
File metadata and controls
82 lines (64 loc) · 2.53 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
public class Board {
public final char[] arr;
public Board() {
this.arr = new char[9];
for (int x = 1; x <= 9; x++) {
this.arr[x - 1] = ' ';
}
}
public void setArr(int position, char player) {
if (player == 'X') {
this.arr[position-1] = 'X';
} else {
this.arr[position -1] = 'O';
}
}
public void printBoard() {
System.out.format("%-3c ! %-3c ! %-3c\n----+----+----\n%-3c ! %-3c ! %-3c\n----+----+----\n%-3c ! %-3c ! %-3c\n",
this.arr[0], this.arr[1], this.arr[2], this.arr[3], this.arr[4], this.arr[5], this.arr[6], this.arr[7], this.arr[8]
);
}
/**
* @param x
* @return the value of the char at a given position
*/
public char getBoardValue(int x) {
return arr[x-1];
}
/**
* Go through the board and check for win (horizontal, diagonal, vertical)
* @param player
* @return whether a win has occurred
*/
public boolean checkWin(char player) {
if(this.arr[0] == player && this.arr[1] == player && this.arr[2] == player)
return true;
if(this.arr[3] == player && this.arr[4] == player && this.arr[5] == player)
return true;
if(this.arr[6] == player && this.arr[7] == player && this.arr[8] == player)
return true;
if(this.arr[0] == player && this.arr[4] == player && this.arr[8] == player)
return true;
if(this.arr[2] == player && this.arr[4] == player && this.arr[6] == player)
return true;
if(this.arr[0] == player && this.arr[3] == player && this.arr[6] == player)
return true;
if(this.arr[1] == player && this.arr[4] == player && this.arr[7] == player)
return true;
return this.arr[2] == player && this.arr[5] == player && this.arr[8] == player;
}
public boolean checkDraw() {
if(!this.checkWin('X') && !this.checkWin('O')) {
return this.getBoardValue(1) != ' ' && this.getBoardValue(2) != ' ' && this.getBoardValue(3) != ' ' && this.getBoardValue(4) != ' ' && this.getBoardValue(5) != ' ' && this.getBoardValue(6) != ' ' && this.getBoardValue(7) != ' ' && this.getBoardValue(8) != ' ' && this.getBoardValue(9) != ' ';
}
return false;
}
/**
* Reset the board
*/
public void clear() {
for (int x = 1; x <= 9; x++) {
this.arr[x - 1] = ' ';
}
}
}