-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHumanPlayer.java
More file actions
36 lines (29 loc) · 1 KB
/
HumanPlayer.java
File metadata and controls
36 lines (29 loc) · 1 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
public class HumanPlayer implements Player {
public boolean play(TicTacToe game) {
if(game.numRounds == game.numRows*game.numColumns){
throw new IllegalArgumentException("Game is finished already!");
}
boolean success = false;
while(!success) {
System.out.println(game);
System.out.print(game.nextPlayer() + " to play: ");
String answer = Utils.readLine();
int value;
try {
value = Integer.parseInt(answer)-1;
} catch (NumberFormatException e) {
value = -1;
}
if(value < 0 || value >= (game.numRows*game.numColumns)){
System.out.println("The value should be between 1 and"
+ (game.numRows*game.numColumns));
} else if(game.valueAt(value) != CellValue.EMPTY) {
System.out.println("This cell has already been played");
} else {
game.play(value);
success = true;
}
}
return success;
}
}