import pygame
import random
# 初始化pygame
pygame.init()
# 设置屏幕尺寸和颜色
WIDTH, HEIGHT = 800, 600
BACKGROUND_COLOR = (255, 255, 255)
EAGLE_COLOR = (0, 0, 255)
CHICK_COLOR = (255, 255, 0)
FPS = 30
# 创建游戏窗口
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("老鹰抓小鸡")
# 创建游戏对象
eagle_size = 50
chick_size = 30
eagle_pos = [WIDTH // 2, HEIGHT // 2]
chick_pos = [random.randint(0, WIDTH - chick_size), random.randint(0, HEIGHT - chick_size)]
# 设置移动速度
eagle_speed = 5
chick_speed = 3
clock = pygame.time.Clock()
def move_eagle(keys):
if keys[pygame.K_LEFT]:
eagle_pos[0] -= eagle_speed
if keys[pygame.K_RIGHT]:
eagle_pos[0] += eagle_speed
if keys[pygame.K_UP]:
eagle_pos[1] -= eagle_speed
if keys[pygame.K_DOWN]:
eagle_pos[1] += eagle_speed
# 防止老鹰走出屏幕边界
eagle_pos[0] = max(0, min(eagle_pos[0], WIDTH - eagle_size))
eagle_pos[1] = max(0, min(eagle_pos[1], HEIGHT - eagle_size))
def move_chick():
direction = random.choice(['left', 'right', 'up', 'down'])
if direction == 'left':
chick_pos[0] -= chick_speed
elif direction == 'right':
chick_pos[0] += chick_speed
elif direction == 'up':
chick_pos[1] -= chick_speed
elif direction == 'down':
chick_pos[1] += chick_speed
# 防止小鸡走出屏幕边界
chick_pos[0] = max(0, min(chick_pos[0], WIDTH - chick_size))
chick_pos[1] = max(0, min(chick_pos[1], HEIGHT - chick_size))
def check_collision():
return (eagle_pos[0] < chick_pos[0] + chick_size and
eagle_pos[0] + eagle_size > chick_pos[0] and
eagle_pos[1] < chick_pos[1] + chick_size and
eagle_pos[1] + eagle_size > chick_pos[1])
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
keys = pygame.key.get_pressed()
move_eagle(keys)
move_chick()
if check_collision():
print("老鹰抓到小鸡了!")
chick_pos = [random.randint(0, WIDTH - chick_size), random.randint(0, HEIGHT - chick_size)]
screen.fill(BACKGROUND_COLOR)
pygame.draw.rect(screen, EAGLE_COLOR, (*eagle_pos, eagle_size, eagle_size))
pygame.draw.rect(screen, CHICK_COLOR, (*chick_pos, chick_size, chick_size))
pygame.display.flip()
clock.tick(FPS)
pygame.quit()