blob: b78bae49e77e1713c3b45623f3027846fd7de359 (
plain)
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
112
113
|
package fr.umlv.java.wallj.context;
import fr.umlv.java.wallj.board.Board;
import fr.umlv.java.wallj.event.ConfirmOrder;
import fr.umlv.java.wallj.event.Event;
import fr.umlv.java.wallj.event.Events;
import fr.umlv.java.wallj.event.QuitGameOrder;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Stream;
/**
* A game.
*
* @author Adam NAILI
*/
public final class Game implements Updateable {
private Stage currentStage;
private int indexBoard;
private final List<Board> boards;
private boolean over;
/**
* @param boards the list of boards charged for the game
*/
public Game(List<Board> boards) {
Objects.requireNonNull(boards);
if (boards.isEmpty()) {
throw new IllegalArgumentException("The list of boards is empty, not able to create a correct game from this.");
}
this.boards = Collections.unmodifiableList(boards);
this.indexBoard = 0;
this.currentStage = new Stage(this.boards.get(0));
this.over = false;
}
/**
* @return a boolean on the condition of having a next Board in our game.
*/
public boolean hasNextBoard() {
return indexBoard + 1 < boards.size();
}
/**
* @return the next board
*/
private Board nextBoard() {
if (!hasNextBoard()) {
throw new IllegalStateException("No more board for the game.");
}
indexBoard++;
return boards.get(indexBoard);
}
/**
* @return the current stage
*/
public Stage getCurrentStage() {
return currentStage;
}
public boolean isOver() {
return over;
}
public void setOver() {
over = true;
}
public void nextStage() {
if (hasNextBoard()) {
currentStage = new Stage(nextBoard());
}
}
public void retryStage() {
currentStage = new Stage(currentStage.getBoard());
}
private void goToNext() {
if (hasNextBoard()) { //continue
nextStage();
return;
}
setOver();
}
private void handleEvents(Context context) {
if (Events.findFirst(context.getEvents(), QuitGameOrder.class).isPresent()) {
context.getGame().setOver();
return;
}
if (Events.findFirst(context.getEvents(), ConfirmOrder.class).isPresent()) {
if (currentStage.isCleared()) {
goToNext();
return;
}
retryStage();
}
}
/**
* @param context the current context
* @return a list of new events
*/
@Override
public Stream<Event> update(Context context) {
handleEvents(context);
return currentStage.update(context);
}
}
|