Files
Anna/main.py
2026-06-17 15:25:34 +08:00

105 lines
2.7 KiB
Python

import pgzrun
import random
import math
WIDTH = 800
HEIGHT = 600
APPLE_POS = (WIDTH / 2, HEIGHT / 2)
DINO_SPEED = 120
START_SPAWN_INTERVAL = 2.0
MIN_SPAWN_INTERVAL = 0.2
SPAWN_ACCELERATION = 0.3
CORPSE_LIFETIME = 2.0
APPLE_HIT_RADIUS = 25
apple = Actor("apple", APPLE_POS)
sword = Actor("sword", APPLE_POS)
dinosaurs = []
corpses = []
spawn_interval = START_SPAWN_INTERVAL
spawn_timer = 0
game_time = 0
score = 0
missed_apples = 0
def on_mouse_move(pos, rel, buttons):
"""Keep the sword centered on the mouse pointer."""
sword.pos = pos
def spawn_dinosaurs():
"""Create a dinosaur just outside one edge of the screen."""
dino_images = ("dino", "dino2")
random_dino = random.choice(dino_images)
dino = Actor(random_dino)
side = random.randint(0, 3)
if side == 0: # up
dino.x = random.randint(0, WIDTH)
dino.y = -50
elif side == 1: # down
dino.x = random.randint(0, WIDTH)
dino.y = HEIGHT + 50
elif side == 2: # left
dino.x = -50
dino.y = random.randint(0, HEIGHT)
else:
dino.x = WIDTH + 50
dino.y = random.randint(0, HEIGHT)
dinosaurs.append(dino)
def update(dt):
global spawn_timer, spawn_interval, game_time, score, missed_apples
game_time += dt
spawn_timer += dt
# Gradually reduce the delay between spawns so the game gets harder.
spawn_interval = max(MIN_SPAWN_INTERVAL, spawn_interval - SPAWN_ACCELERATION * dt)
if spawn_timer >= spawn_interval:
spawn_dinosaurs()
spawn_timer = 0
for dino in dinosaurs[:]:
dx = apple.x - dino.x
dy = apple.y - dino.y
distance = math.hypot(dx, dy)
# Move at a steady speed toward the apple instead of jumping farther
# when the dinosaur is far away.
if distance > 0:
dino.x += (dx / distance) * DINO_SPEED * dt
dino.y += (dy / distance) * DINO_SPEED * dt
if dino.colliderect(sword):
dino.image = "dead"
corpses.append({"actor": dino, "die_time": game_time})
sounds.hit.play()
score += 1
dinosaurs.remove(dino)
elif distance <= APPLE_HIT_RADIUS:
missed_apples += 1
dinosaurs.remove(dino)
for corpse in corpses[:]:
if game_time - corpse["die_time"] >= CORPSE_LIFETIME:
corpses.remove(corpse)
def draw():
screen.fill((100, 200, 100))
apple.draw()
for dino in dinosaurs:
dino.draw()
for corpse in corpses:
corpse["actor"].draw()
sword.draw()
screen.draw.text(f"Score: {score}", (10, 10), fontsize=36, color="white")
screen.draw.text(f"Missed: {missed_apples}", (10, 50), fontsize=36, color="white")
pgzrun.go()