利用pygame写贪吃蛇小游戏

相信很多小伙伴在小时候都玩过贪吃蛇、超级玛丽、扫雷、魂斗罗、俄罗斯方块、58坦克等这些小游戏,这些小游戏我小时候都玩过;还记得当时家里有一台黑白电视,我当时特别喜欢玩游戏然后把零花钱全部存起来买了游戏器材。回忆起了小时候的画面,一种兴奋感就上来了,于是写了贪吃蛇小游戏来记录过去的美好时光。
环境: python3.8、pycharm
下面的代码注释也很详细,不了解pygame如何使用的小伙伴也可以看我之前写的超级详细的pygame,一起来学习吧!

# 导入模块及库
import pygame, sys, random
from pygame.math import Vector2


class Fruit:  # 创建水果类
    def __init__(self):
        self.randomize()  # 调用随机函数

    def draw_fruit(self):  # 绘制水果
        fruit_rect = pygame.Rect(int(self.pos.x * cell_size), int(self.pos.y * cell_size), cell_size,
                                 cell_size)  # 创建矩形需要四个不同方位
        screen.blit(apple, fruit_rect)

    def randomize(self):
        self.x = random.randint(0, cell_number - 1)  # 将X设为随机0~19
        self.y = random.randint(0, cell_number - 1)  # 将Y设为随机0~19
        self.pos = Vector2(self.x, self.y)  # 把X\Y放入向量内,二维数据


class Snake:  # 创建蛇类
    def __init__(self):
        self.body = [Vector2(5, 10), Vector2(6, 10), Vector2(7, 10)]  # 设置蛇在这三个区间中
        self.direction = Vector2(-1, 0)  # 假设它现在是1,0,所以只会向右移动
        self.new_block = False

    def draw_snake(self):  # 绘制蛇
        for block in self.body:
            x_pos = int(block.x * cell_size)
            y_pos = int(block.y * cell_size)
            # 创建一个矩形,画矩形
            block_rect = pygame.Rect(x_pos, y_pos, cell_size, cell_size)
            pygame.draw.rect(screen, (183, 111, 122), block_rect)

    def move_snake(self):  # 移动蛇
        if self.new_block == True:
            body_copy = self.body[:]
            body_copy.insert(0, body_copy[0] + self.direction)  # 从索引0开始插入
            self.body = body_copy[:]  # 复制自己的身体
            self.new_block = False
        else:
            body_copy = self.body[:-1]  # 拷贝从第一个到最后一个
            body_copy.insert(0, body_copy[0] + self.direction)  # 从索引0开始插入
            self.body = body_copy[:]  # 复制自己的身体

    def add_block(self):
        self.new_block = True


class Main:  # 主类
    def __init__(self):
        self.snake = Snake()
        self.fruit = Fruit()

    def update(self):
        self.snake.move_snake()  # 显示蛇移动
        self.check_collision()  # 调用查看碰撞函数
        self.check_fail()  # 调用查看游戏是否失败

    def draw_elements(self):  # 画元素
        self.fruit.draw_fruit()  # 调用水果类中的方法
        self.snake.draw_snake()  # 调用蛇类中的方法

    def check_collision(self):  # 查看碰撞
        if self.fruit.pos == self.snake.body[0]:  # 检查水果的位置,当蛇吃水果时,水果消失,蛇变大
            # print('蛇吃了水果')  # 查看蛇是否碰到了水果
            # 出现新的水果
            self.fruit.randomize()
            # 再给蛇添加一个方块
            self.snake.add_block()

    def check_fail(self):  # 查看游戏失败
        # 检查蛇是否超出边界线
        if not 0 <= self.snake.body[0].x < cell_number or not 0 <= self.snake.body[0].y < cell_number:
            self.game_over()
        # 检查蛇是否击中自己
        for block in self.snake.body[1:]:
            if block == self.snake.body[0]:
                self.game_over()

    def game_over(self):
        pygame.quit()
        sys.exit()  # 用于退出结束游戏并退出


# 初始化界面
pygame.init()
cell_size = 40  # 单元格大小设置为40
cell_number = 20  # 单元格个数设置为20
# screen = pygame.display.set_mode((400, 500))   # 窗口大小
screen = pygame.display.set_mode((cell_number * cell_size, cell_number * cell_size))  # 窗口大小
pygame.display.set_caption('贪吃蛇')  # 游戏标题
clock = pygame.time.Clock()  # 时钟帮助我们影响时间和饼图游戏

apple = pygame.image.load('apple.png').convert_alpha()  # 加载苹果

SCREEN_UPDATE = pygame.USEREVENT  # 自定义一个事件
pygame.time.set_timer(SCREEN_UPDATE, 150)  # 设置没150毫秒触发一次

main_game = Main()  # 调用主类

# 设置程序无限循环,直到python运行时退出结束
while True:
    for event in pygame.event.get():  # 获取事件并逐类响应
        if event.type == pygame.QUIT:  # 设置退出事件
            pygame.quit()
            sys.exit()  # 用于退出结束游戏并退出
        if event.type == SCREEN_UPDATE:  # 获取事件,并更新屏幕
            # snake.move_snake()  # 显示蛇移动
            main_game.update()
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:  # 向上
                if main_game.snake.direction.y != 1:
                    main_game.snake.direction = Vector2(0, -1)
            if event.key == pygame.K_RIGHT:  # 向右
                if main_game.snake.direction.x != -1:
                    main_game.snake.direction = Vector2(1, 0)
            if event.key == pygame.K_DOWN:  # 向下
                if main_game.snake.direction.y != -1:
                    main_game.snake.direction = Vector2(0, 1)
            if event.key == pygame.K_LEFT:  # 向左
                if main_game.snake.direction.x != 1:
                    main_game.snake.direction = Vector2(-1, 0)

    screen.fill((175, 215, 70))  # RGB三原色:红、绿、蓝
    main_game.draw_elements()  # 调用主类中的方法
    pygame.display.update()  # 刷新屏幕,对显示窗口进行更新,默认窗口全部重绘
    clock.tick(60)  # 每秒程序不能超过60次

这是贪吃蛇的简单版本,后期会陆续写新的版本并更新出来!
作者:吴常文
出处:https://blog.csdn.net/qq_41405475
本文版权归作者和CSDN共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接。

猜你喜欢

转载自blog.csdn.net/qq_41405475/article/details/114437916