Curriculum
Course: Python Game Development : Build 5 Fun Pr...
Login

Curriculum

Python Game Development : Build 5 Fun Projects with Pygame

Text lesson

Main Setup: Project 3 : Maze Ball Run

5. Game Logic

  • Defines the check_win method to check if the player has reached the end point.

def check_win(self):

if self.player[‘rect’].colliderect(self.end[‘rect’]):

return True

return False

6. Screen Rendering

  • Defines the draw_start_screen method to render the start screen with game title and start instructions.

def draw_start_screen(self):

self.screen.fill(BACKGROUND_COLOR)

title_text = self.font.render(“Maze Game”, True, FONT_COLOR)

title_rect = title_text.get_rect(center=(SCREEN_WIDTH // 2, SCREEN_HEIGHT // 3))

start_text = self.font.render(“Press SPACE to Start”, True, FONT_COLOR)

start_rect = start_text.get_rect(center=(SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2))

self.screen.blit(title_text, title_rect)

self.screen.blit(start_text, start_rect)

pygame.display.flip()

  • Defines the draw_entities method to render player and end point entities on the screen.

def draw_entities(self):

pygame.draw.rect(self.screen, self.player[‘color’], self.player[‘rect’])

pygame.draw.rect(self.screen, self.end[‘color’], self.end[‘rect’])

7. Main Game Loop

  • Defines the main game loop (run method) to handle game events, such as quitting the game or starting/restarting the game.

def run(self):

running = True

while running:

for event in pygame.event.get():

if event.type == pygame.QUIT:

running = False

elif event.type == pygame.KEYDOWN:

if self.state == “start” and event.key == pygame.K_SPACE:

# Initialize game state and entities

self.state = “play”

self.maze = self.generate_maze()

self.player = self.create_entity(PLAYER_COLOR, (ROWS – 1, random.randint(0, COLS – 1)), 0.6)

self.end = self.create_entity(END_COLOR, (0, random.randint(0, COLS – 1)), 0.6)

self.start_time = pygame.time.get_ticks()

elif self.state == “end” and event.key == pygame.K_SPACE:

self.state = “start”

  • Within the game loop, checks the current game state and calls appropriate methods to render the start screen, play the game, or display the end screen.

if self.state == “start”:

self.draw_start_screen()

elif self.state == “play”:

# Game logic for player movement, collision detection, win condition, and timer

elif self.state == “end”:

self.draw_end_screen(win=self.check_win())

self.clock.tick(30) pygame.quit()

 

 

 

×

Cart