-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEventScheduler.java
More file actions
63 lines (50 loc) · 1.82 KB
/
EventScheduler.java
File metadata and controls
63 lines (50 loc) · 1.82 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
import java.util.*;
/**
* Keeps track of events that have been scheduled.
*/
public final class EventScheduler {
private PriorityQueue<Event> eventQueue;
private Map<Entities, List<Event>> pendingEvents;
private double currentTime;
public EventScheduler() {
this.eventQueue = new PriorityQueue<>(new EventComparator());
this.pendingEvents = new HashMap<>();
this.currentTime = 0;
}
public void scheduleEvent(Entities entity, Action action, double afterPeriod) {
double time = this.currentTime + afterPeriod;
Event event = new Event(action, time, entity);
this.eventQueue.add(event);
// update list of pending events for the given entity
List<Event> pending = this.pendingEvents.getOrDefault(entity, new LinkedList<>());
pending.add(event);
this.pendingEvents.put(entity, pending);
}
public double getCurrentTime(){
return this.currentTime;
}
public void updateOnTime(double time) {
double stopTime = this.currentTime + time;
while (!this.eventQueue.isEmpty() && this.eventQueue.peek().time <= stopTime) {
Event next = this.eventQueue.poll();
removePendingEvent( next);
this.currentTime = next.time;
next.action.executeAction(this);
}
this.currentTime = stopTime;
}
public void unscheduleAllEvents(Entities entity) {
List<Event> pending = this.pendingEvents.remove(entity);
if (pending != null) {
for (Event event : pending) {
this.eventQueue.remove(event);
}
}
}
private void removePendingEvent(Event event) {
List<Event> pending = this.pendingEvents.get(event.entity);
if (pending != null) {
pending.remove(event);
}
}
}