-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEventScheduler.java
67 lines (54 loc) · 1.57 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
import java.util.*;
final class EventScheduler
{
private PriorityQueue<Event> eventQueue;
private Map<WorldEntity, List<Event>> pendingEvents;
private double timeScale;
public EventScheduler(double timeScale)
{
this.eventQueue = new PriorityQueue<>(new EventComparator());
this.pendingEvents = new HashMap<>();
this.timeScale = timeScale;
}
public void updateOnTime(long time)
{
while (!eventQueue.isEmpty() &&
eventQueue.peek().getTime() < time)
{
Event next = eventQueue.poll();
removePendingEvent(next);
next.getAction().executeAction(this);
}
}
private void removePendingEvent(Event event)
{
List<Event> pending = pendingEvents.get(event.getEntity());
if (pending != null)
{
pending.remove(event);
}
}
public void unscheduleAllEvents(WorldEntity entity)
{
List<Event> pending = pendingEvents.remove(entity);
if (pending != null)
{
for (Event event : pending)
{
eventQueue.remove(event);
}
}
}
public void scheduleEvent(ActiveEntity entity, Action action, long afterPeriod)
{
long time = System.currentTimeMillis() +
(long)(afterPeriod * timeScale);
Event event = new Event(action, time, entity);
eventQueue.add(event);
// update list of pending events for the given entity
List<Event> pending = pendingEvents.getOrDefault(entity,
new LinkedList<>());
pending.add(event);
pendingEvents.put(entity, pending);
}
}