pygame - 贪吃蛇小游戏

蛇每吃掉一个身体块,蛇身就增加一个长度。为了统一计算,界面的尺寸和游戏元素的位置都是身体块长度的倍数
1. 上下左右方向键(或者ASDW键)控制蛇的移动方向
2. 空格键暂停和继续蛇的身体图片文件,复制到项目的asset\img目录下

import sys
import pygame
from pygame import Rect, font
import random# control panel contains the controllers and score
ControlPanelColor = (100, 100, 100)
# game panel is the main area for gaming
GamePanelColor = (0, 0, 0)
SnakeSize = 30
MaxWidthBlock = 15
MaxHeightBlock = 10
ControlPanelHeightBlock = 2
SnakeStartX = MaxWidthBlock // 2
SnakeStartY = MaxHeightBlock // 2
ControlPanelHeight = ControlPanelHeightBlock * SnakeSize
GamePanelWidth = MaxWidthBlock * SnakeSize
GamePanelHeight = MaxHeightBlock * SnakeSize
ControlPanelRect = Rect((0, 0), (GamePanelWidth, ControlPanelHeight))
GamePanelRect = Rect((0, ControlPanelHeight), (GamePanelWidth, GamePanelHeight - ControlPanelHeight))
Tick = 20
Tick_Snake_Move = 10
# two buttons to increase and decrease the game speed
minus_btn_rect = None
plus_btn_rect = None
# score
score_value = 0# the SnakeBody
class SnakeBody:def __init__(self, x, y, direction, ishead=False, istail=False):'''身体块,蛇身是由多个身体块组成,头和尾也是图案不同的身体块:param x: 身体块坐标x:param y: 身体块坐标y:param direction: 身体块显示的方向:param ishead: 是否头身体块:param istail:是否尾身体块'''self.__x = xself.__y = yself.__ishead = isheadself.__istail = istailself.__direction = directionname = Noneif self.__ishead:name = "head.png"elif self.__istail:name = "tail.png"else:name = "body.png"angle = 0match direction:case pygame.K_UP:angle = 0case pygame.K_DOWN:angle = 180case pygame.K_LEFT:angle = 90case pygame.K_RIGHT:angle = -90img = pygame.image.load(f"asset/img/{name}")img = pygame.transform.rotate(img, angle)self.image = pygame.transform.scale(img, (SnakeSize, SnakeSize))def get_rect(self):return Rect((self.__x, self.__y), (SnakeSize, SnakeSize))def move(self, x, y):self.__x = self.__x + xself.__y = self.__y + ydef set_direction(self, direction):if self.__direction == direction:returnself.__direction = directionname = Noneif self.__ishead:name = "head.png"elif self.__istail:name = "tail.png"else:name = "body.png"angle = 0match direction:case pygame.K_UP:angle = 0case pygame.K_DOWN:angle = 180case pygame.K_LEFT:angle = 90case pygame.K_RIGHT:angle = -90img = pygame.image.load(f"asset/img/{name}")img = pygame.transform.rotate(img, angle)self.image = pygame.transform.scale(img, (SnakeSize, SnakeSize))def get_direction(self):return self.__directionclass Snake:bodys = []new_body = None__new_direction = pygame.K_UP__tick_movement = 0__tick_create_body = 0__stop = False__is_paused = Falsedef __init__(self):self.bodys.insert(0, SnakeBody(SnakeSize * SnakeStartX, SnakeSize * SnakeStartY, pygame.K_UP, True, False))self.bodys.insert(1,SnakeBody(SnakeSize * SnakeStartX, SnakeSize * (SnakeStartY + 1), pygame.K_UP, False, False))self.bodys.insert(2,SnakeBody(SnakeSize * SnakeStartX, SnakeSize * (SnakeStartY + 2), pygame.K_UP, False, True))def set_direction(self, direction):# do not set inverse directionif ((self.bodys[0].get_direction() == pygame.K_UP and direction != pygame.K_DOWN) or(self.bodys[0].get_direction() == pygame.K_DOWN and direction != pygame.K_UP) or(self.bodys[0].get_direction() == pygame.K_LEFT and direction != pygame.K_RIGHT) or(self.bodys[0].get_direction() == pygame.K_RIGHT and direction != pygame.K_LEFT)):self.__new_direction = directiondef move(self):if self.__stop:returnif self.__is_paused:returnself.__tick_movement += 1if self.__tick_movement <= Tick_Snake_Move:returnself.__tick_movement = 0length = len(self.bodys)head = self.bodys[0]oldheadpos = head.get_rect()oldheaddirection = head.get_direction()# update head direction and movehead.set_direction(self.__new_direction)match self.__new_direction:case pygame.K_UP:head.move(0, -SnakeSize)case pygame.K_DOWN:head.move(0, SnakeSize)case pygame.K_LEFT:head.move(-SnakeSize, 0)case pygame.K_RIGHT:head.move(SnakeSize, 0)if ((self.new_body is not None) and(head.get_rect().x == self.new_body.get_rect().x and head.get_rect().y == self.new_body.get_rect().y)):# as head move, the old head position is empty,# add the new body at the second positionself.new_body.set_direction(head.get_direction())offsetx = oldheadpos.x - self.new_body.get_rect().xoffsety = oldheadpos.y - self.new_body.get_rect().yself.new_body.move(offsetx, offsety)self.bodys.insert(1, self.new_body)self.new_body = Noneglobal score_valuescore_value += 1else:# as head move, the old head position is empty,# move the second-to-last body to the second bodysecond2lastbody = self.bodys[length - 2]second2lastpos = second2lastbody.get_rect()second2lastdirection = second2lastbody.get_direction()offsetx = oldheadpos.x - second2lastpos.xoffsety = oldheadpos.y - second2lastpos.ysecond2lastbody.set_direction(oldheaddirection)second2lastbody.move(offsetx, offsety)self.bodys.remove(second2lastbody)self.bodys.insert(1, second2lastbody)# move tail to the direction of the second-to-last bodytailbody = self.bodys[length - 1]tailbody.set_direction(second2lastdirection)offsetx = second2lastpos.x - tailbody.get_rect().xoffsety = second2lastpos.y - tailbody.get_rect().ytailbody.move(offsetx, offsety)def stop(self):self.__stop = Truedef create_body(self):self.__tick_create_body += 1if self.__tick_create_body <= 30:returnif self.is_paused():returnself.__tick_create_body = 0if self.new_body is not None:returnx, y = 0, 0while True:isspare = Trueintx = random.randint(0, MaxWidthBlock - 1)inty = random.randint(ControlPanelHeightBlock, MaxHeightBlock - 1)x = intx * SnakeSizey = inty * SnakeSizefor b in self.bodys:rect = b.get_rect()if rect.x == x and rect.y == y:isspare = Falsebreakif isspare:breakprint(f"create body block at {intx}, {inty}")self.new_body = SnakeBody(x, y, pygame.K_UP, False, False)def is_collided(self):iscollided = Falsehead = self.bodys[0]headrect = self.bodys[0].get_rect()# boundary collisionif headrect.x <= (0 - SnakeSize) or headrect.x >= GamePanelWidth or \headrect.y <= (ControlPanelHeight - SnakeSize) or headrect.y >= (ControlPanelHeight + GamePanelHeight):iscollided = True# body collisionelse:if head.get_direction() == pygame.K_LEFT:passfor b in self.bodys[1:len(self.bodys)]:if head.get_rect().colliderect(b.get_rect()):iscollided = Truebreakreturn iscollideddef pause(self):self.__is_paused = not self.__is_pauseddef is_paused(self):return self.__is_pauseddef display_result():final_text1 = "Game Over"final_surf = pygame.font.SysFont("Arial", SnakeSize * 2).render(final_text1, 1, (242, 3, 36))  # 设置颜色screen.blit(final_surf, [screen.get_width() / 2 - final_surf.get_width() / 2,screen.get_height() / 2 - final_surf.get_height() / 2])  # 设置显示位置def display_paused():paused_text = "Paused"paused_surf = pygame.font.SysFont("Arial", SnakeSize * 2).render(paused_text, 1, (242, 3, 36))screen.blit(paused_surf, [screen.get_width() / 2 - paused_surf.get_width() / 2,screen.get_height() / 2 - paused_surf.get_height() / 2])def display_control_panel():global minus_btn_rect, plus_btn_rectcolor = (242, 3, 36)speed_text = "Speed"speed_surf = pygame.font.SysFont("Arial", SnakeSize).render(speed_text, 1, "blue")  # 设置颜色speed_rect = speed_surf.get_rect()speed_rect.x, speed_rect.y = 0, 0screen.blit(speed_surf, speed_rect)offsetx = speed_rect.x + speed_rect.width + 10text_minus = "-"minus_btn = pygame.font.SysFont("Arial", SnakeSize).render(text_minus, 1, color)  # 设置颜色minus_btn_rect = minus_btn.get_rect()minus_btn_rect.x, minus_btn_rect.y = offsetx, 0screen.blit(minus_btn, minus_btn_rect)offsetx = minus_btn_rect.x + minus_btn_rect.width + 10text_speed_value = str(Tick - Tick_Snake_Move)speed_value_surf = pygame.font.SysFont("Arial", SnakeSize).render(text_speed_value, 1, color)  # 设置颜色speed_value_rect = speed_value_surf.get_rect()speed_value_rect.x, speed_value_rect.y = offsetx, 0screen.blit(speed_value_surf, speed_value_rect)offsetx = speed_value_rect.x + speed_value_rect.width + 10text_plus = "+"plus_btn = pygame.font.SysFont("Arial", SnakeSize).render(text_plus, 1, color)  # 设置颜色plus_btn_rect = plus_btn.get_rect()plus_btn_rect.x, plus_btn_rect.y = offsetx, 0screen.blit(plus_btn, plus_btn_rect)score_value_text = str(score_value)score_value_surf = pygame.font.SysFont("Arial", SnakeSize).render(score_value_text, 1, color)  # 设置颜色score_value_rect = score_value_surf.get_rect()score_value_rect.x = GamePanelWidth - score_value_rect.widthscore_value_rect.y = 0screen.blit(score_value_surf, score_value_rect)score_text = "Score"score_surf = pygame.font.SysFont("Arial", SnakeSize).render(score_text, 1, "blue")  # 设置颜色score_rect = score_surf.get_rect()score_rect.x = score_value_rect.x - score_rect.width - 10score_rect.y = 0screen.blit(score_surf, score_rect)def check_click(position):global Tick_Snake_Moveif minus_btn_rect == None or plus_btn_rect == None:returnx, y = position[0], position[1]minus_btn_x, minus_btn_y = minus_btn_rect.x, minus_btn_rect.yplus_btn_x, plus_btn_y = plus_btn_rect.x, plus_btn_rect.yif minus_btn_x < x < minus_btn_x + minus_btn_rect.width and \minus_btn_y < y < minus_btn_y + minus_btn_rect.height:Tick_Snake_Move += 1elif plus_btn_x < x < plus_btn_x + plus_btn_rect.width and \plus_btn_y < y < plus_btn_y + plus_btn_rect.height:Tick_Snake_Move -= 1pygame.init()
pygame.font.init()  # 初始化字体
screen = pygame.display.set_mode((GamePanelWidth, ControlPanelHeight + GamePanelHeight))
clock = pygame.time.Clock()
snake = Snake()screen.fill(ControlPanelColor, ControlPanelRect)while True:clock.tick(20)for event in pygame.event.get():if event.type == pygame.QUIT:pygame.quit()sys.exit()elif event.type == pygame.KEYDOWN:if event.key == pygame.K_LEFT or event.key == pygame.K_a:snake.set_direction(pygame.K_LEFT)elif event.key == pygame.K_RIGHT or event.key == pygame.K_d:snake.set_direction(pygame.K_RIGHT)elif event.key == pygame.K_UP or event.key == pygame.K_w:snake.set_direction(pygame.K_UP)elif event.key == pygame.K_DOWN or event.key == pygame.K_s:snake.set_direction(pygame.K_DOWN)elif event.key == pygame.K_SPACE:snake.pause()if pygame.mouse.get_pressed()[0]:check_click(pygame.mouse.get_pos())screen.fill(GamePanelColor, (0, ControlPanelHeight, GamePanelWidth, ControlPanelHeight + GamePanelHeight))snake.move()for body in snake.bodys:screen.blit(body.image, body.get_rect())# collision detectionif snake.is_collided():snake.stop()display_result()else:# new bodysnake.create_body()if snake.new_body is not None:screen.blit(snake.new_body.image, snake.new_body.get_rect())screen.fill(ControlPanelColor, (0, 0, GamePanelWidth, ControlPanelHeight))display_control_panel()if snake.is_paused():display_paused()pygame.display.flip()

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/92432.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【Python】返回指定时间对应的时间戳

使用模块datetime&#xff0c;附赠一个没啥用的“时间推算”功能(获取n天后对应的时间 代码&#xff1a; import datetimedef GetTimestamp(year,month,day,hour,minute,second,*,relativeNone,timezoneNone):#返回指定时间戳。指定relative时进行时间推算"""根…

TFT LCD刷新原理及LCD时序参数总结(LCD时序,写的挺好)

cd工作原理目前不了解&#xff0c;日后会在博客中添加这一部分的内容。 1.LCD工作原理[1] 我对LCD的工作原理也仅仅处在了解的地步&#xff0c;下面基于NXP公司对LCD工作原理介绍的ppt来学习一下。 LCD(liquid crystal display,液晶显示屏) 是由液晶段阵列组成&#xff0c;当…

newstarctf

wp web: 1.rce 可以发现这个变量名有下划线也有点。 $code$_POST[e_v.a.l]; 这时候如果直接按这个变量名来传参&#xff0c;php 是无法接收到这个值的&#xff0c;具体原因是 php 会自动把一些不合法的字符转化为下划线&#xff08;注&#xff1a;php8以下&#xff09;&am…

springboot和vue:八、vue快速入门

vue快速入门 新建一个html文件 导入 vue.js 的 script 脚本文件 <script src"https://unpkg.com/vuenext"></script>在页面中声明一个将要被 vue 所控制的 DOM 区域&#xff0c;既MVVM中的View <div id"app">{{ message }} </div…

Node.js 是如何处理请求的

前言&#xff1a;在服务器软件中&#xff0c;如何处理请求是非常核心的问题。不管是底层架构的设计、IO 模型的选择&#xff0c;还是上层的处理都会影响一个服务器的性能&#xff0c;本文介绍 Node.js 在这方面的内容。 TCP 协议的核心概念 要了解服务器的工作原理首先需要了…

C++17中std::filesystem::directory_entry的使用

C17引入了std::filesystem库(文件系统库, filesystem library)。这里整理下std::filesystem::directory_entry的使用。 std::filesystem::directory_entry&#xff0c;目录项&#xff0c;获取文件属性。此directory_entry类主要用法包括&#xff1a; (1).构造函数、…

EasyExcel的源码流程(导入Excel)

1. 入口 2. EasyExcel类继承了EasyExcelFactory类&#xff0c;EasyExcel自动拥有EasyExcelFactory父类的所有方法&#xff0c;如read()&#xff0c;readSheet()&#xff0c;write()&#xff0c;writerSheet()等等。 3. 进入.read()方法&#xff0c;需要传入三个参数(文件路径…

【C++】:类和对象(1)

朋友们、伙计们&#xff0c;我们又见面了&#xff0c;本期来给大家解读一下有关C中类和对象的知识点&#xff0c;如果看完之后对你有一定的启发&#xff0c;那么请留下你的三连&#xff0c;祝大家心想事成&#xff01; C 语 言 专 栏&#xff1a;C语言&#xff1a;从入门到精通…

Windows电脑显示部分功能被组织控制

目录 问题描述 解决方法 总结 问题描述 如果你的电脑出现以上情况&#xff0c;建议你使用我这种方法&#xff08;万不得已&#xff09; 解决方法 原因就是因为当时你的电脑在激活的时候是选择了组织性激活的&#xff0c;所以才会不管怎么搞&#xff0c;都无法摆脱组织的控…

十五、异常(4)

本章概要 Java 标志异常 特例&#xff1a;RuntimeException 使用 finally 进行清理 finally 用来做什么&#xff1f;在 return 中使用 finally缺憾&#xff1a;异常丢失 Java 标准异常 Throwable 这个 Java 类被用来表示任何可以作为异常被抛出的类。Throwable 对象可分为两…

ubuntu下源码编译方式安装opencv

基础条件 ubuntu 20.04 opencv 3.4.3 opencv 源码编译的安装步骤 第一步&#xff0c; 首先clone源码 git clone https://github.com/opencv/opencv.git第二步&#xff0c;依赖包&#xff0c;执行下面的命令 sudo apt-get install build-essential sudo apt-get install cmak…

Android studio “Layout Inspector“工具在Android14 userdebug设备无法正常使用

背景描述 做rom开发的都知道&#xff0c;“Layout Inspector”和“Attach Debugger to Android Process”是studio里很好用的工具&#xff0c;可以用来查看布局、调试系统进程&#xff08;比如setting、launcher、systemui&#xff09;。 问题描述 最进刚开始一个Android 14…

Android Shape设置背景

设置背景时&#xff0c;经常这样 android:background“drawable/xxx” 。如果是纯色图片&#xff0c;可以考虑用 shape 替代。 shape 相比图片&#xff0c;减少资源占用&#xff0c;缩减APK体积。 开始使用。 <?xml version"1.0" encoding"utf-8"?…

云安全之HTTP协议介绍

HTTP的基本概念 什么是网络协议 网络协议是计算机之间为了实现网络通信而达成的一种“约定”或者”规则“&#xff0c;有了这种”约定不同厂商生产的设备&#xff0c;以及不同操作系统组成的计算机之间&#xff0c;就可以实现通信。 网络协议由三个要素构成&#xff1a;1、语…

WSL2和ubuntu的安装过程

目录 1.WSL2的安装 2.Ubuntu的安装 3.安装完成后的打开方式 1.WSL2的安装 按下WINX键&#xff0c;选择Windows PowerShell (管理员) 1.1执行以下命令&#xff0c;该命令的作用是&#xff1a;启用适用于 Linux 的 Windows 子系统 dism.exe /online /enable-feature /featur…

【小沐学前端】Node.js实现基于Protobuf协议的WebSocket通信

文章目录 1、简介1.1 Node1.2 WebSocket1.3 Protobuf 2、安装2.1 Node2.2 WebSocket2.2.1 nodejs-websocket2.2.2 ws 2.3 Protobuf 3、代码测试3.1 例子1&#xff1a;websocket&#xff08;html&#xff09;3.1.1 客户端&#xff1a;yxy_wsclient1.html3.1.2 客户端&#xff1a…

利用mAP计算yolo精确度

当将yolo算法移植部署在嵌入式设备上&#xff0c;为了验证算法的准确率。将模型测试的结果保存为txt文件&#xff08;每一个txt文件&#xff0c;对应一个图片&#xff09;。此外&#xff0c;需要将数据集中的标签由[x,y,w,h]转为[x1,y1,x2,y2]。最后&#xff0c;运行验证代码 …

Secureboot从入门到精通

关键词&#xff1a;trustzone视频、tee视频、ATF视频、secureboot视频、安全启动视频、selinux视频&#xff0c;cache视频、mmu视频&#xff0c;armv8视频、armv9视频 FF-A视频、密码学视频、RME/CCA视频、学习资料下载、免费学习资料、免费 周贺贺&#xff0c;baron&#xff0…

把握现在,热爱生活

博客主页&#xff1a;https://tomcat.blog.csdn.net 博主昵称&#xff1a;农民工老王 主要领域&#xff1a;Java、Linux、K8S 期待大家的关注&#x1f496;点赞&#x1f44d;收藏⭐留言&#x1f4ac; 目录 厨艺房价琐事计划随想 今年的中秋国庆假期放8天&#xff0c;比春节假期…

Centos7配置firewalld防火墙规则

这里写自定义目录标题 欢迎使用Markdown编辑器一、简单介绍二、特点和功能2.1、区域&#xff08;Zone&#xff09;2.2、运行时和永久配置2.3、服务和端口2.4、动态更新2.5、连接跟踪2.6、D-Bus接口 三、设置规则3.1、启动防火墙服务3.2、新建防火墙规则的服务&#xff0c;添加端…