Я делаю игру о черепахе, которая идет в свое гнездо, чтобы выиграть игру. Если они выиграют, игра должна закончиться экраном «Вы выиграли». Если игрок падает в яму, игра должна быть проиграна и закончится на экране «Игра окончена». Вместо этого эти конечные заставки воспроизводятся долю секунды, а затем мгновенно воспроизводят игру. Вот мой текущий код.
import pygame
# Initialize pygame
pygame.init()
screen = pygame.display.set_mode((600, 800)) # Set screen size (600 wide, 800 high)
clock = pygame.time.Clock()
# Define player speed
player_speed = 5
# Set up game over and win screen images
game_over_image = pygame.image.load('game_over.png')
end_screen_image = pygame.image.load('youwin.png')
# Load the start screen image
start_screen_image = pygame.image.load('start_screen_real.png')
start_screen_rect = start_screen_image.get_rect(center=(300, 400)) # Center start screen at (300, 400)
# Player class definition
class Player:
def __init__(self, image_path, player_speed):
self.image = pygame.image.load(image_path)
self.rect = self.image.get_rect() # Get the rect that represents the image
self.velocity_x = 0
self.velocity_y = 0
self.player_speed = player_speed # Define player speed
self.moving = True # Flag to indicate whether the player is still moving
def update(self, keys, obstacles):
if not self.moving:
return True # If the player is stopped, don't update
# Set velocity to 0 if no keys are pressed
if not any(keys): # No key pressed
self.velocity_x = 0
self.velocity_y = 0
# Handle key presses for movement
if keys[pygame.K_a]: # Left
self.velocity_x = -self.player_speed
if keys[pygame.K_d]: # Right
self.velocity_x = self.player_speed
if keys[pygame.K_w]: # Up
self.velocity_y = -self.player_speed
if keys[pygame.K_s]: # Down
self.velocity_y = self.player_speed
# Handle collisions with obstacles (sand piles, holes, etc.)
for obstacle in obstacles:
if self.rect.colliderect(obstacle.rect):
if obstacle.type == 'hole': # Collision with hole triggers Game Over
return False
else:
# Handle collision with sand piles or other obstacles (push player back slightly)
if self.velocity_x < 0: # Moving left
self.rect.x += 10 # Push player right (10 steps)
if self.velocity_x > 0: # Moving right
self.rect.x -= 10 # Push player left (10 steps)
if self.velocity_y < 0: # Moving up
self.rect.y += 10 # Push player down (10 steps)
if self.velocity_y > 0: # Moving down
self.rect.y -= 10 # Push player up (10 steps)
return True # Return True if no hole was hit, indicating normal movement
def move(self):
self.rect.x += self.velocity_x # Move the player horizontally
self.rect.y += self.velocity_y # Move the player vertically
def draw(self, screen):
screen.blit(self.image, self.rect) # Draw the image on the screen using its rect
# Define obstacles as rectangles (sand piles or holes)
class Obstacle:
def __init__(self, image_path, x, y, obstacle_type='sand'):
self.image = pygame.image.load(image_path)
self.rect = self.image.get_rect()
self.rect.center = (x, y)
self.type = obstacle_type # Could be 'sand' or 'hole'
def draw(self, screen):
screen.blit(self.image, self.rect)
# Game loop
running = True
game_started = False # Flag to track whether the game has started
game_over = False # Flag to track game over state
game_won = False # Flag to track if the game is won
# Initialize player and obstacles
player = Player("turtle1.png", player_speed) # Create player instance
# Create obstacles (sand piles and holes) at predefined reasonable positions
obstacles = [
Obstacle('sand_pile.png', 100, 200), # First sand pile
Obstacle('sand_pile.png', 500, 300), # Second sand pile
Obstacle('sand_pile.png', 400, 500), # Third sand pile
Obstacle('sand_pile.png', 200, 600), # Fourth sand pile
Obstacle('hole.png', 300, 250, 'hole'), # First hole
Obstacle('hole.png', 100, 500, 'hole'), # Second hole
Obstacle('hole.png', 400, 450, 'hole'), # Third hole
Obstacle('hole.png', 500, 650, 'hole'), # Fourth hole
]
# Set up the goal (nest)
goal_image = pygame.image.load("egg_nest.png")
goal_rect = goal_image.get_rect()
goal_rect.center = (275, 150) # Nest placed at (275, 150)
# Load the background image
background = pygame.image.load("pixel_art.png")
while running:
# Blit the background image at (0, 0) to fill the screen
screen.blit(background, (0, 0))
# Event handling
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# If the game hasn't started, show the start screen
if not game_started:
# Display the start screen centered at (300, 400)
screen.blit(start_screen_image, start_screen_rect) # Centered at (300, 400)
# Wait for player to press F to start the game
keys = pygame.key.get_pressed()
if keys[pygame.K_f]: # Press F to begin the game
game_started = True # Set the flag to start the game
# Position the player at spawn point
player.rect.center = (275, 650)
# Set up the game environment (goal, obstacles, etc.)
goal_rect.center = (275, 150) # Nest placed at (275, 150)
else:
# Game has started, allow player movement and game logic
keys = pygame.key.get_pressed()
if not player.update(keys, obstacles): # If the player collides with a hole
game_over = True # Set game over flag
screen.blit(game_over_image, (150, 200)) # Show "Game Over" screen at (300, 400)
else:
player.move() # Move the player based on keys pressed
player.draw(screen) # Draw the player on the screen
# Draw the goal (nest) on the screen
screen.blit(goal_image, goal_rect)
# Draw all obstacles (sand piles and holes)
for obstacle in obstacles:
obstacle.draw(screen)
# Check for collision with goal (nest)
if player.rect.colliderect(goal_rect):
if not game_won: # Prevent game from restarting immediately
game_won = True # Mark the game as won
screen.blit(end_screen_image, (150, 200)) # Show "You Win!" screen at (300, 400)
# If game is over or won, stop further actions
if game_over or game_won:
game_started = False # Stop player movement and interaction after game ends
# Update the screen
pygame.display.flip()
# Set FPS
clock.tick(60)
pygame.quit()
Чтобы разобраться, вот что работает:
Движение
Коллизии
Спрайты (в виде изображений)
Положение
Стартовый экран
И вот что не работает:
Экран «Игра окончена»
Экран «Вы выиграли»
Теперь в начале игры есть стартовый экран. Когда игра начинается, этот экран закрывается. Есть также способ проиграть и есть способ выиграть. Добравшись до конечной цели, вы выиграете. Упав в яму, вы проиграете. Существует экран окончания игры, который воспроизводится, если вы проигрываете, и экран «Вы выиграли», который открывается, если вы выигрываете. Когда игрок выигрывает/проигрывает, эти экраны воспроизводятся только долю секунды, и игра зависает на стартовом экране. Вместо того, чтобы зависать на стартовом экране, я хотел бы зависать, когда игра окончена, иначе вы выиграете экраны. Капиш?
Я делаю игру о черепахе, которая идет в свое гнездо, чтобы выиграть игру. Если они выиграют, игра должна закончиться экраном «Вы выиграли». Если игрок падает в яму, игра должна быть проиграна и закончится на экране «Игра окончена». Вместо этого эти конечные заставки воспроизводятся долю секунды, а затем мгновенно воспроизводят игру. Вот мой текущий код. [code]import pygame
# Set up game over and win screen images game_over_image = pygame.image.load('game_over.png') end_screen_image = pygame.image.load('youwin.png')
# Load the start screen image start_screen_image = pygame.image.load('start_screen_real.png') start_screen_rect = start_screen_image.get_rect(center=(300, 400)) # Center start screen at (300, 400)
# Player class definition class Player: def __init__(self, image_path, player_speed): self.image = pygame.image.load(image_path) self.rect = self.image.get_rect() # Get the rect that represents the image self.velocity_x = 0 self.velocity_y = 0 self.player_speed = player_speed # Define player speed self.moving = True # Flag to indicate whether the player is still moving
def update(self, keys, obstacles): if not self.moving: return True # If the player is stopped, don't update
# Set velocity to 0 if no keys are pressed if not any(keys): # No key pressed self.velocity_x = 0 self.velocity_y = 0
# Handle key presses for movement if keys[pygame.K_a]: # Left self.velocity_x = -self.player_speed if keys[pygame.K_d]: # Right self.velocity_x = self.player_speed if keys[pygame.K_w]: # Up self.velocity_y = -self.player_speed if keys[pygame.K_s]: # Down self.velocity_y = self.player_speed
# Handle collisions with obstacles (sand piles, holes, etc.) for obstacle in obstacles: if self.rect.colliderect(obstacle.rect): if obstacle.type == 'hole': # Collision with hole triggers Game Over return False else: # Handle collision with sand piles or other obstacles (push player back slightly) if self.velocity_x < 0: # Moving left self.rect.x += 10 # Push player right (10 steps) if self.velocity_x > 0: # Moving right self.rect.x -= 10 # Push player left (10 steps) if self.velocity_y < 0: # Moving up self.rect.y += 10 # Push player down (10 steps) if self.velocity_y > 0: # Moving down self.rect.y -= 10 # Push player up (10 steps)
return True # Return True if no hole was hit, indicating normal movement
def move(self): self.rect.x += self.velocity_x # Move the player horizontally self.rect.y += self.velocity_y # Move the player vertically
def draw(self, screen): screen.blit(self.image, self.rect) # Draw the image on the screen using its rect
# Define obstacles as rectangles (sand piles or holes) class Obstacle: def __init__(self, image_path, x, y, obstacle_type='sand'): self.image = pygame.image.load(image_path) self.rect = self.image.get_rect() self.rect.center = (x, y) self.type = obstacle_type # Could be 'sand' or 'hole'
# Game loop running = True game_started = False # Flag to track whether the game has started game_over = False # Flag to track game over state game_won = False # Flag to track if the game is won
# Initialize player and obstacles player = Player("turtle1.png", player_speed) # Create player instance
# Create obstacles (sand piles and holes) at predefined reasonable positions obstacles = [ Obstacle('sand_pile.png', 100, 200), # First sand pile Obstacle('sand_pile.png', 500, 300), # Second sand pile Obstacle('sand_pile.png', 400, 500), # Third sand pile Obstacle('sand_pile.png', 200, 600), # Fourth sand pile Obstacle('hole.png', 300, 250, 'hole'), # First hole Obstacle('hole.png', 100, 500, 'hole'), # Second hole Obstacle('hole.png', 400, 450, 'hole'), # Third hole Obstacle('hole.png', 500, 650, 'hole'), # Fourth hole ]
# Set up the goal (nest) goal_image = pygame.image.load("egg_nest.png") goal_rect = goal_image.get_rect() goal_rect.center = (275, 150) # Nest placed at (275, 150)
# Load the background image background = pygame.image.load("pixel_art.png")
while running: # Blit the background image at (0, 0) to fill the screen screen.blit(background, (0, 0))
# Event handling for event in pygame.event.get(): if event.type == pygame.QUIT: running = False
# If the game hasn't started, show the start screen if not game_started: # Display the start screen centered at (300, 400) screen.blit(start_screen_image, start_screen_rect) # Centered at (300, 400)
# Wait for player to press F to start the game keys = pygame.key.get_pressed() if keys[pygame.K_f]: # Press F to begin the game game_started = True # Set the flag to start the game
# Position the player at spawn point player.rect.center = (275, 650)
# Set up the game environment (goal, obstacles, etc.) goal_rect.center = (275, 150) # Nest placed at (275, 150)
else: # Game has started, allow player movement and game logic keys = pygame.key.get_pressed() if not player.update(keys, obstacles): # If the player collides with a hole game_over = True # Set game over flag screen.blit(game_over_image, (150, 200)) # Show "Game Over" screen at (300, 400) else: player.move() # Move the player based on keys pressed player.draw(screen) # Draw the player on the screen
# Draw the goal (nest) on the screen screen.blit(goal_image, goal_rect)
# Draw all obstacles (sand piles and holes) for obstacle in obstacles: obstacle.draw(screen)
# Check for collision with goal (nest) if player.rect.colliderect(goal_rect): if not game_won: # Prevent game from restarting immediately game_won = True # Mark the game as won screen.blit(end_screen_image, (150, 200)) # Show "You Win!" screen at (300, 400)
# If game is over or won, stop further actions if game_over or game_won: game_started = False # Stop player movement and interaction after game ends
# Update the screen pygame.display.flip()
# Set FPS clock.tick(60)
pygame.quit() [/code] Чтобы разобраться, вот что работает: [list] [*]Движение [*]Коллизии [*]Спрайты (в виде изображений) [*]Положение [*]Стартовый экран И вот что не работает: [*]Экран «Игра окончена» [/list] Экран «Вы выиграли» Теперь в начале игры есть стартовый экран. Когда игра начинается, этот экран закрывается. Есть также способ проиграть и есть способ выиграть. Добравшись до конечной цели, вы выиграете. Упав в яму, вы проиграете. Существует экран окончания игры, который воспроизводится, если вы проигрываете, и экран «Вы выиграли», который открывается, если вы выигрываете. Когда игрок выигрывает/проигрывает, эти экраны воспроизводятся только долю секунды, и игра зависает на стартовом экране. Вместо того, чтобы зависать на стартовом экране, я хотел бы зависать, когда игра окончена, иначе вы выиграете экраны. Капиш?