游戏代码运行1:贪吃蛇游戏

yumo6662个月前 (03-09)技术文章93

以下是一个使用 Pygame 实现的简单贪吃蛇游戏代码。这个代码适合初学者学习,涵盖了游戏循环、事件处理、碰撞检测等核心概念。


贪吃蛇游戏代码

python

import pygame
import time
import random

# 初始化 Pygame
pygame.init()

# 定义颜色
WHITE = (255, 255, 255)
YELLOW = (255, 255, 102)
BLACK = (0, 0, 0)
RED = (213, 50, 80)
GREEN = (0, 255, 0)
BLUE = (50, 153, 213)

# 定义屏幕尺寸
WIDTH, HEIGHT = 600, 400

# 创建屏幕
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("贪吃蛇游戏")

# 定义时钟
clock = pygame.time.Clock()

# 定义蛇的块大小和速度
BLOCK_SIZE = 20
SNAKE_SPEED = 15

# 定义字体
font_style = pygame.font.SysFont("bahnschrift", 25)
score_font = pygame.font.SysFont("comicsansms", 35)

# 显示分数
def display_score(score):
    value = score_font.render("分数: " + str(score), True, YELLOW)
    screen.blit(value, [0, 0])

# 画蛇
def draw_snake(block_size, snake_list):
    for block in snake_list:
        pygame.draw.rect(screen, GREEN, [block[0], block[1], block_size, block_size])

# 显示消息
def display_message(msg, color):
    mesg = font_style.render(msg, True, color)
    screen.blit(mesg, [WIDTH / 6, HEIGHT / 3])

# 游戏循环
def game_loop():
    game_over = False
    game_close = False

    # 蛇的初始位置
    x = WIDTH / 2
    y = HEIGHT / 2

    # 蛇的移动方向
    x_change = 0
    y_change = 0

    # 蛇的身体
    snake_list = []
    snake_length = 1

    # 食物的位置
    food_x = round(random.randrange(0, WIDTH - BLOCK_SIZE) / BLOCK_SIZE) * BLOCK_SIZE
    food_y = round(random.randrange(0, HEIGHT - BLOCK_SIZE) / BLOCK_SIZE) * BLOCK_SIZE

    while not game_over:
        while game_close:
            screen.fill(BLUE)
            display_message("你输了!按 Q 退出游戏或 C 重新开始", RED)
            display_score(snake_length - 1)
            pygame.display.update()

            # 处理游戏结束后的输入
            for event in pygame.event.get():
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_q:
                        game_over = True
                        game_close = False
                    if event.key == pygame.K_c:
                        game_loop()

        # 处理事件
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                game_over = True
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT and x_change == 0:
                    x_change = -BLOCK_SIZE
                    y_change = 0
                elif event.key == pygame.K_RIGHT and x_change == 0:
                    x_change = BLOCK_SIZE
                    y_change = 0
                elif event.key == pygame.K_UP and y_change == 0:
                    y_change = -BLOCK_SIZE
                    x_change = 0
                elif event.key == pygame.K_DOWN and y_change == 0:
                    y_change = BLOCK_SIZE
                    x_change = 0

        # 检查是否撞墙
        if x >= WIDTH or x < 0 or y>= HEIGHT or y < 0: game_close='True' x y screen.fillblack pygame.draw.rectscreen red food_x food_y block_size block_size snake_head='[x,' y snake_list.appendsnake_head if lensnake_list> snake_length:
            del snake_list[0]

        # 检查是否撞到自己
        for block in snake_list[:-1]:
            if block == snake_head:
                game_close = True

        # 画蛇
        draw_snake(BLOCK_SIZE, snake_list)
        display_score(snake_length - 1)

        # 更新屏幕
        pygame.display.update()

        # 检查是否吃到食物
        if x == food_x and y == food_y:
            food_x = round(random.randrange(0, WIDTH - BLOCK_SIZE) / BLOCK_SIZE) * BLOCK_SIZE
            food_y = round(random.randrange(0, HEIGHT - BLOCK_SIZE) / BLOCK_SIZE) * BLOCK_SIZE
            snake_length += 1

        # 控制游戏速度
        clock.tick(SNAKE_SPEED)

    # 退出 Pygame
    pygame.quit()
    quit()

# 启动游戏
game_loop()

代码说明

  1. 游戏逻辑
  2. 蛇通过方向键控制移动。
  3. 吃到食物后,蛇的长度增加。
  4. 如果蛇撞到墙壁或自己,游戏结束。
  5. 核心功能
  6. pygame.event.get():处理用户输入。
  7. pygame.draw.rect():绘制蛇和食物。
  8. clock.tick():控制游戏帧率。
  9. 扩展建议
  10. 增加难度:随着分数提高,加快蛇的速度。
  11. 增加音效:使用 pygame.mixer 播放音效。
  12. 增加关卡:设计不同的地图或障碍物。

运行方法

  1. 安装 Pygame:pip install pygame
  2. 将代码保存为 snake_game.py。
  3. 运行代码:python snake_game.py

希望这个代码能帮助你理解贪吃蛇游戏的实现原理!

相关文章

一个使用 Python 和 Pygame 库编写的简单俄罗斯方块游戏代码示例

```pythonimport pygameimport random初始化 Pygamepygame.init()定义常量WIDTH, HEIGHT = 300, 600BLOCK_SIZE = 3...