-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEventScheduler.java
74 lines (57 loc) · 1.73 KB
/
EventScheduler.java
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
import java.util.*;
/*
EventScheduler: ideally our way of controlling what happens in our virtual world
*/
final class EventScheduler
{
private final PriorityQueue<Event> eventQueue;
private final Map<Entity, List<Event>> pendingEvents;
private final double timeScale;
public EventScheduler(double timeScale)
{
this.eventQueue = new PriorityQueue<>(new EventComparator());
this.pendingEvents = new HashMap<>();
this.timeScale = timeScale;
}
public void removePendingEvent(Event event)
{
List<Event> pending = this.pendingEvents.get(event.getEntity());
if (pending != null)
{
pending.remove(event);
}
}
public void unscheduleAllEvents(Entity entity)
{
List<Event> pending = this.pendingEvents.remove(entity);
if (pending != null)
{
for (Event event : pending)
{
this.eventQueue.remove(event);
}
}
}
public void updateOnTime(long time)
{
while (!this.eventQueue.isEmpty() &&
this.eventQueue.peek().getTime() < time)
{
Event next = this.eventQueue.poll();
this.removePendingEvent(next);
next.getAction().executeAction(this);
}
}
public void scheduleEvent(Entity entity, Action action, long afterPeriod)
{
long time = System.currentTimeMillis() +
(long)(afterPeriod * this.timeScale);
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);
}
}