import pygame
import random
import sys

pygame.init()
WIDTH, HEIGHT = 800, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("猫抓老鼠")
clock = pygame.time.Clock()

# 老鼠（玩家控制）
mouse_pos = [WIDTH // 2, HEIGHT // 2]
MOUSE_SPEED = 5
MOUSE_RADIUS = 12

# 猫（自动追老鼠）
cat_pos = [100, 100]
CAT_SPEED = 2.2
CAT_RADIUS = 15

font = pygame.font.SysFont("simhei", 36)
score = 0
game_over = False

def dist(a, b):
    return ((a[0]-b[0])**2 + (a[1]-b[1])**2) ** 0.5

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit(); sys.exit()
        if event.type == pygame.KEYDOWN and event.key == pygame.K_r and game_over:
            # 重开
            mouse_pos = [WIDTH // 2, HEIGHT // 2]
            cat_pos = [random.randint(0, WIDTH), random.randint(0, HEIGHT)]
            score = 0
            game_over = False

    keys = pygame.key.get_pressed()
    if not game_over:
        if keys[pygame.K_LEFT]:  mouse_pos[0] -= MOUSE_SPEED
        if keys[pygame.K_RIGHT]: mouse_pos[0] += MOUSE_SPEED
        if keys[pygame.K_UP]:    mouse_pos[1] -= MOUSE_SPEED
        if keys[pygame.K_DOWN]:  mouse_pos[1] += MOUSE_SPEED

        # 边界限制
        mouse_pos[0] = max(MOUSE_RADIUS, min(WIDTH - MOUSE_RADIUS, mouse_pos[0]))
        mouse_pos[1] = max(MOUSE_RADIUS, min(HEIGHT - MOUSE_RADIUS, mouse_pos[1]))

        # 猫朝老鼠移动
        dx = mouse_pos[0] - cat_pos[0]
        dy = mouse_pos[1] - cat_pos[1]
        d = (dx**2 + dy**2) ** 0.5
        if d > 0:
            cat_pos[0] += CAT_SPEED * dx / d
            cat_pos[1] += CAT_SPEED * dy / d

        # 碰撞检测
        if dist(mouse_pos, cat_pos) < MOUSE_RADIUS + CAT_RADIUS:
            game_over = True

        score += 1  # 生存帧数计分

    # 绘制
    screen.fill((240, 240, 220))
    pygame.draw.circle(screen, (150, 150, 150), (int(mouse_pos[0]), int(mouse_pos[1])), MOUSE_RADIUS)  # 老鼠
    pygame.draw.circle(screen, (200, 80, 40), (int(cat_pos[0]), int(cat_pos[1])), CAT_RADIUS)          # 猫

    txt = font.render(f"得分: {score//10}", True, (0, 0, 0))
    screen.blit(txt, (20, 20))

    if game_over:
        over = font.render("被抓住了！按 R 重开", True, (200, 0, 0))
        screen.blit(over, (WIDTH//2 - 180, HEIGHT//2 - 20))

    pygame.display.flip()
    clock.tick(60)