详细讲解用Python制作贪吃蛇游戏(附源码)

近几年来 Python 语言得到了快速发展,而 Pygame 作为 Python 开发应用和游戏必备的库更是展现了 Python 的优越性。今天我们就将借助 Pygame 实现贪吃蛇游戏。

CSDN大礼包:《2025年最新全套学习资料包》免费分享
在这里插入图片描述

步骤 1: 安装Pygame

在开始之前,确保你已经安装了Pygame库。如果没有安装,可以使用以下命令:

pip install pygame

步骤 2: 初始化Pygame和设置屏幕

首先,导入必要的库并初始化Pygame。

import pygame
import time
import random

# 初始化Pygame
pygame.init()

# 设置屏幕大小
screen_width = 600
screen_height = 400
screen = pygame.display.set_mode((screen_width, screen_height))

# 设置标题
pygame.display.set_caption('贪吃蛇')

# 设置时钟
clock = pygame.time.Clock()

# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (213, 50, 80)
green = (0, 255, 0)
blue = (50, 153, 213)

步骤 3: 定义游戏中的变量

定义蛇和食物的初始位置和尺寸。

snake_block = 10
snake_speed = 15

font_style = pygame.font.SysFont(None, 50)
score_font = pygame.font.SysFont(None, 35)

def your_score(score):
    value = score_font.render("Score: " + str(score), True, black)
    screen.blit(value, [0, 0])

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

def message(msg, color):
    mesg = font_style.render(msg, True, color)
    screen.blit(mesg, [screen_width / 6, screen_height / 3])

步骤 4: 编写游戏循环

这是游戏的核心部分,包括处理事件、移动蛇、检测碰撞和更新屏幕。

def gameLoop():
    game_over = False
    game_close = False

    x1 = screen_width / 2
    y1 = screen_height / 2

    x1_change = 0
    y1_change = 0

    snake_List = []
    Length_of_snake = 1

    foodx = round(random.randrange(0, screen_width - snake_block) / 10.0) * 10.0
    foody = round(random.randrange(0, screen_height - snake_block) / 10.0) * 10.0

    while not game_over:

        while game_close:
            screen.fill(blue)
            message("You Lost! Press Q-Quit or C-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 >= screen_width or x1 < 0 or y1 >= screen_height or y1 < 0:
            game_close = True
        x1 += x1_change
        y1 += y1_change
        screen.fill(blue)
        pygame.draw.rect(screen, 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, screen_width - snake_block) / 10.0) * 10.0
            foody = round(random.randrange(0, screen_height - snake_block) / 10.0) * 10.0
            Length_of_snake += 1

        clock.tick(snake_speed)

    pygame.quit()
    quit()

gameLoop()

代码解释

  1. 初始化Pygame:必须调用pygame.init()来初始化所有的Pygame模块。
  2. 设置屏幕:使用pygame.display.set_mode()创建一个窗口。
  3. 定义颜色和速度:设置一些基本颜色和蛇的速度。
  4. 定义函数
    • your_score(score):显示当前得分。
    • our_snake(snake_block, snake_list):绘制蛇。
    • message(msg, color):显示信息。
  5. 游戏循环
    • 处理游戏事件,如按键。
    • 移动蛇并检查是否撞墙或自撞。
    • 如果蛇吃到食物,增加蛇的长度并生成新的食物。
    • 更新屏幕显示。
  6. 游戏结束和重新开始:当蛇撞墙或自撞时,显示游戏结束信息,并允许玩家选择重新开始或退出游戏。

这段代码创建了一个简单的贪吃蛇游戏。你可以通过修改代码来添加更多功能,如增加难度、不同的关卡、音效等。希望你在这个过程中学到有用的东西!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值