-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathGame.java
More file actions
53 lines (48 loc) · 1.46 KB
/
Game.java
File metadata and controls
53 lines (48 loc) · 1.46 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
package ticTacToe;
/**
* @author Georgiy Korneev (kgeorgiy@kgeorgiy.info)
*/
public class Game {
private final boolean log;
private final Player[] players;
public Game(final boolean log, final Player... players) {
this.log = log;
// if (players.length != 4) {
// throw new IllegalArgumentException("4 players needed");
// }
this.players = players;
}
public int play(Board board) {
while (true) {
for (int i = 0; i < players.length; i++) {
final int result = move(board, players[i], i);
if (result != -1) {
return result;
}
}
}
}
private int move(final Board board, final Player player, final int no) {
final Move move = player.move(board.getPosition(), board.getCell());
final Result result = board.makeMove(move);
log("Player " + no + " move: " + move);
log("Position:\n" + board);
if (result == Result.WIN) {
log("Player " + no + " won");
return no + 1;
} else if (result == Result.LOSE) {
log("Player " + no + " lose");
return 4 - no;
} else if (result == Result.DRAW) {
log("Draw");
return 0;
} else {
return -1;
}
}
private void log(final String message) {
if (log) {
System.out.println(message);
}
}
}