-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEventScheduler.java
More file actions
64 lines (53 loc) · 1.84 KB
/
EventScheduler.java
File metadata and controls
64 lines (53 loc) · 1.84 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
54
55
56
57
58
59
60
61
62
63
64
import java.util.*;
/**
* Keeps track of events that have been scheduled.
*/
public final class EventScheduler {
private final PriorityQueue<Event> eventQueue;
private final Map<Entity, List<Event>> pendingEvents;
private double currentTime;
public EventScheduler() {
this.eventQueue = new PriorityQueue<>(new EventComparator());
this.pendingEvents = new HashMap<>();
this.currentTime = 0;
}
/**
* Unschedule all events for a given Entity.
* @param entity - the entity whose events we are removing.
*/
public void unscheduleAllEvents(Entity entity) {
List<Event> pending = pendingEvents.remove(entity);
if (pending != null) {
for (Event event : pending) {
eventQueue.remove(event);
}
}
}
public void updateOnTime(double time) {
double stopTime = currentTime + time;
while (!eventQueue.isEmpty() && eventQueue.peek().getTime() <= stopTime) {
Event next = eventQueue.poll();
removePendingEvent(next);
currentTime = next.getTime();
next.getAction().executeAction(this);
}
currentTime = stopTime;
}
private void removePendingEvent(Event event) {
List<Event> pending = pendingEvents.get(event.getEntity());
if (pending != null) {
pending.remove(event);
}
}
public void scheduleEvent(Entity entity, Action action, double afterPeriod) {
double time = currentTime + afterPeriod;
Event event = new Event(action, time, entity);
eventQueue.add(event);
List<Event> pending = pendingEvents.getOrDefault(entity, new LinkedList<>());
pending.add(event);
pendingEvents.put(entity, pending);
}
public double getCurrentTime() {
return currentTime;
}
}