-
Notifications
You must be signed in to change notification settings - Fork 0
/
game_framework.py
123 lines (84 loc) · 2.4 KB
/
game_framework.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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
import time
font = None
class GameState:
def __init__(self, state):
self.enter = state.enter
self.exit = state.exit
self.pause = state.pause
self.resume = state.resume
self.handle_events = state.handle_events
self.update = state.update
self.draw = state.draw
class TestGameState:
def __init__(self, name):
self.name = name
def enter(self):
print("State [%s] Entered" % self.name)
def exit(self):
print("State [%s] Exited" % self.name)
def pause(self):
print("State [%s] Paused" % self.name)
def resume(self):
print("State [%s] Resumed" % self.name)
def handle_events(self, frame_time):
print("State [%s] handle_events(%f)" % (self.name, frame_time))
def update(self, frame_time):
print("State [%s] update(%f)" % (self.name, frame_time))
def draw(self, frame_time):
print("State [%s] draw(%f)" % (self.name, frame_time))
running = None
stack = None
def change_state(state):
global stack
pop_state()
stack.append(state)
state.enter()
def push_state(state):
global stack
if (len(stack) > 0):
stack[-1].pause()
stack.append(state)
state.enter()
def pop_state():
global stack
if (len(stack) > 0):
# execute the current state's exit function
stack[-1].exit()
# remove the current state
stack.pop()
# execute resume function of the previous state
if (len(stack) > 0):
stack[-1].resume()
def get_top_state():
global stack
if (len(stack) > 0):
return stack[-1]
def quit():
global running
running = False
def restart():
change_state(stack[-1])
def run(start_state):
global running, stack
running = True
stack = [start_state]
start_state.enter()
current_time = time.clock()
while (running):
frame_time = time.clock() - current_time
current_time += frame_time
stack[-1].handle_events(frame_time)
stack[-1].update(frame_time)
stack[-1].draw(frame_time)
# repeatedly delete the top of the stack
while (len(stack) > 0):
stack[-1].exit()
stack.pop()
def reset_time():
global current_time
current_time = time.clock()
def test_game_framework():
start_state = TestGameState('StartState')
run(start_state)
if __name__ == '__main__':
test_game_framework()