repair this code and say if something need manual imput: import pygame import random…
- User
repair this code and say if something need manual imput: import pygame import random
Initialize Pygame
pygame.init()
Set up the screen
screen_width = 800 screen_height = 600 screen = pygame.display.set_mode((10, 30)) pygame.display.set_caption("Hide and Seek")
Create the player
player_width = 50 player_height = 50 player_x = screen_width // 2 - player_width // 2 player_y = screen_height // 2 - player_height // 2 player_color = (255, 0, 0) player_speed = 5 player_rect = pygame.Rect(player_x, player_y, player_width, player_height)
Create the enemy
enemy_width = 50 enemy_height = 50 enemy_x = random.randint(0, screen_width - enemy_width) enemy_y = random.randint(0, screen_height - enemy_height) enemy_color = (0, 255, 0) enemy_speed = 3 enemy_rect = pygame.Rect(enemy_x, enemy_y, enemy_width, enemy_height)
Check for collision
def check_collision(player_rect, enemy_rect): if player_rect.colliderect(enemy_rect): return True else: return False
Game loop
running = True while running: # Handle events for event in pygame.event.get(): if event.type == pygame.QUIT: running = False elif event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: running = False
# Move the player keys = pygame.key.get_pressed() if keys[pygame.K_LEFT] and player_rect.left > 0: player_rect.x -= player_speed elif keys[pygame.K_RIGHT] and player_rect.right < screen_width: player_rect.x += player_speed elif keys[pygame.K_UP] and player_rect.top > 0: player_rect.y -= player_speed elif keys[pygame.K_DOWN] and player_rect.bottom < screen_height: player_rect.y += player_speedMove the enemy
if enemy_rect.centerx < player_rect.centerx: enemy_rect.x += enemy_speed elif enemy_rect.centerx > player_rect.centerx: enemy_rect.x -= enemy_speed
if enemy_rect.centery < player_rect.centery: enemy_rect.y += enemy_speed elif enemy_rect.centery > player_rect.centery: enemy_rect.y -= enemy_speed
Check for collision
if check_collision(player_rect, enemy_rect): print("Collision! Game over.") running = False
Draw the player and enemy on the screen
screen.fill((255, 255, 255)) pygame.draw.rect(screen, player_color, player_rect) pygame.draw.rect(screen, enemy_color, enemy_rect) pygame.display.update()
- Assistant