-
Notifications
You must be signed in to change notification settings - Fork 1
/
state_machine.py
104 lines (89 loc) · 3.02 KB
/
state_machine.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
96
97
98
99
100
101
102
103
104
"""
Une machine a état générique. Utilisée pour le flow d'execution général du programme.
Source: https://github.com/Mekire/cabbages-and-kings
Copyright 2018, Sean J. McKiernan
"""
class StateMachine(object):
"""
Une machine à état générique
"""
def __init__(self):
self.done = False
self.state_dict = {}
self.state_name = None
self.state = None
self.now = None
def setup_states(self, state_dict, start_state):
"""
Given a dictionary of states and a state to start in,
creates the self.state_dict.
"""
self.state_dict = state_dict
self.state_name = start_state
self.state = self.state_dict[self.state_name]
def update(self, keys, now):
"""
Checks if a state is done or has called for a game quit.
State is flipped if neccessary and State.update is called.
"""
self.now = now
if self.state.quit:
self.done = True
elif self.state.done:
self.flip_state()
self.state.update(keys, now)
def draw(self, surface, interpolate):
self.state.draw(surface, interpolate)
def flip_state(self):
"""
When a State changes to done necessary startup and cleanup functions
are called and the current State is changed.
"""
previous, self.state_name = self.state_name, self.state.next
persist = self.state.cleanup()
self.state = self.state_dict[self.state_name]
self.state.startup(self.now, persist)
self.state.previous = previous
def get_event(self, event):
"""
Pass events down to current State.
"""
self.state.get_event(event)
class State(object):
"""
This is a prototype class for states. All states should inherit from it.
No direct instances of this class should be created. get_event and update
must be overloaded in the childclass. The startup and cleanup methods
need to be overloaded when there is data that must persist between states.
"""
def __init__(self):
self.start_time = 0.0
self.now = 0.0
self.done = False
self.quit = False
self.next = None
self.previous = None
self.persist = {}
def get_event(self, event):
"""
Processes events that were passed from the main event loop.
Must be overloaded in children.
"""
pass
def startup(self, now, persistant):
"""
Add variables passed in persistant to the proper attributes and
set the start time of the State to the current time.
"""
self.persist = persistant
self.start_time = now
def cleanup(self):
"""
Add variables that should persist to the self.persist dictionary.
Then reset State.done to False.
"""
self.done = False
return self.persist
def update(self, keys, now):
"""Update function for state. Must be overloaded in children."""
pass