![]() |
[PyGame] When I hit the space bar from the home screen, it sends me to the game over screen - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Game Development (https://python-forum.io/forum-11.html) +--- Thread: [PyGame] When I hit the space bar from the home screen, it sends me to the game over screen (/thread-39889.html) |
When I hit the space bar from the home screen, it sends me to the game over screen - JesusisKing - Apr-30-2023 ok, this is driving me nuts, i cant seem to figure out why when i press the space bar from the home screen, it sends me straight to the game over screen. if someone would mind please helping me out https://textdoc.co/gUiBZqbeR9s2JC8M RE: When I hit the space bar from the home screen, it sends me to the game over screen - deanhystad - Apr-30-2023 Please post your code. I'm not clicking on link. RE: When I hit the space bar from the home screen, it sends me to the game over screen - Mollycoddle - Jul-31-2024 (Apr-30-2023, 10:11 PM)deanhystad Wrote: Please post your code. I'm not clicking on link. this is all I see in the link: import pygame import pygame.time import random import os import sys nut_group = pygame.sprite.Group() habanero_group = pygame.sprite.Group() habanero_spawn_interval = 6000 # spawn habanero every 6 seconds heart_group = pygame.sprite.Group() heart_speed = 1 # Define colors BLACK = (0, 0, 0) WHITE = (255, 255, 255) RED = (255, 0, 0) GREEN = (0, 255, 0) # Set up the game window WINDOW_WIDTH = 800 WINDOW_HEIGHT = 600 pygame.init() game_window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT)) pygame.display.set_caption("Squirrel Run") # create game window screen = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT)) # Specify absolute path to img directory img_dir = os.path.abspath("img") # Load images nut_img = pygame.image.load(os.path.join(img_dir, "nut.png")).convert_alpha() heart_img = pygame.image.load(os.path.join(img_dir, "heart.png")).convert_alpha() squirrel_img = pygame.image.load(os.path.join(img_dir, "squirrel.png")).convert_alpha() # Set up game loop clock = pygame.time.Clock() running = True on_start_screen = True # set on_start_screen to True initially # Calculate the size of the Habanero sprite in pixels INCHES_TO_MM = 25.4 INCHES_WIDTH = 7 INCHES_HEIGHT = 5 RESOLUTION = 300 SIZE_WIDTH = int(INCHES_WIDTH * INCHES_TO_MM * RESOLUTION / 1000) SIZE_HEIGHT = int(INCHES_HEIGHT * INCHES_TO_MM * RESOLUTION / 1000) # Load the Habanero sprite image and resize it to the calculated size habanero_img = pygame.image.load(os.path.join(img_dir, "habaneropepper.png")).convert_alpha() habanero_img = pygame.transform.scale(habanero_img, (SIZE_WIDTH, SIZE_HEIGHT)) all_sprites = pygame.sprite.Group() nuts = pygame.sprite.Group() squirrels = pygame.sprite.Group() habaneros = pygame.sprite.Group() # Set initial game values score = 0 lives = 3 nut_speed_increase = 0.05 nut_speed_increase_interval = 25 nut_count = 0 habanero_count = 0 game_timer = 60*30 # 30 seconds in frames # Define classes for game objects class Squirrel(pygame.sprite.Sprite): def __init__(self, nut_group, habanero_group, heart_group): super().__init__() self.image = squirrel_img self.rect = self.image.get_rect() self.rect.center = (WINDOW_WIDTH // 2, WINDOW_HEIGHT - 50) self.speed = 0 self.lives = 3 self.nut_group = nut_group self.habanero_group = habanero_group self.heart_group = heart_group def update(self): mouse_pos = pygame.mouse.get_pos() self.rect.centerx = mouse_pos[0] self.rect.centery = mouse_pos[1] if self.rect.left < 0: self.rect.left = 0 if self.rect.right > WINDOW_WIDTH: self.rect.right = WINDOW_WIDTH if self.rect.top < 0: self.rect.top = 0 if self.rect.bottom > WINDOW_HEIGHT: self.rect.bottom = WINDOW_HEIGHT self.check_collision() def check_collision(self): nut_collisions = pygame.sprite.spritecollide(self, self.nut_group, True) if nut_collisions: print("Nut collected!") habanero_collisions = pygame.sprite.spritecollide(self, self.habanero_group, False) if habanero_collisions: print("Habanero hit!") self.lives -= 1 # reduce the number of lives by 1 when hit by a habanero heart_collisions = pygame.sprite.spritecollide(self, self.heart_group, True) if heart_collisions: print("Heart collected!") self.lives += 1 # increase the number of lives by 1 when a heart is collected if self.lives > 5: # Make sure the number of lives does not exceed 5 self.lives = 5 class Heart(pygame.sprite.Sprite): def __init__(self): super().__init__() self.image = heart_img self.rect = self.image.get_rect() self.rect.x = random.randrange(WINDOW_WIDTH - self.rect.width) self.rect.y = random.randrange(-100, -40) def update(self): global score self.rect.y += heart_speed if self.rect.top > WINDOW_HEIGHT: self.rect.x = random.randrange(WINDOW_WIDTH - self.rect.width) self.rect.y = random.randrange(-100, -40) self.check_collision() def check_collision(self): global score, lives, heart_group for nut in nut_group: if pygame.sprite.collide_rect(self, nut): nut.rect.x = random.randrange(WINDOW_WIDTH - nut.rect.width) nut.rect.y = random.randrange(-100, -40) if nut.rect.y > WINDOW_HEIGHT: nut.rect.x = random.randrange(WINDOW_WIDTH - nut.rect.width) nut.rect.y = random.randrange(-100, -40) for habanero in habanero_group: if pygame.sprite.collide_rect(self, habanero): habanero.rect.x = random.randrange(WINDOW_WIDTH - habanero.rect.width) habanero.rect.y = random.randrange(-100, -40) if habanero.rect.y > WINDOW_HEIGHT: habanero.rect.x = random.randrange(WINDOW_WIDTH - habanero.rect.width) habanero.rect.y = random.randrange(-100, -40) for heart in heart_group: if pygame.sprite.collide_rect(self, habanero): habanero.rect.x = random.randrange(WINDOW_WIDTH - habanero.rect.width) habanero.rect.y = random.randrange(-100, -40) if habanero.rect.y > WINDOW_HEIGHT: habanero.rect.x = random.randrange(WINDOW_WIDTH - habanero.rect.width) habanero.rect.y = random.randrange(-100, -40) class Nut(pygame.sprite.Sprite): def __init__(self, speed): super().__init__() self.image = nut_img self.rect = self.image.get_rect() self.rect.x = random.randrange(0, WINDOW_WIDTH - self.rect.width) self.rect.y = -self.rect.height self.speed = speed def update(self): self.rect.y += self.speed if self.rect.top > WINDOW_HEIGHT: self.kill() def check_collision(self): global nut_group, all_sprites, score for nut in nut_group: if pygame.sprite.collide_rect(self, nut): nut_group.remove(nut) all_sprites.remove(nut) score += self.score_value nut.score_value = self.score_value nut_group.add(nut) all_sprites.add(nut) class Habanero(pygame.sprite.Sprite): def __init__(self): super().__init__() self.image = habanero_img self.rect = self.image.get_rect().inflate(-20, -20) self.speed = 3 self.rect.x = random.randrange(WINDOW_WIDTH - self.rect.width) self.rect.y = random.randrange(-100, -self.rect.height) self.score_value = -10 def update(self): global lives, habanero_count self.rect.y += self.speed if self.rect.y > WINDOW_HEIGHT: self.rect.x = random.randrange(WINDOW_WIDTH - self.rect.width) self.rect.y = random.randrange(-100, -self.rect.height) habanero_count += 1 self.check_collision() def check_collision(self): global score, lives, habanero_group, running for habanero in habanero_group: if pygame.sprite.collide_rect(self, habanero): habanero_group.remove(habanero) all_sprites.remove(habanero) score += self.score_value lives -= 1 if lives <= 0: running = False else: habanero = Habanero() habanero.score_value = self.score_value # Set score value of new habanero habanero_group.add(habanero) all_sprites.add(habanero) # Create game objects and add them to sprite groups nut_speed = 5 # Define nut_speed before the for loop for i in range(10): nut = Nut(nut_speed) all_sprites.add(nut) nuts.add(nut) for i in range(2): habanero = Habanero() all_sprites.add(habanero) habaneros.add(habanero) # Create a Habanero object with an initial nut speed habanero_speed = 1 all_sprites.add(habanero) habaneros.add(habanero) squirrel = Squirrel(nut_group, habanero_group, heart_group) all_sprites.add(squirrel) nut = Nut(nut_speed) nut_group.add(nut) all_sprites.add(nut) habanero = Habanero() habanero_group.add(habanero) all_sprites.add(habanero) heart = Heart() heart_group.add(heart) all_sprites.add(heart) # Create the squirrel sprite and add it to the sprite groups all_sprites.add(squirrel) def draw_text(surface, text, size, x, y): font = pygame.font.SysFont("Arial", size) text_surface = font.render(text, True, (0, 0, 0)) text_rect = text_surface.get_rect() text_rect.center = (x, y) surface.blit(text_surface, text_rect) # Set up high score file HIGH_SCORE_FILE = "high_score.txt" try: with open(HIGH_SCORE_FILE, 'r') as f: high_score = int(f.read()) except FileNotFoundError: high_score = 0 def save_high_score(score): with open(HIGH_SCORE_FILE, 'w') as f: f.write(str(score)) def draw_home_screen(): # Fill screen with white color screen.fill((255, 255, 255)) # Draw text onto the screen draw_text(screen, "Welcome to Squirrel Game!", 64, WINDOW_WIDTH // 2, WINDOW_HEIGHT // 4) draw_text(screen, "Press Spacebar to start the game", 32, WINDOW_WIDTH // 2, WINDOW_HEIGHT // 2) # Show high score if it exists if high_score > 0: draw_text(screen, f"High Score: {high_score}", 32, WINDOW_WIDTH // 2, WINDOW_HEIGHT // 2 + 50) # Update the screen pygame.display.update() def draw_game_screen(): # Draw background screen.fill(BLUE) # Draw player and other game objects player.draw(screen) for obj in game_objects: obj.draw(screen) # Draw score draw_text(screen, f"Score: {score}", 32, 10, 10) # Update the screen pygame.display.update() def draw_game_over_screen(): # Draw background screen.fill(RED) # Draw text draw_text(screen, "Game Over", 64, WINDOW_WIDTH // 2, WINDOW_HEIGHT // 4) draw_text(screen, f"Score: {score}", 32, WINDOW_WIDTH // 2, WINDOW_HEIGHT // 2) # Check and display high score if score > high_score: draw_text(screen, f"New High Score: {score}", 32, WINDOW_WIDTH // 2, WINDOW_HEIGHT // 2 + 50) elif high_score > 0: draw_text(screen, f"High Score: {high_score}", 32, WINDOW_WIDTH // 2, WINDOW_HEIGHT // 2 + 50) # Draw prompt to play again draw_text(screen, "Press 'SPACE' to play again", 32, WINDOW_WIDTH // 2, WINDOW_HEIGHT * 3 // 4) # Update the screen pygame.display.update() pygame.font.init() font = pygame.font.SysFont("Arial", 24) score_surface = font.render(f"Score: {score}", True, (0, 0, 0)) lives_surface = font.render(f"Lives: {lives}", True, (0, 0, 0)) prev_score = -1 if score != prev_score: score_surface = font.render(f"Score: {score}", True, (0, 0, 0)) screen.blit(score_surface, (10, 10)) # Initialize game state running = True prev_score = 0 score = 0 lives = 3 consecutive_nuts = 0 multiplier = 1 clock = pygame.time.Clock() last_habanero_spawn = pygame.time.get_ticks() consecutive_nuts = 0 multiplier = 1 game_over = False # set to False at the beginning of the game home_screen = True # Game loop while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False elif event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE: home_screen = False if home_screen: draw_home_screen() elif game_over: draw_game_over_screen() else: # Update the game state all_sprites.update() # Update sprites squirrel.update() nut_group.update() habanero_group.update() nut_group.update() # Fill screen with white color screen.fill((255, 255, 255)) # Draw sprites onto the screen nut_group.draw(screen) habanero_group.draw(screen) heart_group.draw(screen) screen.blit(squirrel.image, squirrel.rect) # Check for collisions between squirrel and nuts/habaneros nut_collisions = pygame.sprite.spritecollide(squirrel, nuts, True) for nut in nut_collisions: consecutive_nuts += 1 if consecutive_nuts >= 50 and consecutive_nuts < 100: multiplier = 2 elif consecutive_nuts >= 100: multiplier = 3 else: multiplier = 1 score += 1 * multiplier nut = Nut() all_sprites.add(nut) nuts.add(nut) habanero_collisions = pygame.sprite.spritecollide(squirrel, habaneros, True) for habanero in habanero_collisions: consecutive_nuts = 0 multiplier = 1 score -= 5 # reduce score by 5 for hitting habanero if score < 0: if lives > 0: lives -= 1 score = 0 else: game_over = True else: print(f"Score: {score}") # Check if the player has no remaining lives if lives <= 0: game_over = True # Check for collisions between squirrel and hearts heart_collisions = pygame.sprite.spritecollide(squirrel, heart_group, True) if heart_collisions: score += 10 # increase score by 10 for collecting heart print("Heart collected") # Check if the player has collected all the hearts if len(heart_group) == 0: game_over = True # Spawn a new habanero at random intervals now = pygame.time.get_ticks() if now - last_habanero_spawn > habanero_spawn_interval: last_habanero_spawn = now habanero_speed = 1 + score // 10 if habanero_speed > 5: # limit habanero speed to 5 habanero_speed = 5 habanero = Habanero() habanero.rect.bottom = 0 habanero.rect.x = random.randrange(0, WINDOW_WIDTH - habanero.rect.width) all_sprites.add(habanero) habaneros.add(habanero) habanero_group.add(habanero) # Draw the screen draw_text(screen, f"Score: {score}", 32, WINDOW_WIDTH // 2, 10) draw_text(screen, f"Lives: {lives}", 32, WINDOW_WIDTH - 100, 10) # Check if the game is over if lives <= 0 or len(heart_group) == 0: game_over = True # Check if the player has a new high score if score > high_score: high_score = score draw_text(screen, "NEW HIGH SCORE!", 32, WINDOW_WIDTH // 2, WINDOW_HEIGHT // 2 - 50) pygame.display.flip() clock.tick(60) pygame.quit() # Loop to keep window open after game is over pygame.init() while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() # Quit Pygame properly pygame.quit() |