73 lines
2.2 KiB
Java
73 lines
2.2 KiB
Java
package uulm.teamname.marvelous.gamelibrary.gamelogic;
|
|
|
|
import uulm.teamname.marvelous.gamelibrary.events.Event;
|
|
import uulm.teamname.marvelous.gamelibrary.requests.Request;
|
|
|
|
import java.util.ArrayDeque;
|
|
import java.util.ArrayList;
|
|
|
|
/** Represents manager for a game state. */
|
|
class GameStateManager {
|
|
/** The managed {@link GameState} */
|
|
private final GameState state;
|
|
|
|
/** The queue of {@link Event}s to be applied during {@link Request} processing */
|
|
private final ArrayDeque<Event> queue = new ArrayDeque<Event>();
|
|
|
|
/**
|
|
* Constructs a new {@link GameStateManager}.
|
|
* @param state A reference to the state to be managed
|
|
*/
|
|
public GameStateManager(GameState state) {
|
|
this.state = state;
|
|
}
|
|
|
|
/**
|
|
* Checks a list of {@link Request}s for validity and optionally produces resulting {@link Event}s.
|
|
* @param requests The requests to check
|
|
* @param apply True if resulting events should be stored for later application
|
|
*/
|
|
public boolean processRequests(Request[] requests, boolean apply) {
|
|
GameState snapshot = state.snapshot();
|
|
|
|
for(Request request: requests) {
|
|
if (GameLogic.checkRequest(snapshot, request)) {
|
|
ArrayList<Event> result = GameLogic.executeRequest(snapshot, request);
|
|
if(apply) {
|
|
queue.addAll(result);
|
|
}
|
|
}else {
|
|
queue.clear();
|
|
return false;
|
|
}
|
|
}
|
|
|
|
return true;
|
|
}
|
|
|
|
/**
|
|
* Applies an array of {@link Event}s to the game state.
|
|
* @param events The events to apply
|
|
*/
|
|
public void applyEvents(Event[] events) {
|
|
for(Event event: events) {
|
|
GameLogic.applyEvent(state, event);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Applies the result of the last processRequests call.
|
|
* @return A list of applied events
|
|
*/
|
|
public Event[] apply() {
|
|
Event[] toReturn = new Event[queue.size()];
|
|
Event current;
|
|
int i = 0;
|
|
while ((current = queue.poll()) != null) {
|
|
GameLogic.applyEvent(state, current);
|
|
toReturn[i++] = current;
|
|
}
|
|
return toReturn;
|
|
}
|
|
}
|