编辑代码

import pygame
import sys
import random

# 初始化 Pygame
pygame.init()

# 设置屏幕大小
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("Block Game")

# 定义颜色
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)

# 定义方块和敌人的大小
block_size = 50
enemy_size = 50

# 定义初始位置
player_pos = [screen_width // 2, screen_height // 2]
enemy_pos = [random.randint(0, screen_width - enemy_size), random.randint(0, screen_height - enemy_size)]

# 设置速度
player_speed = 10
enemy_speed = 3

# 主循环
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.MOUSEBUTTONDOWN:
            player_pos = list(event.pos)
    
    # 更新敌人位置
    direction_x = player_pos[0] - enemy_pos[0]
    direction_y = player_pos[1] - enemy_pos[1]
    distance = max(abs(direction_x), abs(direction_y))
    if distance != 0:
        enemy_pos[0] += (direction_x / distance) * enemy_speed
        enemy_pos[1] += (direction_y / distance) * enemy_speed
    
    # 检查碰撞
    if (abs(player_pos[0] - enemy_pos[0]) < block_size and abs(player_pos[1] - enemy_pos[1]) < block_size):
        print("You lose!")
        running = False
    
    # 绘制背景、玩家和敌人
    screen.fill(WHITE)
    pygame.draw.rect(screen, GREEN, (*player_pos, block_size, block_size))
    pygame.draw.rect(screen, RED, (*enemy_pos, enemy_size, enemy_size))
    
    # 刷新屏幕
    pygame.display.flip()
    pygame.time.Clock().tick(30)

pygame.quit()
sys.exit()