-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBoard.java
More file actions
111 lines (102 loc) · 2.95 KB
/
Board.java
File metadata and controls
111 lines (102 loc) · 2.95 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
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
* Board Object
* Contains pieces. Has functions for printing board, setting pieces,
* etc.
*
*
* @author jkwong
*/
public class Board {
char [] grid = new char[9];
// default constructor
Board(){
// creat blank board
for (int i = 0; i < 9; i++){
grid[i] = ' '; // space
}
}
public void Print(){
// Indices:
// 0 1 2
// 3 4 5
// 6 7 8
System.out.println("-------");
for (int i = 0; i < 3; i++){
System.out.println("|" + String.valueOf(grid[i*3]) + "|" + String.valueOf(grid[i*3+1]) + "|" + String.valueOf(grid[i*3+2]) + "|");
// System.out.println(grid[i*3] + grid[i*3+1] + grid[i*3+2]);
System.out.println("-------");
}
}
public boolean CheckMove(int move){
System.out.println(grid[move]);
return(grid[move] == ' ');
}
public boolean SetMove(int move, char marker){
if (CheckMove(move)){
grid[move] = marker;
return(true);
} else {
System.out.println("Move Invalid.");
return(false);
}
}
public boolean[] FindMoves(){
boolean [] moves = {false, false, false, false, false, false, false, false, false};
for (int i = 0; i < 9; i++){
if (grid[i] == ' '){
moves[i] = true;
}
}
return(moves);
}
// checks to see if the game has ended
// returns ' ' if not over
// returns char of winner player
// returns '0' if game has ended with a tie
public char EndGame(){
char status;
// Check if the board is full
boolean temp = true;
for (int i = 0; i < 9; i++){
temp = temp & (grid[i] != ' ');
}
if (temp){
return('0');
}
// check horizontals
for (int i = 0; i < 3; i++){
if (grid[i*3] != ' '){
if ( (grid[i*3] == grid[i*3+1]) && (grid[i*3+1] == grid[i*3+2])){
status = grid[i*3];
return(status);
}
}
}
// check verticals
for (int i = 0; i < 3; i++){
if (grid[i] != ' '){
if ( (grid[i] == grid[i+3]) && (grid[i+3] == grid[i+6])){
status = grid[i];
return(status);
}
}
}
// check diagonals
if (grid[4] != ' '){
if ( (grid[0] == grid[4]) && (grid[4] == grid[8])){
status = grid[4];
return(status);
}
if ( (grid[2] == grid[4]) && (grid[4] == grid[6])){
status = grid[4];
return(status);
}
}
// game is not over yet
return(' ');
}
}