贪吃蛇小游戏-简单开发版

发布于:2025-03-16 ⋅ 阅读:(19) ⋅ 点赞:(0)

一、需求

        本项目旨在开发一个经典的贪吃蛇游戏,用户可以通过键盘控制蛇的移动方向,让蛇吃掉随机出现在游戏区域内的食物,每吃掉一个食物,蛇的身体长度就会增加,同时得分也会相应提高。游戏结束的条件为蛇撞到游戏区域的边界或者撞到自己的身体。用户在游戏结束后可以选择退出游戏或者重新开始。

二、技术细节

1. 游戏库 :使用 pygame 库来创建游戏窗口、处理用户输入、绘制图形和控制游戏帧率。

2. 颜色定义 :使用RGB值定义了游戏中需要用到的各种颜色,如白色、黄色、黑色、红色、绿色和蓝色。

3. 游戏窗口 :定义了游戏窗口的大小,并创建了一个指定大小的游戏窗口。

4. 时钟对象 :使用 pygame.time.Clock() 创建了一个时钟对象,用于控制游戏的帧率。

5. 蛇的表示 :使用一个列表 snake_List 来表示蛇的身体,每个元素是一个包含蛇身体部分坐标的列表。

6. 食物的生成 :使用 random.randrange() 函数随机生成食物的位置,并确保食物的位置是 snake_block 的整数倍。

7. 碰撞检测 :在游戏循环中检查蛇是否撞到边界或自己的身体,如果是则游戏结束。

8. 用户输入处理 :使用 pygame.event.get() 获取用户的输入事件,根据用户按下的方向键来改变蛇的移动方向。

三、完整代码

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)

# 定义游戏窗口大小
dis_width = 800
dis_height = 600

# 创建游戏窗口
dis = pygame.display.set_mode((dis_width, dis_height))
pygame.display.set_caption('贪吃蛇游戏')

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

# 定义蛇的初始大小
snake_block = 10
snake_speed = 15

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


def Your_score(score):
    value = score_font.render("Your score: " + str(score), True, yellow)
    dis.blit(value, [0, 0])


def our_snake(snake_block, snake_list):
    for x in snake_list:
        pygame.draw.rect(dis, black, [x[0], x[1], snake_block, snake_block])


def message(msg, color):
    mesg = font_style.render(msg, True, color)
    dis.blit(mesg, [dis_width / 6, dis_height / 3])


def gameLoop():
    game_over = False
    game_close = False

    # 蛇的初始位置
    x1 = dis_width / 2
    y1 = dis_height / 2

    # 蛇的移动速度
    x1_change = 0
    y1_change = 0

    # 蛇的身体列表
    snake_List = []
    Length_of_snake = 1

    # 食物的随机位置
    foodx = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
    foody = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0

    while not game_over:

        while game_close == True:
            dis.fill(blue)
            message("You lost! Press Q to quit or C to play again", red)
            Your_score(Length_of_snake - 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:
                        gameLoop()

        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:
                    x1_change = -snake_block
                    y1_change = 0
                elif event.key == pygame.K_RIGHT:
                    x1_change = snake_block
                    y1_change = 0
                elif event.key == pygame.K_UP:
                    y1_change = -snake_block
                    x1_change = 0
                elif event.key == pygame.K_DOWN:
                    y1_change = snake_block
                    x1_change = 0

        # 检查蛇是否撞到边界
        if x1 >= dis_width or x1 < 0 or y1 >= dis_height or y1 < 0:
            game_close = True
        x1 += x1_change
        y1 += y1_change
        dis.fill(blue)
        pygame.draw.rect(dis, green, [foodx, foody, snake_block, snake_block])
        snake_Head = []
        snake_Head.append(x1)
        snake_Head.append(y1)
        snake_List.append(snake_Head)
        if len(snake_List) > Length_of_snake:
            del snake_List[0]

        # 检查蛇是否撞到自己
        for x in snake_List[:-1]:
            if x == snake_Head:
                game_close = True

        our_snake(snake_block, snake_List)
        Your_score(Length_of_snake - 1)

        pygame.display.update()

        # 检查蛇是否吃到食物
        if x1 == foodx and y1 == foody:
            foodx = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
            foody = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0
            Length_of_snake += 1

        clock.tick(snake_speed)

    pygame.quit()
    quit()


gameLoop()

四、游戏运行

1. 环境要求

        确保你的系统已经安装了Python和 pygame 库。如果没有安装 pygame 库,可以使用以下命令进行安装:

pip install pygame

2. 运行步骤

        打开终端或命令提示符。

        导航到包含 snake_game.py 文件的目录。

        运行以下命令启动游戏:

python snake_game.py

3. 游戏操作说明

        使用方向键(上、下、左、右)控制蛇的移动方向。

        当蛇撞到边界或自己的身体时,游戏结束,此时会显示得分,并提示你按 Q 键退出游戏或按 C 键重新开始游戏。


网站公告

今日签到

点亮在社区的每一天
去签到