import pygame import random pygame.init() WIDTH = 500 HEIGHT = 600 screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("Survival Game") clock = pygame.time.Clock() font = pygame.font.Font(None, 32) # Player player = pygame.Rect(230, 500, 40, 40) player_speed = 5 health = 100 # Enemy enemy = pygame.Rect( random.randint(0, WIDTH - 40), random.randint(0, 300), 40, 40 ) enemy_speed = 2 # Food food = pygame.Rect( random.randint(0, WIDTH - 25), random.randint(50, HEIGHT - 25), 25, 25 ) score = 0 running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False # Controls keys = pygame.key.get_pressed() if keys[pygame.K_LEFT] and player.left > 0: player.x -= player_speed if keys[pygame.K_RIGHT] and player.right < WIDTH: player.x += player_speed if keys[pygame.K_UP] and player.top > 0: player.y -= player_speed if keys[pygame.K_DOWN] and player.bottom < HEIGHT: player.y += player_speed # Enemy follows player if enemy.x < player.x: enemy.x += enemy_speed if enemy.x > player.x: enemy.x -= enemy_speed if enemy.y < player.y: enemy.y += enemy_speed if enemy.y > player.y: enemy.y -= enemy_speed # Enemy hits player if player.colliderect(enemy): health -= 1 enemy.x = random.randint(0, WIDTH - 40) enemy.y = random.randint(0, 300) # Eat food if player.colliderect(food): score += 10 health = min(100, health + 10) food.x = random.randint(0, WIDTH - 25) food.y = random.randint(50, HEIGHT - 25) # Game Over if health <= 0: running = False # Draw screen.fill((40, 120, 60)) pygame.draw.rect(screen, (0, 100, 255), player) pygame.draw.rect(screen, (255, 0, 0), enemy) pygame.draw.rect(screen, (255, 200, 0), food) health_text = font.render( "Health: " + str(health), True, (255, 255, 255) ) score_text = font.render( "Score: " + str(score), True, (255, 255, 255) ) screen.blit(health_text, (10, 10)) screen.blit(score_text, (10, 40)) pygame.display.update() clock.tick(60) pygame.quit() print("GAME OVER!") print("Final Score:", score)
Hosted & Compiled with HtmlRunner.com