python_不误正业之贪吃蛇

时间:2022-07-25
本文章向大家介绍python_不误正业之贪吃蛇,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

python贪吃蛇

概述

一直以来就想学这个,玩玩看 教程来自B站python学习者

备注:年前完成,20200818测试

代码

# -*- coding: utf-8 -*-
import sys  # 系统交互的模块
import random  # 随机产生食物的位置
import pygame  # 开发游戏的模块,需要额外pip安装

screen_x = 600  # 界面大小
screen_y = 600  # 界面大小

# 添加类
# 蛇

class Snake(object): 
    #   属性 1.初始化蛇的长度
    #        2.蛇开始的位置
    def __init__(self):
        # 默认初始方向和长度
        self.direction = pygame.K_RIGHT  # 蛇的方向
        self.body = []  # 蛇的长度
        for x in range(5):
            self.addnode()

    #   行为:1.吃食物
    #         2.死亡
    #         3.移动
    #         4.方向

    def addnode(self):
        # 设置初始化蛇的位置
        left, top = (0, 0)
        if self.body:
            left, top = (self.body[0].left, self.body[0].top)
        node = pygame.Rect(left, top, 25, 25)
        if self.direction == pygame.K_LEFT:
            node.left -= 25
        if self.direction == pygame.K_RIGHT:
            node.left += 25
        elif self.direction == pygame.K_UP:
            node.top -= 25
        elif self.direction == pygame.K_DOWN:
            node.top += 25
        self.body.insert(0, node)

    # 移动后删除原始位置像素点
    def delnode(self):
        self.body.pop()

    # 死亡方法
    def isdead(self):
        # 撞墙
        if self.body[0].x not in range(screen_x):
            return True
        if self.body[0].y not in range(screen_y):
            return True
        # 撞自己
        if self.body[0] in self.body[1:]:
            return True
        return False

    # 移动
    def move(self):
        self.addnode()
        self.delnode()

    # 改变方向
    def changedirection(self, curkey):
        LR = [pygame.K_LEFT, pygame.K_RIGHT]
        UD = [pygame.K_UP, pygame.K_DOWN]

        if curkey in LR + UD:
            # 如果键盘为左右,蛇身子为左右则不执行
            if (curkey in LR) and (self.direction in LR):
                return
            # 如果键盘为上下,蛇身子为上下则不执行
            if (curkey in UD) and (self.direction in UD):
                return
            # 其他情况为键盘
            self.direction = curkey


# 食物
class Food:
    def __init__(self):
        # 初始化位置
        self.rect = pygame.Rect(-25, 0, 25, 25)

    def remove(self):
        self.rect.x = -25

    def set(self):
        if self.rect.x == -25:
            allpos = []
            # 不能靠墙太近
            for pos in range(25, screen_x-25, 25):
                allpos.append(pos)
            self.rect.left = random.choice(allpos)
            self.rect.top = random.choice(allpos)
            print(self.rect)


# 主函数核心
def main():
    pygame.init()  # 游戏初始化
    # 定义游戏界面大小
    screen_size = (screen_x, screen_y)
    # 返回到界面
    screen = pygame.display.set_mode(screen_size)
    pygame.display.set_caption("瞎的贪吃蛇")  # 窗口标题
    clock = pygame.time.Clock()  # 游戏的刷新频率
    scores = 0  # 初始成绩
    isdead = False  # 死亡
    snake = Snake()
    food = Food()
    while True:
        for event in pygame.event.get():
            # 如果退出
            if event.type == pygame.QUIT:
                sys.exit()
            # 如果键盘事件
            if event.type == pygame.KEYDOWN:
                snake.changedirection(event.key)
                # 如果没死和按空格返回游戏
                if event.key == pygame.K_SPACE and isdead:
                    return main()
        # 填充主板颜色
        screen.fill((255, 255, 255))

        # 画蛇身体
        if not isdead:
            snake.move()
        for rect in snake.body:
            pygame.draw.rect(screen, (20, 220, 39), rect, 0)

        # 显示死亡文字
        isdead = snake.isdead()
        if isdead:
            show_text(screen, (100, 100), "you dead!", (227, 29, 18), False, 100)
            show_text(
                screen, (150, 260), "press space to try again", (0, 0, 22), False, 30
            )
        # 食物处理,吃到+1
        # 如果蛇头和食物重叠,则运行
        if food.rect == snake.body[0]:
            scores += 50
            food.remove()
            snake.addnode()
        # 添加新的食物
        food.set()
        pygame.draw.rect(screen, (136, 0, 24), food.rect, 0)
        # 显示分数文字
        show_text(screen, (50, 500), "Scores: " + str(scores), (223, 223, 223))
        # 更新
        pygame.display.update()
        clock.tick(10)


def show_text(
    screen, pos, text, color, font_bold=False, font_size=60, font_italic=False):
    # 获取系统字体,设置大小
    cur_font = pygame.font.SysFont("宋体", font_size)
    # 设置粗体
    cur_font.set_bold(font_bold)
    # 设置斜体
    cur_font.set_italic(font_italic)
    # 设置文字内容
    text_fmt = cur_font.render(text, 1, color)
    # 绘制文字
    screen.blit(text_fmt, pos)
# 调用函数
main()

测试结果

游戏测试结果

运行测试

死亡测试

得分测试

结束语

这几天心情颇不宁静,静下心来写点东西总是很难,思来想去,幸福的生活是一样的,不幸福的生活各式各样。

北京,我又要回来了。