-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathevents.py
95 lines (75 loc) · 2.75 KB
/
events.py
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
# events.py
# ---------
# Licensing Information: You are free to use or extend these projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to UC Berkeley, including a link to http://ai.berkeley.edu.
#
# Attribution Information: The Pacman AI projects were developed at UC Berkeley.
# The core projects and autograders were primarily created by John DeNero
# ([email protected]) and Dan Klein ([email protected]).
# Student side autograding was added by Brad Miller, Nick Hay, and
# Pieter Abbeel ([email protected]).
import bisect
class EventQueue:
"""
Implements the event queue for Pacman games.
Currently uses a slow list implementation (not a heap) so that
equality checking is easy.
"""
def __init__(self):
self.sortedEvents = []
def registerEventAtTime(self, event, time):
assert isinstance(event, Event)
entry = (time, event)
index = bisect.bisect_right(self.sortedEvents, entry)
self.sortedEvents.insert(index, entry)
def peek(self):
assert self.sortedEvents, "Error: Peek on an empty EventQueue"
return self.sortedEvents[0]
def pop(self):
assert self.sortedEvents, "Error: Pop on an empty EventQueue"
return self.sortedEvents.pop(0)
def isEmpty(self):
return len(self.sortedEvents) == 0
def getSortedTimesAndEvents(self):
return self.sortedEvents
def deepCopy(self):
result = EventQueue()
result.sortedEvents = [(t, e.deepCopy()) for t, e in self.sortedEvents]
return result
def __hash__(self):
return hash(tuple(self.sortedEvents))
def __eq__(self, other):
return hasattr(other, 'sortedEvents') and \
self.sortedEvents == other.sortedEvents
def __str__(self):
ansStr = "["
for (t,e) in self.sortedEvents:
if(e.isAgentMove):
ansStr+= "(t = " + str(t) + ", " + str(e) + ")"
return ansStr+"]"
class Event:
"""
An abstract class for an Event. All Events must have a trigger
method which performs the actions of the Event.
"""
nextId = 0
def __init__(self, prevId=None):
if prevId is None:
self.eventId = Event.nextId
Event.nextId += 1
else:
self.eventId = prevId
def trigger(self, state):
util.raiseNotDefined()
def isAgentMove(self):
return False
def deepCopy(self):
util.raiseNotDefined()
def __eq__( self, other ):
util.raiseNotDefined()
def __hash__( self ):
util.raiseNotDefined()
def __lt__(self, other):
return self.eventId < other.eventId