初学python,跟着各种教程写了个贪吃蛇小游戏。

部分代码借鉴了以下视频中的内容:

【智源学院】Python实战案例 — 贪吃蛇 (pygame)_哔哩哔哩_bilibili

以下为代码:

# 初始框架
import pygame
import randomclass Point:  # 将每个小方格定义为类似于坐标的形式col = 0row = 0def __init__(self, row, col):self.row = rowself.col = coldef copy(self):return Point(row=self.row, col=self.col)# 初始化
pygame.init()
clock = pygame.time.Clock()
W = 800  # 游戏部分窗口宽度
W_W = 1000  # 窗口总宽度
H = 600
ROW = 30  # 小方格行数
COL = 40  # 小方格列数
size = (W_W, H)
window = pygame.display.set_mode(size)  # 窗口大小
pygame.display.set_caption('贪吃蛇')
game_continue = True  # 控制开始和暂停的变量
dead = False  # 控制是否游戏结束的变量
score = 0  # 计分# 定义坐标和颜色
head = Point(row=int(ROW / 2), col=int(COL / 2))  # 初始时蛇头位置
head_color = (0, 128, 128)  # 蛇头颜色
bg_color = (255, 255, 255)  # 背景颜色
bg_color_right = (0, 200, 200)  # 右侧颜色
snake_color = (200, 200, 200)  # 蛇身颜色
font_color = (0, 0, 0)  # 字体颜色
direct = 'left'  # 开始时向左出发
snakes = []  # 蛇身坐标以链表形式存储# 生成食物的函数
def gen_food():while True:pos = Point(row=random.randint(0, ROW - 1), col=random.randint(0, COL - 1))is_coll = False# 是否跟蛇头撞上了if head.row == pos.row and head.col == pos.col:is_coll = True# 是否跟蛇身撞上了for snake_body in snakes:if snake_body.row == pos.row and snake_body.col == pos.col:is_coll = Truebreakif not is_coll:breakreturn pos# 在指定位置生成指定颜色的格子的函数
def rect(point, color):cell_width = W / COLcell_height = H / ROWleft = point.col * cell_width  # 格子左上点的x坐标top = point.row * cell_height  # ypygame.draw.rect(window, color, (left, top, cell_width, cell_height))# 开局前将已生成的蛇头坐标作为存储蛇身的链表的第一项
snakes.insert(0, head.copy())
# 开局前生成食物
food = gen_food()
food_color = (255, 255, 0)# 游戏循环
game_quit = False
while not game_quit:# 处理玩家输入的操作for event in pygame.event.get():# print(event)  # 需要调试测试时取消注释,即可输出所有检测到的eventif event.type == pygame.QUIT:game_quit = Trueelif event.type == pygame.KEYDOWN:if event.key == 119 or event.key == 1073741906:if direct == 'left' or direct == 'right':  # 只有蛇处于往左或往右运动的状态时才允许让蛇往上走direct = 'up'elif event.key == 115 or event.key == 1073741905:if direct == 'left' or direct == 'right':direct = 'down'elif event.key == 97 or event.key == 1073741904:if direct == 'up' or direct == 'down':direct = 'left'elif event.key == 100 or event.key == 1073741903:if direct == 'up' or direct == 'down':direct = 'right'elif event.key == 32:  # 按空格暂停游戏game_continue = not game_continueelif event.type == pygame.MOUSEBUTTONDOWN:m_x = event.pos[0]  # 鼠标位置x坐标m_y = event.pos[1]if 840 < m_x < 960 and 264 < m_y < 336:  # 鼠标点击继续时继续游戏game_continue = Trueelif 840 < m_x < 960 and 376 < m_y < 448:  # 鼠标点击暂停时暂停游戏game_continue = Falseelif 840 < m_x < 960 and 488 < m_y < 560:  # 鼠标点击退出时退出游戏game_quit = Trueif game_continue and not dead:  # 处于游戏继续状态并且没有结束时进行各种判断及移动# 未暂停时蛇头移动if direct == 'left':head.col -= 1elif direct == 'right':head.col += 1elif direct == 'up':head.row -= 1elif direct == 'down':head.row += 1# 检测是否游戏结束# 1.撞墙if head.col < 0 or head.row < 0 or head.col >= COL or head.row >= ROW:dead = True# 2.撞自己for snake in snakes:if head.col == snake.col and head.row == snake.row:dead = Truebreak# 判断是否吃到东西eat = head.row == food.row and head.col == food.col# 吃到东西的话加一分并重新产生食物if eat:score += 1food = gen_food()# 处理蛇身移动显示# 1.把蛇头坐标插入到链表snakes的头部snakes.insert(0, head.copy())# 2.若没吃到东西就把链表最后一项删除if not eat:snakes.pop()# 渲染# 背景及显示pygame.draw.rect(window, bg_color, (0, 0, W, H))  # 左侧白色背景pygame.draw.rect(window, bg_color_right, (W, 0, 200, H))  # 右侧蓝色背景pygame.draw.rect(window, bg_color, (W + 40, 40, 120, 72))  # 五个白色矩形pygame.draw.rect(window, bg_color, (W + 40, 152, 120, 72))pygame.draw.rect(window, bg_color, (W + 40, 264, 120, 72))pygame.draw.rect(window, bg_color, (W + 40, 376, 120, 72))pygame.draw.rect(window, bg_color, (W + 40, 488, 120, 72))font_name = pygame.font.match_font('MicrosoftYaHei', 40)  # 获取字体文件font = pygame.font.Font(font_name, 25)  # 设置方格内显示文字的字体text_begin = font.render('继续', True, font_color)text_rect = text_begin.get_rect(center=(900, 300))window.blit(text_begin, text_rect)text_begin = font.render('暂停', True, font_color)text_rect = text_begin.get_rect(center=(900, 412))window.blit(text_begin, text_rect)text_begin = font.render('退出', True, font_color)text_rect = text_begin.get_rect(center=(900, 524))window.blit(text_begin, text_rect)score_text = str(score)  # 将分数转换为str型变量text_begin = font.render(score_text, True, font_color)text_rect = text_begin.get_rect(center=(900, 76))window.blit(text_begin, text_rect)if not game_continue:  # 显示游戏已暂停text_begin = font.render('已暂停', True, font_color)text_rect = text_begin.get_rect(center=(900, 188))window.blit(text_begin, text_rect)if dead:text_begin = font.render('游戏结束', True, font_color)text_rect = text_begin.get_rect(center=(900, 188))window.blit(text_begin, text_rect)if not dead:  # 使游戏结束后清空屏幕# 食物rect(food, food_color)# 蛇身for snake in snakes:rect(snake, snake_color)# 蛇头rect(head, head_color)# 更新显示pygame.display.flip()# 设置帧频clock.tick(10)

Python 贪吃蛇小游戏相关推荐

  1. Python贪吃蛇小游戏_完整源码免费分享

    文章目录 Python 贪吃蛇小游戏 1. 导包 2. 配置初始化参数 3. 主函数及运行主体 4. 画食物的函数 5. 画贪吃蛇的函数 6. 画网格的函数(非必选,觉得多余的可以忽略此项) 7. 操 ...

  2. python 贪吃蛇小游戏代码_10分钟再用Python编写贪吃蛇小游戏

    Python编写贪吃蛇 前不久我们公众号发布了一篇C++编写贪吃蛇小游戏的推文,反响空前.看来大家对这类简单易上手小游戏还是很喜爱的. 恰逢2018年IEEE Spectrum编程语言排行榜新鲜出炉, ...

  3. python贪吃蛇小游戏_python开发贪吃蛇小游戏

    3.概要设计 3.1 程序功能模块 由设计应解决的问题可知,本次的设计是使用用方向键来实现一个简易的贪吃蛇小游戏的程序,具体的功能模块如图3-1所示. 图3-1 程序功能模块 Fig.3-1 prog ...

  4. python贪吃蛇小游戏制作思路详解

    很多时候,游戏都是一种可以发泄自己内心情绪的工具,在游戏中,我们可以忘记经历过的很多不快.如今呢,随着软硬件的不断提高,游戏市场越来越繁华红火,很多游戏都动辄好几个G.让人不得不感叹啊,以前那种玩贪吃 ...

  5. Python贪吃蛇小游戏教程

    今天教大家使用pygame编一个简单贪吃蛇小游戏. 1.导库 import pygame, sys, time, random, zt """ zt库是用来搞游戏暂停的 ...

  6. python小游戏代码大全-【程序源代码】python贪吃蛇小游戏

    关键字:python 游戏 贪吃蛇 正文 | 内容 在网络还不发达,没有平板电脑和手机的童年;电视机里的动画片和小游戏曾经陪伴我们度过了欢乐的时光.扫雷.贪吃蛇.俄罗斯方块.58坦克大战.超级玛丽.魂 ...

  7. python贪吃蛇小游戏代码_python 贪吃蛇小游戏代码

    #!/usr/bin/python # -*- coding: UTF-8 -*- #作者:黄哥 #链接:https://www.zhihu.com/question/55873159/answer/ ...

  8. 用Python做贪吃蛇小游戏

    用Python做贪吃蛇小游戏 简介 引言 游戏预览 结构图 代码框架图 代码讲解 main主函数-开始工作 show_start_info()欢迎进入游戏 running_game-让我们开始游戏吧 ...

  9. Python 简单实现贪吃蛇小游戏

    文章目录 1. pygame库的简介2. pygame库的安装3. python代码实现贪吃蛇小游戏4. pyinstaller打包成exe 很多人学习python,不知道从何学起. 很多人学习pyt ...

  10. Python实现贪吃蛇小游戏(双人模式)

    这篇文章主要为大家详细介绍了Python实现双人模式的贪吃蛇小游戏,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下 简单用py写了一个贪吃蛇游戏,有单人.双人模式,比较简 ...

最新文章

  1. PHPCMSv9首页显示分页点击下一页跳转链接出现错误,跳转到后台的解决方案
  2. td 内单选框不可用_材料特殊处理TD、TICN概述
  3. jq 实现发送验证码倒计时功能
  4. 使用bat文件实现批量重命名功能
  5. vivado----fpga硬件调试 (四)----mark_debug
  6. amr 转mp3 java_JAVA 音频转换AMR 转MP3,OS,Linux cent os 7
  7. [轉]Exploit Linux Kernel Slub Overflow
  8. ExtJs4 学习一
  9. V4L2视频应用程序编程架构
  10. UVA 11624 BFS
  11. 综述-自动驾驶中基于图像的3D目标检测
  12. 百度地图显示车辆运行轨迹(动态轨迹回放功能)
  13. 严格对角占优矩阵特征值_严格对角占优M-矩阵特征值的界
  14. Python类与对象最全总结大全(类、实例、属性方法、继承、派生、多态、内建函数)
  15. 计算机组成原理----有关数据通路
  16. spring的几种注入方式
  17. 可拖拽排序的GridView(高仿今日头条编辑频道效果)
  18. 98-微服务项目的编写(下篇)
  19. 51单片机之外部中断拙见
  20. 如何理解goto语句

热门文章

  1. Unity 内置渲染管线、SRP、URP、HDRP区别
  2. 【c++实现】模拟银行叫号系统
  3. c语言乐谱提取软件,SmartScore X2 Pro(乐谱扫描识别软件) V10.5.4 官方版
  4. Centos/Linux 源码安装wireshark与tshark任意版本
  5. mysql数据库银行项目题_银行数据库笔试编程题
  6. 软考初级程序员案例分析必考考点解析:
  7. Solidworks CAM入门教程,简单生成雕刻机刀路,经验分享
  8. ICEM使用经验与网格划分错误分析
  9. iweboffice文档内容服务器文件,iWebOffice2015使用常见问题-NTKOOffice文档控件.doc
  10. 使用PHP自带的ZipArchive的一些问题