-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
279 lines (215 loc) · 10.6 KB
/
main.py
File metadata and controls
279 lines (215 loc) · 10.6 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
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
import sys
import pygame
import src.core.constants as c
from src.core.event_handler import EventHandler
from src.core.maze import Maze
from src.entities.lookout_tower import LookoutTower
from src.entities.player import Player
from src.entities.scarecrow import Scarecrow
from src.ui.menus import MenuManager
from src.ui.sidebar import Sidebar
class Game:
"""The main application class that manages game states, loops, and rendering."""
def __init__(self) -> None:
"""Initializes the Pygame engine, display settings, UI elements, and core managers."""
pygame.init()
self.screen = pygame.display.set_mode(
(c.LOGICAL_SCREEN_WIDTH, c.LOGICAL_SCREEN_HEIGHT),
pygame.RESIZABLE)
# Surface to draw everything on before scaling smoothly to the size of the screen:
self.virtual_surface = pygame.Surface((c.LOGICAL_SCREEN_WIDTH, c.LOGICAL_SCREEN_HEIGHT))
pygame.display.set_caption("Midnight Maize")
self.clock = pygame.time.Clock()
# Stack to keep track of the game state:
self.state_stack = [c.GameState.START_MENU]
self.large_font = pygame.font.Font(c.LARGE_FONT_PATH, 32)
self.small_font = pygame.font.Font(c.SMALL_FONT_PATH, 16)
# The ground:
self.ground_img = pygame.image.load(c.GRAPHICS_DIR / "ground.png").convert()
# The nightfall surface that goes over the maze:
self.nightfall = pygame.Surface((c.MAZE_WIDTH, c.MAZE_HEIGHT))
# This causes magenta to act like green in a green screen.
# It will appear transparent. This is for the circular cutouts
# in the nightfall surface:
self.nightfall.set_colorkey((255, 0, 255))
self.menus = MenuManager(self.large_font, self.small_font)
self.event_handler = EventHandler(self)
self.new_game()
self.running = True
@property
def state(self) -> c.GameState:
"""Gets the current active game state.
Returns:
c.GameState: The active state at the top of the state stack.
"""
return self.state_stack[-1]
def change_state(self, new_state: c.GameState) -> None:
"""Pushes a new state onto the state stack to make it active.
Args:
new_state (c.GameState): The state to transition to.
"""
self.state_stack.append(new_state)
def go_back(self) -> None:
"""Pops the current state from the stack, reverting to the previous state."""
if len(self.state_stack) > 1:
self.state_stack.pop()
def new_game(self, seed: str = None) -> None:
"""Initializes a new game session with a fresh maze and entities.
Args:
seed (str, optional): A specific map seed to use for generation. Defaults to None.
"""
self.maze = Maze(seed)
self.sidebar = Sidebar()
self.character_sprites = pygame.sprite.Group()
self.player = Player(self.maze.player_starting_position)
self.lookout_tower = LookoutTower(self.maze.lookout_tower_position)
self.scarecrow = Scarecrow(self.maze.scarecrow_starting_position)
self.character_sprites.add(self.lookout_tower)
self.character_sprites.add(self.scarecrow)
self.character_sprites.add(self.player)
self.glow_stick_sprites = pygame.sprite.Group()
self.glow_sticks_dropped = 0
self.start_ticks = pygame.time.get_ticks() # Get start time in ms
self.elapsed_ticks = 0
# Record when this specific game started.
# Used in pause screen to keep time paused:
self.last_frame_ticks = pygame.time.get_ticks()
# Instead of drawing the maze from scratch on every frame,
# create a Surface to put the maze on, and you can just
# blit the surface to the screen:
self.background_surface = pygame.Surface((c.MAZE_WIDTH, c.MAZE_HEIGHT))
self.background_surface.blit(self.ground_img, (0, 0))
# Draw the maze on top of the surface:
self.maze.draw(self.background_surface)
def handle_events(self) -> None:
"""Processes all input events through the EventHandler."""
self.event_handler.process_events()
def get_scaled_rect(self) -> pygame.Rect:
"""Calculates the size of the rect for the scaled virtual surface.
Returns:
pygame.Rect: The rect for the scaled virtual surface.
"""
window_width, window_height = self.screen.get_size()
width_scale = window_width / c.LOGICAL_SCREEN_WIDTH
height_scale = window_height / c.LOGICAL_SCREEN_HEIGHT
scale = min(width_scale, height_scale)
new_width = int(c.LOGICAL_SCREEN_WIDTH * scale)
new_height = int(c.LOGICAL_SCREEN_HEIGHT * scale)
# Center on self.screen:
return pygame.Rect(
(window_width - new_width) // 2,
(window_height - new_height) // 2,
new_width,
new_height)
def draw_screen(self) -> None:
"""Renders the game world, UI, and menus to the screen based on the active state."""
# Clear the virtual surface first:
self.virtual_surface.fill(c.BLACK)
# Always draw the game world in the background (except start menu):
if self.state != c.GameState.START_MENU:
self.virtual_surface.blit(self.background_surface, (0, 0))
self.character_sprites.draw(self.virtual_surface)
self.glow_stick_sprites.draw(self.virtual_surface)
# Fill the nightfall surface with a really dark blue:
self.nightfall.fill((5, 5, 12))
# Cut out a hole in the nightfall for the player.
# Magenta acts as green in a green screen:
pygame.draw.circle(
self.nightfall,
(255, 0, 255),
self.player.rect.center,
c.PLAYER_LIGHT_RADIUS)
# Also cut out holes in the nightfall for the glow sticks:
for glow_stick_sprite in self.glow_stick_sprites:
pygame.draw.circle(
self.nightfall,
(255, 0, 255),
glow_stick_sprite.rect.center,
c.GLOW_STICK_LIGHT_RADIUS)
# Draw the nightfall over the maze:
self.virtual_surface.blit(self.nightfall, (0, 0))
# Draw sidebar after nightfall is drawn so it stays on top:
self.sidebar.draw(self.virtual_surface, self.player, self.elapsed_ticks)
# Route the drawing based on the active state:
if self.state == c.GameState.START_MENU:
self.menus.draw_start_menu(self.virtual_surface)
elif self.state == c.GameState.PAUSED_MENU:
self.menus.draw_paused_menu(self.virtual_surface)
elif self.state == c.GameState.STORY_SCREEN:
self.menus.draw_story_screen(self.virtual_surface)
elif self.state == c.GameState.CONTROLS_SCREEN:
self.menus.draw_controls_screen(self.virtual_surface)
elif self.state == c.GameState.ENTER_SEED_SCREEN:
self.menus.draw_enter_seed_screen(self.virtual_surface)
elif self.state == c.GameState.CURRENT_SEED_SCREEN:
self.menus.draw_current_seed_screen(self.virtual_surface, self.maze.seed)
elif self.state == c.GameState.RESULTS_SCREEN:
self.menus.draw_results_screen(
self.virtual_surface,
self.last_result_won,
self.last_result_time_string,
self.last_result_sticks_used,
self.last_result_sticks_left,
self.maze.seed
)
# Clear the actual screen:
self.screen.fill(c.BLACK)
# Get the centered rect for the scaled virtual surface based on the current screen size:
dest_rect = self.get_scaled_rect()
# Scale the virtual surface up to the destination size:
scaled_frame = pygame.transform.scale(self.virtual_surface, dest_rect.size)
# Blit the scaled frame onto the physical screen at the centered position:
self.screen.blit(scaled_frame, dest_rect.topleft)
pygame.display.flip()
def update(self) -> None:
"""Updates the timing, game logic, and entities for the active frame."""
# Calculate how much time has passed since last loop:
current_ticks = pygame.time.get_ticks()
delta_time = current_ticks - self.last_frame_ticks
# Always update the last frame ticks, otherwise after
# unpausing, the time will include all the paused time:
self.last_frame_ticks = current_ticks
if self.state == c.GameState.PLAYING:
self.elapsed_ticks += delta_time
self.glow_stick_sprites.update()
self.player.update(self.maze)
self.scarecrow.update(self.maze, self.player)
# Lose condition:
if self.player.hitbox_rect.colliderect(self.scarecrow.hitbox_rect):
self.show_results(False)
# Win condition:
if self.player.hitbox_rect.colliderect(self.lookout_tower.rect):
self.show_results(True)
def show_results(self, won: bool) -> None:
"""Calculates final game statistics and transitions to the results screen.
Args:
won (bool): True if the player reached the lookout tower, False if caught by the scarecrow.
"""
# Calculate final stats:
total_seconds = self.elapsed_ticks / 1000 # Seconds
minutes = int(total_seconds / 60)
seconds = total_seconds - minutes * 60
if minutes > 0:
time_string = f"{minutes} minutes, {seconds:.2f} seconds"
else:
time_string = f"{seconds:.2f} seconds"
# Save stats to the game object so results menu can read them:
self.last_result_won = won
self.last_result_time_string = time_string
self.last_result_sticks_used = self.player.glow_sticks_used
self.last_result_sticks_left = self.player.glow_sticks_left
# Clear everything before in the state stack so the player
# can't "unpause" a finished game:
self.state_stack = [c.GameState.RESULTS_SCREEN]
def run(self) -> None:
"""Starts and maintains the main game loop."""
while self.running:
self.handle_events()
self.update()
self.draw_screen()
self.clock.tick(c.FPS)
pygame.quit()
sys.exit()
if __name__ == "__main__":
game = Game()
game.run()