-
Notifications
You must be signed in to change notification settings - Fork 0
/
game_framework.py
119 lines (85 loc) · 2.39 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
import time
frame_time = 0.0
frame_count = 0
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):
print("State [%s] handle_events" % self.name)
def update(self):
print("State [%s] update" % self.name)
def draw(self):
print("State [%s] draw" % self.name)
running = None
stack = None
def change_state(state):
global stack
if (len(stack) > 0):
# execute the current state's exit function
stack[-1].exit()
# remove the current state
stack.pop()
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 quit():
global running
running = False
def run(start_state):
global running, stack
running = True
stack = [start_state]
start_state.enter()
global frame_time
global frame_count
current_time = time.time()
while (running):
stack[-1].handle_events()
stack[-1].update()
stack[-1].draw()
frame_time = time.time() - current_time
frame_rate = 1.0 / frame_time
current_time += frame_time
frame_count += 1
frame_count = frame_count%100
# repeatedly delete the top of the stack
while (len(stack) > 0):
stack[-1].exit()
stack.pop()
def test_game_framework():
start_state = TestGameState('image\StartState')
run(start_state)
if __name__ == '__main__':
test_game_framework()