跳到正文

休闲·娱乐

抢饭

pcl5约 32 分钟
原文
文章信息与版本

文章信息

发布
2025年8月19日
收录
2026年2月4日
更新
2026年11月14日
篇幅
约 32 分钟

版本

  1. v1当前
Python
import pygame
import random
import math
import sys

# 初始化pygame
pygame.init()

# 游戏常量
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
TILE_SIZE = 40
FPS = 60

# 颜色定义
BACKGROUND = (30, 30, 50)
PLAYER_COLOR = (70, 130, 180)
FOOD_COLOR = (255, 215, 0)
OBSTACLE_COLOR = (139, 69, 19)
OTHER_STUDENT_COLOR = (220, 20, 60)
TEXT_COLOR = (255, 255, 255)
UI_BG = (0, 0, 0, 180)
PATH_COLOR = (100, 100, 150)
WALL_COLOR = (50, 50, 70)

# 创建游戏窗口
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("食堂抢饭大冒险 - 肉鸽游戏")
clock = pygame.time.Clock()

# 加载字体
try:
    # 尝试使用系统字体,如果失败则使用默认字体
    font_large = pygame.font.SysFont("SimHei", 48)
    font_medium = pygame.font.SysFont("SimHei", 32)
    font_small = pygame.font.SysFont("SimHei", 24)
except:
    font_large = pygame.font.Font(None, 48)
    font_medium = pygame.font.Font(None, 32)
    font_small = pygame.font.Font(None, 24)


class Player:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.radius = 15
        self.speed = 5
        self.health = 100
        self.food_collected = 0
        self.dash_cooldown = 0
        self.dash_duration = 0
        self.dash_speed = 10

    def move(self, dx, dy):
        # 冲刺状态
        if self.dash_duration > 0:
            speed = self.dash_speed
            self.dash_duration -= 1
        else:
            speed = self.speed

        if self.dash_cooldown > 0:
            self.dash_cooldown -= 1

        # 计算新位置
        new_x = self.x + dx * speed
        new_y = self.y + dy * speed

        # 边界检查
        if new_x - self.radius > 0 and new_x + self.radius < SCREEN_WIDTH:
            self.x = new_x
        if new_y - self.radius > 0 and new_y + self.radius < SCREEN_HEIGHT:
            self.y = new_y

    def dash(self):
        if self.dash_cooldown == 0:
            self.dash_duration = 10
            self.dash_cooldown = 60  # 1秒冷却

    def draw(self, surface):
        # 绘制玩家
        pygame.draw.circle(surface, PLAYER_COLOR, (int(self.x), int(self.y)), self.radius)
        pygame.draw.circle(surface, (255, 255, 255), (int(self.x), int(self.y)), self.radius, 2)

        # 绘制冲刺冷却指示器
        if self.dash_cooldown > 0:
            cooldown_percent = 1 - (self.dash_cooldown / 60)
            pygame.draw.arc(surface, (0, 200, 255),
                            (self.x - self.radius - 5, self.y - self.radius - 5,
                             self.radius * 2 + 10, self.radius * 2 + 10),
                            -math.pi / 2, -math.pi / 2 + 2 * math.pi * cooldown_percent, 3)


class Food:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.radius = 8
        self.type = random.choice(["鸡腿", "汉堡", "披萨", "水果", "饮料"])
        self.colors = {
            "鸡腿": (210, 180, 140),
            "汉堡": (205, 133, 63),
            "披萨": (255, 140, 0),
            "水果": (255, 99, 71),
            "饮料": (30, 144, 255)
        }

    def draw(self, surface):
        color = self.colors.get(self.type, FOOD_COLOR)
        pygame.draw.circle(surface, color, (int(self.x), int(self.y)), self.radius)
        pygame.draw.circle(surface, (255, 255, 255), (int(self.x), int(self.y)), self.radius, 1)


class Obstacle:
    def __init__(self, x, y, width, height):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.rect = pygame.Rect(x, y, width, height)

    def draw(self, surface):
        pygame.draw.rect(surface, OBSTACLE_COLOR, self.rect)
        # 添加纹理
        for i in range(0, self.width, 5):
            for j in range(0, self.height, 5):
                if random.random() > 0.7:
                    pygame.draw.rect(surface, (160, 82, 45),
                                     (self.x + i, self.y + j, 2, 2))


class OtherStudent:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.radius = 12
        self.speed = random.uniform(1.0, 2.5)
        self.direction = random.uniform(0, 2 * math.pi)
        self.change_direction_timer = random.randint(30, 90)
        self.target = None

    def move(self, player):
        self.change_direction_timer -= 1

        # 随机改变方向或追踪玩家
        if self.target is None or self.change_direction_timer <= 0:
            if random.random() < 0.3 and self.distance_to(player) < 200:
                self.target = player
            else:
                self.direction = random.uniform(0, 2 * math.pi)
                self.target = None
                self.change_direction_timer = random.randint(30, 90)

        # 追踪玩家
        if self.target:
            dx = self.target.x - self.x
            dy = self.target.y - self.y
            dist = max(1, math.sqrt(dx * dx + dy * dy))
            self.direction = math.atan2(dy, dx)

        # 更新位置
        self.x += math.cos(self.direction) * self.speed
        self.y += math.sin(self.direction) * self.speed

        # 边界检查
        self.x = max(self.radius, min(SCREEN_WIDTH - self.radius, self.x))
        self.y = max(self.radius, min(SCREEN_HEIGHT - self.radius, self.y))

    def distance_to(self, other):
        return math.sqrt((self.x - other.x) ** 2 + (self.y - other.y) ** 2)

    def draw(self, surface):
        pygame.draw.circle(surface, OTHER_STUDENT_COLOR, (int(self.x), int(self.y)), self.radius)
        pygame.draw.circle(surface, (255, 255, 255), (int(self.x), int(self.y)), self.radius, 1)

        # 绘制眼睛
        eye_offset = 5
        eye_radius = 3
        angle = self.direction
        left_eye_x = self.x + eye_offset * math.cos(angle + math.pi / 4)
        left_eye_y = self.y + eye_offset * math.sin(angle + math.pi / 4)
        right_eye_x = self.x + eye_offset * math.cos(angle - math.pi / 4)
        right_eye_y = self.y + eye_offset * math.sin(angle - math.pi / 4)

        pygame.draw.circle(surface, (255, 255, 255), (int(left_eye_x), int(left_eye_y)), eye_radius)
        pygame.draw.circle(surface, (255, 255, 255), (int(right_eye_x), int(right_eye_y)), eye_radius)
        pygame.draw.circle(surface, (0, 0, 0), (int(left_eye_x), int(left_eye_y)), eye_radius // 2)
        pygame.draw.circle(surface, (0, 0, 0), (int(right_eye_x), int(right_eye_y)), eye_radius // 2)


class Game:
    def __init__(self):
        self.reset()

    def reset(self):
        self.player = Player(SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2)
        self.foods = []
        self.obstacles = []
        self.other_students = []
        self.game_over = False
        self.level_complete = False
        self.level = 1
        self.score = 0
        self.time_remaining = 60 * FPS  # 60秒
        self.generate_level()

    def generate_level(self):
        # 清除旧对象
        self.foods = []
        self.obstacles = []
        self.other_students = []

        # 创建食堂路径
        self.create_cafeteria_path()

        # 添加食物
        for _ in range(10 + self.level * 2):
            valid_position = False
            while not valid_position:
                x = random.randint(30, SCREEN_WIDTH - 30)
                y = random.randint(30, SCREEN_HEIGHT - 30)
                valid_position = True

                # 检查是否与障碍物重叠
                for obstacle in self.obstacles:
                    if obstacle.rect.collidepoint(x, y):
                        valid_position = False
                        break

                # 检查是否与其他食物太近
                for food in self.foods:
                    if math.sqrt((x - food.x) ** 2 + (y - food.y) ** 2) < 30:
                        valid_position = False
                        break

            self.foods.append(Food(x, y))

        # 添加其他学生
        for _ in range(3 + self.level):
            x = random.randint(50, SCREEN_WIDTH - 50)
            y = random.randint(50, SCREEN_HEIGHT - 50)
            self.other_students.append(OtherStudent(x, y))

        # 重置时间(每级增加10秒)
        self.time_remaining = (60 + self.level * 10) * FPS

    def create_cafeteria_path(self):
        # 创建食堂布局 - 路径和障碍物
        path_width = 150

        # 主通道(垂直)
        pygame.draw.rect(screen, PATH_COLOR, (SCREEN_WIDTH // 2 - path_width // 2, 0, path_width, SCREEN_HEIGHT))

        # 横向通道
        num_horizontal = 4
        spacing = SCREEN_HEIGHT // (num_horizontal + 1)
        for i in range(num_horizontal):
            y_pos = (i + 1) * spacing
            pygame.draw.rect(screen, PATH_COLOR, (0, y_pos - path_width // 2, SCREEN_WIDTH, path_width))

        # 添加桌子(障碍物)
        table_size = 80
        for row in range(3):
            for col in range(3):
                x = 100 + col * 200
                y = 100 + row * 150
                self.obstacles.append(Obstacle(x, y, table_size, table_size))

        # 添加墙壁
        wall_thickness = 20
        # 上墙
        self.obstacles.append(Obstacle(0, 0, SCREEN_WIDTH, wall_thickness))
        # 下墙
        self.obstacles.append(Obstacle(0, SCREEN_HEIGHT - wall_thickness, SCREEN_WIDTH, wall_thickness))
        # 左墙
        self.obstacles.append(Obstacle(0, 0, wall_thickness, SCREEN_HEIGHT))
        # 右墙
        self.obstacles.append(Obstacle(SCREEN_WIDTH - wall_thickness, 0, wall_thickness, SCREEN_HEIGHT))

    def update(self):
        if self.game_over or self.level_complete:
            return

        # 更新时间
        self.time_remaining -= 1
        if self.time_remaining <= 0:
            self.game_over = True
            return

        # 移动其他学生
        for student in self.other_students:
            student.move(self.player)

            # 检测与玩家的碰撞
            distance = student.distance_to(self.player)
            if distance < student.radius + self.player.radius:
                self.player.health -= 0.5
                if self.player.health <= 0:
                    self.game_over = True

        # 检测食物收集
        for food in self.foods[:]:
            distance = math.sqrt((self.player.x - food.x) ** 2 + (self.player.y - food.y) ** 2)
            if distance < self.player.radius + food.radius:
                self.foods.remove(food)
                self.player.food_collected += 1
                self.score += 10
                self.player.health = min(100, self.player.health + 5)

                # 检查是否收集了足够的食物
                if self.player.food_collected >= 5 + self.level:
                    self.level_complete = True

    def next_level(self):
        self.level += 1
        self.player.food_collected = 0
        self.player.health = 100
        self.level_complete = False
        self.generate_level()

    def draw(self, surface):
        # 绘制背景
        surface.fill(BACKGROUND)

        # 绘制路径
        path_width = 150
        pygame.draw.rect(surface, PATH_COLOR, (SCREEN_WIDTH // 2 - path_width // 2, 0, path_width, SCREEN_HEIGHT))

        # 横向通道
        num_horizontal = 4
        spacing = SCREEN_HEIGHT // (num_horizontal + 1)
        for i in range(num_horizontal):
            y_pos = (i + 1) * spacing
            pygame.draw.rect(surface, PATH_COLOR, (0, y_pos - path_width // 2, SCREEN_WIDTH, path_width))

        # 绘制障碍物
        for obstacle in self.obstacles:
            obstacle.draw(surface)

        # 绘制食物
        for food in self.foods:
            food.draw(surface)

        # 绘制其他学生
        for student in self.other_students:
            student.draw(surface)

        # 绘制玩家
        self.player.draw(surface)

        # 绘制UI
        self.draw_ui(surface)

        # 游戏结束或过关显示
        if self.game_over:
            self.draw_game_over(surface)
        elif self.level_complete:
            self.draw_level_complete(surface)

    def draw_ui(self, surface):
        # 半透明背景
        ui_surface = pygame.Surface((SCREEN_WIDTH, 80), pygame.SRCALPHA)
        ui_surface.fill(UI_BG)
        surface.blit(ui_surface, (0, 0))

        # 分数
        score_text = font_medium.render(f"分数: {self.score}", True, TEXT_COLOR)
        surface.blit(score_text, (20, 20))

        # 等级
        level_text = font_medium.render(f"等级: {self.level}", True, TEXT_COLOR)
        surface.blit(level_text, (20, 50))

        # 收集的食物
        food_text = font_medium.render(f"食物: {self.player.food_collected}/{(5 + self.level)}", True, TEXT_COLOR)
        surface.blit(food_text, (SCREEN_WIDTH // 2 - 60, 20))

        # 生命值
        pygame.draw.rect(surface, (100, 0, 0), (SCREEN_WIDTH // 2 - 60, 50, 120, 20))
        pygame.draw.rect(surface, (0, 200, 0), (SCREEN_WIDTH // 2 - 60, 50, 120 * (self.player.health / 100), 20))
        pygame.draw.rect(surface, TEXT_COLOR, (SCREEN_WIDTH // 2 - 60, 50, 120, 20), 2)
        health_text = font_small.render(f"生命值: {int(self.player.health)}%", True, TEXT_COLOR)
        surface.blit(health_text, (SCREEN_WIDTH // 2 - health_text.get_width() // 2, 52))

        # 时间
        time_left = self.time_remaining // FPS
        time_text = font_medium.render(f"时间: {time_left}秒", True, TEXT_COLOR)
        surface.blit(time_text, (SCREEN_WIDTH - time_text.get_width() - 20, 20))

        # 操作提示
        controls_text = font_small.render("移动: WASD, 冲刺: 空格", True, TEXT_COLOR)
        surface.blit(controls_text, (SCREEN_WIDTH - controls_text.get_width() - 20, 50))

    def draw_game_over(self, surface):
        overlay = pygame.Surface((SCREEN_WIDTH, SCREEN_HEIGHT), pygame.SRCALPHA)
        overlay.fill((0, 0, 0, 200))
        surface.blit(overlay, (0, 0))

        game_over_text = font_large.render("游戏结束!", True, (255, 50, 50))
        surface.blit(game_over_text, (SCREEN_WIDTH // 2 - game_over_text.get_width() // 2, SCREEN_HEIGHT // 2 - 60))

        score_text = font_medium.render(f"最终分数: {self.score}", True, TEXT_COLOR)
        surface.blit(score_text, (SCREEN_WIDTH // 2 - score_text.get_width() // 2, SCREEN_HEIGHT // 2))

        level_text = font_medium.render(f"达到等级: {self.level}", True, TEXT_COLOR)
        surface.blit(level_text, (SCREEN_WIDTH // 2 - level_text.get_width() // 2, SCREEN_HEIGHT // 2 + 40))

        restart_text = font_medium.render("按R键重新开始", True, TEXT_COLOR)
        surface.blit(restart_text, (SCREEN_WIDTH // 2 - restart_text.get_width() // 2, SCREEN_HEIGHT // 2 + 100))

    def draw_level_complete(self, surface):
        overlay = pygame.Surface((SCREEN_WIDTH, SCREEN_HEIGHT), pygame.SRCALPHA)
        overlay.fill((0, 0, 0, 150))
        surface.blit(overlay, (0, 0))

        complete_text = font_large.render("关卡完成!", True, (50, 200, 50))
        surface.blit(complete_text, (SCREEN_WIDTH // 2 - complete_text.get_width() // 2, SCREEN_HEIGHT // 2 - 60))

        level_text = font_medium.render(f"进入等级 {self.level + 1}", True, TEXT_COLOR)
        surface.blit(level_text, (SCREEN_WIDTH // 2 - level_text.get_width() // 2, SCREEN_HEIGHT // 2))

        continue_text = font_medium.render("按空格键继续", True, TEXT_COLOR)
        surface.blit(continue_text, (SCREEN_WIDTH // 2 - continue_text.get_width() // 2, SCREEN_HEIGHT // 2 + 60))


# 创建游戏实例
game = Game()

# 游戏主循环
running = True
while running:
    # 处理事件
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_r:
                game.reset()
            elif event.key == pygame.K_SPACE:
                if game.level_complete:
                    game.next_level()
                else:
                    game.player.dash()

    # 获取按键状态
    keys = pygame.key.get_pressed()
    dx, dy = 0, 0
    if keys[pygame.K_w] or keys[pygame.K_UP]:
        dy -= 1
    if keys[pygame.K_s] or keys[pygame.K_DOWN]:
        dy += 1
    if keys[pygame.K_a] or keys[pygame.K_LEFT]:
        dx -= 1
    if keys[pygrrame.K_d] or keys[pygame.K_RIGHT]:
        dx += 1

    # 标准化对角线移动
    if dx != 0 and dy != 0:
        dx *= 0.7071
        dy *= 0.7071

    # 更新游戏状态
    game.player.move(dx, dy)
    game.update()

    # 绘制游戏
    game.draw(screen)

    # 更新显示
    pygame.display.flip()

    # 控制帧率
    clock.tick(FPS)

# 退出游戏
pygame.quit()
sys.exit()

需下载pygamepygame

原文