-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgame.py
281 lines (234 loc) Β· 9.36 KB
/
game.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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
"""game module: Contains main entrypoint for the game"""
from __future__ import annotations
# pylint: disable=R0902,R0912
import logging
import os
import sys
from datetime import datetime
import pygame
import pytmx
import pyscroll
import pyscroll.data
from pyscroll.group import PyscrollGroup
from pytmx.util_pygame import load_pygame
from Puzzles.konami_code import KonamiCode
from Puzzles.lever_combination import LeverCombination
from Puzzles.math import Math
from Puzzles.morse_code import MorseCode
from Puzzles.music import Music
from Puzzles.simon_says import SimonSays
from Screens.in_game import Ingame
from Screens.main_menu import MainMenu
from Screens.paused_menu import PausedMenu
from Screens.settings_menu import SettingsMenu
from colargulog import BraceFormatStyleFormatter, ColorizedArgsFormatter
from player import Player
from door_manager import DoorManager
from toast_manager import ToastManager
from enums import GameState, UserEvents, Skills
from constants import RESOURCES_DIR, PLAYER_MOVE_SPEED, PLAYER_RUN_SPEED
from utils import resource_path, initialize_screen
os.environ["PYGAME_HIDE_SUPPORT_PROMPT"] = "1"
def init_logging():
"""Initialize color and file logger.
"""
root_logger = logging.getLogger()
root_logger.setLevel(logging.DEBUG)
console_level = "DEBUG"
console_handler = logging.StreamHandler(stream=sys.stdout)
console_handler.setLevel(console_level)
console_format = "%(asctime)s - %(levelname)-8s - %(name)-25s - %(message)s"
colored_formatter = ColorizedArgsFormatter(console_format)
console_handler.setFormatter(colored_formatter)
root_logger.addHandler(console_handler)
file_handler = logging.FileHandler(
f"{datetime.now():%Y-%m-%d_%H-%M-%S}.log"
)
file_level = "DEBUG"
file_handler.setLevel(file_level)
file_format = "%(asctime)s - %(name)s (%(lineno)s) - %(levelname)-12s - %(message)s"
file_handler.setFormatter(BraceFormatStyleFormatter(file_format))
root_logger.addHandler(file_handler)
init_logging()
logger = logging.getLogger(__name__)
class Game:
"""Contains whole game state
"""
map_path = resource_path(RESOURCES_DIR / "map.tmx")
def __init__(self, screen: pygame.Surface) -> None:
self.screen = screen
self.running = False
self.game_state = GameState.MAIN_MENU
self.tmx_data = load_pygame(self.map_path)
self.player = Player(self)
spawn_obj = self.tmx_data.get_layer_by_name("spawn")[0]
self.player.position = (spawn_obj.x - spawn_obj.width / 2, spawn_obj.y)
# Create new renderer
self.map_layer = pyscroll.BufferedRenderer(
data=pyscroll.data.TiledMapData(self.tmx_data),
size=screen.get_size(),
clamp_camera=False,
zoom=2,
)
# Make Pyscroll group
self.group = PyscrollGroup(map_layer=self.map_layer, default_layer=50)
self.group.add(self.player)
self.toast_manager: ToastManager = ToastManager(self.screen)
self.door_manager: DoorManager = DoorManager(self)
self.puzzles = {
"simonsays": SimonSays(self),
"morsecode": MorseCode(self),
"math": Math(self),
"music": Music(self),
"levercombination": LeverCombination(self),
"konami": KonamiCode(self),
}
self.menus = {
"mainmenu": MainMenu(self),
"ingame": Ingame(self),
"settings": SettingsMenu(self),
"pausemenu": PausedMenu(self),
}
def draw(self) -> None:
"""Draws current active menu
"""
if self.game_state == GameState.MAIN_MENU:
self.menus["mainmenu"].draw(self.screen)
if self.game_state == GameState.SETTINGS:
self.menus["settings"].draw(self.screen)
if self.game_state == GameState.PAUSE_MENU:
self.menus["pausemenu"].draw(self.screen)
if self.game_state == GameState.IN_GAME:
self.menus["ingame"].draw(self.screen)
for puzzle in self.puzzles.values():
if puzzle.active:
puzzle.draw(self.screen)
self.toast_manager.draw(self.screen)
def handle_input(self) -> None:
"""Handle input for everything game related
- Movement
- Buttons
- Resizes
"""
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.running = False
break
if event.type == UserEvents.PAUSE_BLINK.value:
self.menus["pausemenu"].blink()
elif event.type == UserEvents.SIMON_SAYS_BLINK.value:
self.puzzles["simonsays"].next_color()
elif event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1 and self.game_state == GameState.MAIN_MENU:
self.menus["mainmenu"].handle_click(event.pos)
if event.button == 1 and self.game_state == GameState.PAUSE_MENU:
self.menus["pausemenu"].handle_click(event.pos)
elif event.type == pygame.KEYDOWN:
if (
event.key == pygame.K_ESCAPE
and self.game_state == GameState.MAIN_MENU
):
self.running = False
break
if (
event.key == pygame.K_ESCAPE and self.game_state == GameState.IN_GAME
):
self.game_state = GameState.PAUSE_MENU
elif (
event.key == pygame.K_ESCAPE
and self.game_state == GameState.PAUSE_MENU
):
self.game_state = GameState.MAIN_MENU
else:
if self.game_state == GameState.IN_GAME:
self.menus["ingame"].handle_input(event)
for puzzle in self.puzzles.values():
puzzle.handle_input(event)
elif event.type == pygame.VIDEORESIZE:
logger.info("Resizing screen to {}x{}", event.w, event.h)
self.screen = initialize_screen(event.w, event.h)
self.map_layer.set_size((event.w, event.h))
else:
if self.game_state == GameState.IN_GAME:
self.menus["ingame"].handle_input(event)
if self.game_state == GameState.IN_GAME:
pressed = pygame.key.get_pressed()
mods = pygame.key.get_mods()
if pressed[pygame.K_w]:
self.player.velocity[1] = (
-PLAYER_RUN_SPEED
if mods & pygame.KMOD_SHIFT and Skills.RUN in self.player.skills
else -PLAYER_MOVE_SPEED
)
elif pressed[pygame.K_s]:
self.player.velocity[1] = (
PLAYER_RUN_SPEED
if mods & pygame.KMOD_SHIFT and Skills.RUN in self.player.skills
else PLAYER_MOVE_SPEED
)
else:
self.player.velocity[1] = 0
if pressed[pygame.K_a]:
self.player.velocity[0] = (
-PLAYER_RUN_SPEED
if mods & pygame.KMOD_SHIFT and Skills.RUN in self.player.skills
else -PLAYER_MOVE_SPEED
)
elif pressed[pygame.K_d]:
self.player.velocity[0] = (
PLAYER_RUN_SPEED
if mods & pygame.KMOD_SHIFT and Skills.RUN in self.player.skills
else PLAYER_MOVE_SPEED
)
else:
self.player.velocity[0] = 0
def update(self, dt_: float) -> None:
"""Handle update cycle for everything game
Args:
dt_ (float): frame timedelta
"""
self.menus["ingame"].update(dt_)
for puzzle in self.puzzles.values():
if puzzle.active:
puzzle.update(dt_)
def run(self) -> None:
"""Run π The π Game π Loop π"""
clock = pygame.time.Clock()
self.running = True
try:
while self.running:
dt_ = clock.tick() / 1000.0
self.handle_input()
self.update(dt_)
self.draw()
pygame.display.flip()
except KeyboardInterrupt:
self.running = False
def main() -> None:
"""Main initialize function, only execute when `__main__`
"""
logger.debug("Python version: {}", str(sys.version))
logger.debug("Pygame version: {}", str(pygame.version.ver))
logger.debug("Pytmx version: {}", str(pytmx.__version__))
logger.debug("Pyscroll version: {}", str(pyscroll.__version__))
logger.debug("Current Process ID: {}", str(os.getpid()))
logger.debug("Current Parent Process ID: {}", str(os.getppid()))
pygame.init()
logger.info("Pygame initialized")
pygame.font.init()
logger.info("Pygame font module initialized")
pygame.mixer.init()
logger.info("Pygame mixer module initialized")
screen = initialize_screen(1280, 720)
logger.info("Initialized screen")
pygame.display.set_caption("Swish and Frick")
logger.debug("Set window title to: {}", str(pygame.display.get_caption()[0]))
try:
game = Game(screen)
game.run()
except KeyboardInterrupt:
pass
finally:
pygame.quit()
if __name__ == "__main__":
main()