-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHumanPlayer.java
74 lines (68 loc) · 2.06 KB
/
HumanPlayer.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
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import static java.lang.System.in;
import static java.lang.System.out;
public class HumanPlayer extends Board implements Player {
char mark;
String name;
private final BufferedReader br;
HumanPlayer(String name, char mark, char[] board) {
super(board);
this.mark = mark;
this.name = name;
for (int i = 0; i < 9; i++)
availableMoves.add(i);
br = new BufferedReader(new InputStreamReader(in));
}
HumanPlayer(char mark, char[] board) {
super(board);
this.mark = mark;
name = mark == 'X' ? "Player1" : "Player2";
for (int i = 0; i < 9; i++)
availableMoves.add(i);
br = new BufferedReader(new InputStreamReader(in));
}
private int getInput() {
out.print("Enter the cell number (1-9) >> ");
try {
return Integer.parseInt(br.readLine().trim());
} catch (IOException ioe) {
return 0;
}
}
@Override
public void move() {
int cell = getInput();
while (cell < 1 || cell > 9) {
out.println("Please enter value from 1 to 9 only.");
cell = getInput();
}
while (!availableMoves.isEmpty() && board[cell - 1] != ' ') {
out.println("Cell is already occupied!!");
cell = getInput();
}
availableMoves.remove(cell - 1);
board[cell - 1] = this.mark;
moveCount++;
int r = (cell - 1) / 3, c = (cell - 1) % 3;
out.println(name + " played on " + String.format("cell[%d][%d].", r, c));
out.println(this);
if (hasWon()) {
out.println(name + " has won the game.");
Board.moveCount = INF;
Board.won = true;
}
}
@Override
public boolean hasWon() {
char[] b = board;
return (b[0] == mark && b[1] == mark && b[2] == mark) || (b[3] == mark && b[4] == mark && b[5] == mark)
|| (b[6] == mark && b[7] == mark && b[8] == mark) || (b[0] == mark && b[3] == mark && b[6] == mark)
|| (b[1] == mark && b[4] == mark && b[7] == mark) || (b[2] == mark && b[5] == mark && b[8] == mark)
|| (b[0] == mark && b[4] == mark && b[8] == mark) || (b[2] == mark && b[4] == mark && b[6] == mark);
}
public String toString() {
return super.getMove();
}
}