pygame手搓贪吃蛇

news/2024/11/16 16:37:20/文章来源:https://www.cnblogs.com/xuxiaobo/p/18382902

代码:

#coding=utf-8import os,sys,re,time
import pygame
import random
from win32api import GetSystemMetrics
import copypygame.init()
pygame.display.set_caption("贪吃蛇")percent = 0.6
screen_width = GetSystemMetrics(0)
screen_height = GetSystemMetrics(1)
window_width = int(screen_width*percent)
window_height = int(screen_height*percent)maxLine = 25
maxField = 25
empty_width = window_height / (maxLine + 2) / 13left_width = window_height
left_height = window_height
left_width_nei = left_width - 2 * empty_width
left_height_nei = left_height - 2 * empty_width
right_width = window_width - left_width
right_height = window_height
line_border_width = 1perWidth = left_width_nei / maxField
perHeight = left_height_nei / maxLinedt = 0
clock = pygame.time.Clock()screen = pygame.display.set_mode((window_width-right_width/1.3, window_height))#停止处理输入法事件
pygame.key.stop_text_input()font_path = os.path.join(os.path.dirname(sys.argv[0]), 'simsun.ttc')class Button:def __init__(self, x, y, width, height, color, text):self.x = xself.y = yself.width = widthself.height = heightself.color = colorself.text = textdef draw(self, win, outline=None, line_width = 1):pygame.draw.rect(win, self.color, (self.x, self.y, self.width, self.height))if outline:pygame.draw.rect(win, outline, (self.x, self.y, self.width, self.height), 1)myfont = pygame.font.Font(font_path, int(19*percent))text = myfont.render(self.text, 1, (0, 0, 0))myw = self.x + (self.width / 2 - text.get_width() / 2)myy = self.y + (self.height / 2 - text.get_height() / 2)win.blit(text, (myw, myy))def changeText(self, text):self.text = textdef beClicked(self, mouse_pos, event):if self.x + self.width > event.pos[0] > self.x and self.y + self.height > event.pos[1] > self.y:return Truereturn Falsedef checkPointIsin(mypoints1, testpoint):for mypoint in mypoints1:if testpoint[0] == mypoint[0] and testpoint[1] == mypoint[1]:return Truereturn Falsedef getRandpoints(randpoint1):res = []for i in range(3):x = random.randint(0, maxLine-1)y = random.randint(0, maxField-1)color = (random.randint(1, 255), random.randint(1, 255), random.randint(1, 255))mytime = int(round(time.time() * 1000 + random.randint(1, 10000)))if randpoint1[0] == x and randpoint1[1] == y:continueres.append([x, y, color, mytime])return resdef restElsepoints(elsepoints, mypoints1):res = []for i,point in enumerate(elsepoints):if int(round(time.time() * 1000)) - point[3] > 12000:x = random.randint(0, maxLine-1)y = random.randint(0, maxField-1)color = (random.randint(1, 255), random.randint(1, 255), random.randint(1, 255))mytime = int(round(time.time() * 1000))if checkPointIsin(mypoints1, [x, y, color, mytime]) == False:res.append([x, y, color, mytime])else:res.append(point)if len(res) < 1:x = random.randint(0, maxLine-1)y = random.randint(0, maxField-1)color = (random.randint(1, 255), random.randint(1, 255), random.randint(1, 255))mytime = int(round(time.time() * 1000))if checkPointIsin(mypoints1, [x, y, color, mytime]) == False:res.append([x, y, color, mytime])return resdef has_index(lst, element):try:lst.index(element)return Trueexcept ValueError:return Falsebuttonwidth = 80*percent
randpoint1 = [random.randint(0, maxLine-1), random.randint(0, maxField-1), 'red']
mypoints = [randpoint1]
elsepoints = getRandpoints(randpoint1)
sleepTime = 0
direct = ''
pauseFlag = False
restartBt = Button(window_width-right_width+2, 1, buttonwidth, 25, 'Gold3', '重新开始')
pauseBt = Button(window_width-right_width+buttonwidth+4, 1, buttonwidth, 25, 'Gold3', '暂停')running = True
while running:for event in pygame.event.get():if event.type == pygame.QUIT:running = Falseif event.type == pygame.MOUSEBUTTONDOWN:mouse_pos = pygame.mouse.get_pos()if restartBt.beClicked(mouse_pos, event):randpoint1 = [random.randint(0, maxLine-1), random.randint(0, maxField-1), 'red']mypoints = [randpoint1]elsepoints = getRandpoints(randpoint1)sleepTime = 0direct = ''pauseFlag = Falseif pauseBt.beClicked(mouse_pos, event):if pauseFlag == True:pauseFlag = FalsepauseBt.changeText('暂停')else:pauseFlag = TruepauseBt.changeText('开始')keys_pressed = pygame.key.get_pressed()#ESC键if keys_pressed[pygame.K_ESCAPE]:running = Falseif pauseFlag == False:if keys_pressed[pygame.K_a]:direct = 'a'firstpoint = mypoints[0]if firstpoint[0] <= 0:firstpoint[0] = 0mypoints[0] = firstpointelse:mypointsold = copy.deepcopy(mypoints)for i in range(1, len(mypoints)):mypoints[i][0] = mypointsold[i-1][0]mypoints[i][1] = mypointsold[i-1][1]firstpoint[0] -= 1mypoints[0] = firstpointif keys_pressed[pygame.K_d]:direct = 'd'firstpoint = mypoints[0]if firstpoint[0] >= maxField - 1:firstpoint[0] = maxField - 1mypoints[0] = firstpointelse:mypointsold = copy.deepcopy(mypoints)for i in range(1, len(mypoints)):mypoints[i][0] = mypointsold[i-1][0]mypoints[i][1] = mypointsold[i-1][1]firstpoint[0] += 1mypoints[0] = firstpointif keys_pressed[pygame.K_w]:direct = 'w'firstpoint = mypoints[0]if firstpoint[1] <= 0:firstpoint[1] = 0mypoints[0] = firstpointelse:mypointsold = copy.deepcopy(mypoints)for i in range(1, len(mypoints)):mypoints[i][0] = mypointsold[i-1][0]mypoints[i][1] = mypointsold[i-1][1]firstpoint[1] -= 1mypoints[0] = firstpointif keys_pressed[pygame.K_s]:direct = 's'firstpoint = mypoints[0]if firstpoint[1] >= maxLine - 1:firstpoint[1] = maxLine - 1mypoints[0] = firstpointelse:mypointsold = copy.deepcopy(mypoints)for i in range(1, len(mypoints)):mypoints[i][0] = mypointsold[i-1][0]mypoints[i][1] = mypointsold[i-1][1]firstpoint[1] += 1mypoints[0] = firstpointtime.sleep(0.1)screen.fill("purple")#左侧块rect1 = pygame.Rect(empty_width, empty_width, perWidth*maxField, perHeight*maxLine)pygame.draw.rect(screen, 'LightYellow1', rect1)#右侧块rect2 = pygame.Rect(left_width, 0, right_width, right_height)pygame.draw.rect(screen, 'Honeydew', rect2)restartBt.draw(screen, 'black')pauseBt.draw(screen, 'black')#横线for i in range(0, maxLine+1):start = (empty_width, empty_width+i*perHeight)end = (empty_width+left_width_nei, empty_width+i*perHeight)pygame.draw.aaline(screen, 'black', start, end, line_border_width)#竖线for i in range(0, maxField+1):start = (empty_width+i*perWidth, empty_width)end = (empty_width+i*perWidth, empty_width+left_height_nei)pygame.draw.aaline(screen, 'black', start, end, line_border_width)#蛇头myrect = pygame.Rect(empty_width+mypoints[0][0]*perWidth, empty_width+mypoints[0][1]*perHeight, perWidth, perHeight)#随机块if pauseFlag == False:elsepoints = restElsepoints(elsepoints, mypoints)for i,mypoint1 in enumerate(elsepoints):myrect1 = pygame.Rect(empty_width+mypoint1[0]*perWidth, empty_width+mypoint1[1]*perHeight, perWidth, perHeight)pygame.draw.rect(screen, mypoint1[2], myrect1)if myrect.colliderect(myrect1):if direct == 'a':mypoint1[0] -= 1elif direct == 'd':mypoint1[0] += 1elif direct == 'w':mypoint1[1] -= 1elif direct == 's':mypoint1[1] += 1mypoints.insert(0, [mypoint1[0], mypoint1[1], mypoint1[2]])del elsepoints[i]#蛇块for i,mypoint1 in enumerate(mypoints):myrect1 = pygame.Rect(empty_width+mypoint1[0]*perWidth, empty_width+mypoint1[1]*perHeight, perWidth, perHeight)pygame.draw.rect(screen, mypoint1[2], myrect1)if i == 0:pygame.draw.rect(screen, 'black', myrect1, 3)#更新显示
    pygame.display.flip()#pygame.display.update()
    dt = clock.tick(60) / 600pygame.quit()

 

效果:

 

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

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

相关文章

AI创新,DataOps聚能 | 白鲸开源DTCC共话DataOps新篇章

近日,由IT168联合旗下ITPUB、ChinaUnix两大技术社区主办的第15届中国数据库技术大会(DTCC 2024)隆重召开。大会以“自研创新 数智未来”为主题,吸引了数百位行业专家和广大数据领域从业者共聚这场年度数据库技术交流盛宴,共同探讨新时代下数据库的技术动态和应用实践。作为…

Android taskset用法详解

一、简介taskset 命令用于设置或者获取一直指定的 PID 对于 CPU 核的运行依赖关系。通过 taskset 命令可将某个进程与某个CPU核心绑定,使得其仅在与之绑定的CPU核心上运行 关于绑核的解释绑核,其实就是设定某个进程/线程与某个CPU核的亲和力(affinity)。设定以后,Linux调度…

Builder 模式在 Go 语言中的应用

Builder 模式在 Go 语言中的应用 江湖十年 Go编程世界2024年08月27日 07:21 浙江Builder 模式是一种创建型模式,即用来创建对象。 Builder 模式,中文翻译不太统一,有时候被翻译为建造者模式或构建者模式,有时候也被翻译为生成器模式。为了不给读者造成困扰,我还是直接叫它…

.NET Core 处理 WebAPI JSON 返回烦人的null为空

前言项目开发中不管是前台还是后台都会遇到烦人的null,数据库表中字段允许空值,则代码实体类中对应的字段类型为可空类型Nullable<>,如int?,DateTime?,null值字段序列化返回的值都为null,前台对应字段赋值需要做null值判断,怎么才能全局把null替换为空。本文分享…

软工第一次作业

这个作业属于哪个课程 2024软工这个作业要求在哪里 第一次作业要求这个作业的目标 熟悉markdown,github,博客园自我介绍 我是来自广州本地的学生。爱好听音乐,看视频,看有关编程的书籍。 五个问题如何保证开发人员所了解的,就是客户想要的? 软件即将完成,全方面碾压的新…

mysql磁盘碎片整理

背景 数据结转过程中经常进行 delete 操作,产生空白空间,如果进行新的插入操作,MySQL将尝试利用这些留空的区域,但仍然无法将其彻底占用,于是造成了数据的存储位置不连续,以及物理存储顺序与理论上的排序顺序不同,久而久之就产生了碎片。 碎片治理思路 根据线上处理经验总…

【SpringCloud】idea如何实现微服务多开

实现微服务多开背景:当需要使用相同的配置启动多个服务且host相同时,就需要在命令行指定不同的端口,但是 spring cloud 中远程配置默认会覆盖所有本地参数,所以需要修改默认覆盖优先级 一、默认优先级 二、配置远程配置优先级低于本地系统参数 # 是否允许本地配置覆盖远程配…

[ARC175E] Three View Drawing

构造My Blogs [ARC175E] Three View Drawing 哎,构造。 首先考虑 \(m=n^2\) 怎么做:显然是最上面一层填满第一条主对角线,第二层填满第二条主对角线...(主对角线指可以循环的对角线)。 把 \(n\) 变成满足 \(n^2\geq m\) 的最小的 \(n\)。然后考虑删去 \(n^2-m\) 个。可以发…

c/c++代码流程图生成

以下介绍2款皆免费 1.cxx2flow【github项目】c/c++函数解析为dot然后通过Graphviz渲染项目有附带gui程序可直接生成流程图,但是显示效果缩放不太行,建议解析生成dot后喂给其他基于Graphviz的渲染服务,使用过vscode上面的graphviz-interactive-preview,效果还行,也有在线网页…

算法与数据结构——哈希表

哈希表 哈希表(hash table),又称散列表,它通过建立键key与值value之间的映射,实现高效的元素查询。具体而言,我们向哈希表中输入一个键key,则可以在O(1)时间内获取对应的值value。 除哈希表外,数组和链表也可以实现查询功能,他们的效率对比如下表:添加元素:仅需将元…

Android systrace环境的搭建和使用

一、systrace简介 Systrace 是 Android4.1 中新增的性能数据采样和分析工具。它可帮助开发者收集 Android 关键子系统(如 SurfaceFlinger/SystemServer/Kernel/Input/Display 等 Framework 部分关键模块、服务,View系统等)的运行信息,从而帮助开发者更直观的分析系统瓶颈,…

threeJs 修改TransformControls的显示位置

有的时候模型的原点不是自身中心而是在场景的[0, 0, 0]位置这个时候想要让TransformControls的位置显示在模型的中心目前找的的处理方式是修改源码 找到updateMatrixWorld方法 updateMatrixWorld () {...for ( let i = 0; i < handles.length; i ++ ) {...if ( this.mode ==…