This repository was archived by the owner on Feb 6, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathGame.py
More file actions
109 lines (95 loc) · 3.15 KB
/
Game.py
File metadata and controls
109 lines (95 loc) · 3.15 KB
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
#!/usr/bin/py
# -*- coding: utf-8 -*-
import pygame as pg
import Events as evs
from Enums import GameEnum as sub
from GameStates import StateStack
import pickle as pic
class Game:
"""
Main engine class responsible for event handling,rendering and running game states
"""
def __init__(self, screen, start_state):
"""
Game engine initialization
:param screen: pygame display
:param start_state: name of starting state class
"""
self.finish = False
self.screen = screen
self.clock = pg.time.Clock()
self.fps = 60
self.state_stack = StateStack()
self.state_stack.push(start_state())
def event_loop(self):
"""
Handles all events
"""
for event in pg.event.get():
if event.type is evs.EngineEvent:
if event.sub is sub.StateCallEvent:
self.state_stack.push(event.state(event.args))
self.state_stack.set_persistent(event.args)
elif event.sub is sub.StateExitEvent:
self.state_stack.pop()
self.state_stack.send_callback(event.args)
elif event.sub is sub.StackResetEvent:
self.state_stack.reset()
elif event.sub is sub.GameSaveEvent:
self.save_game(event.path)
elif event.sub is sub.GameLoadEvent:
self.load_game(event.path)
else:
self.state_stack.get_event(event)
def update(self, dt):
"""
Handles active state update
:param dt: time in millis since last frame
"""
self.state_stack.update(dt)
if self.state_stack.peek().quit:
self.finish = True
def draw(self):
"""
Pass display to active state for drawing
"""
self.state_stack.peek().draw(self.screen)
def save_game(self, path):
"""
Save current game state in file
:param path: string - path to game save file
"""
try:
file = open(path, "wb")
for i in self.state_stack.states:
i.on_save()
pic.dump(self.state_stack, file)
for i in self.state_stack.states:
i.on_load()
except IOError or pic.PicklingError as e:
print("Game save error: {}".format(e))
def load_game(self, path):
"""
Load game state from file
:param path: string - path to game save file
"""
temp_stack = self.state_stack
try:
file = open(path, 'rb')
self.state_stack = pic.load(file)
for i in self.state_stack.states:
i.on_load()
del temp_stack
except IOError or pic.UnpicklingError as e:
print("Game load error: {}".format(e))
self.state_stack = temp_stack
def run(self):
"""
Main game loop
"""
while not self.finish:
dt = self.clock.tick(self.fps)
self.event_loop()
self.update(dt)
self.draw()
pg.display.update()