Python pyglet制作彩色圆圈“连连看”游戏

原文链接: 

Python 一步一步教你用pyglet制作“彩色方块连连看”游戏(续)-CSDN博客文章浏览阅读1.6k次,点赞75次,收藏55次。上期讲到相同的色块连接,链接见: Python 一步一步教你用pyglet制作“彩色方块连连看”游戏-CSDN博客续上期,接下来要实现相邻方块的连线:首先来进一步扩展 行列的类......https://blog.csdn.net/boysoft2002/article/details/137063657

彩色圆圈“连连看”

有个网友留言要把原文中的方块改成圆圈,再要加入消去的分数。大致效果如下: 

以下就把原文的代码作几步简单的修改:

Box类的修改

class Box:
    def __init__(self, x, y, w, h, color, batch=batch):
        self.x, self.y, self.w, self.h = x, y, w, h
        self.rect = shapes.Rectangle(x, y, w, h, color=color, batch=batch)
        self.box = shapes.Box(x, y, w, h, color=Color('WHITE').rgba, thickness=3, batch=batch)

    def hide(self):
        self.box.batch = self.rect.batch = None
    def show(self):
        self.box.batch = self.rect.batch = batch
    def on_mouse_over(self, x, y):
        return self.x<=x<=self.x+self.w and self.y<=y<=self.y+self.h

把矩形及方框用圆圈和圆弧来代替:

        self.rect = shapes.Circle(x+w//2, y+h//2, min(w,h)//2, color=color, batch=batch)
        self.box = shapes.Arc(x+w//2, y+h//2, min(w,h)//2, color=Color('WHITE').rgba, batch=batch)

Game类的修改 

Game类中增加分数属性:

class Game:
    def __init__(self):
        initMatrix(row, col)
        self.score = 0
        self.rc, self.rc2 = Point(), Point()
        self.array, self.arces = Array, Boxes

update方法中增加分数和显示

    def update(self, event):
        clock.unschedule(self.update)
        if self.last1.cir.color==self.last2.cir.color and matrix.connect(self.rc, self.rc2):
            self.hide()
            sound1.play()
            self.score += 10
            window.set_caption(window.caption.split('分数:')[0] + f'分数:{self.score}')

        ......

点击事件的修改

在on_mouse_press事件中增加分数的显示:

@window.event
def on_mouse_press(x, y, dx, dy):
    global score
    if (ret := game.on_mouse_click(x, y)):
        window.set_caption(f'彩色方块连连看——坐标:{ret[0]}  颜色:{ret[1]}  分数:{game.score}')

部分代码的替代

在源码全文中搜索并替代: .rect 替换为 .cir ; .box 替换为 .arc

class Box类名也可以修改一下,不作修改也不影响代码的运行。

大致就以上几步就完成了修改:

完整代码 

from pyglet import *
from colorlib import *
from pointlib import Point
from pyglet.window import keyW, H = 800, 600
window = window.Window(W, H)
gl.glClearColor(*Color('lightblue3').decimal)
batch, batch2, group = graphics.Batch(), graphics.Batch(), graphics.Group()row, col, space = 8, 10, 5
w, h = W//(col+2), H//(row+2)
x0, y0 = (W-(w+space)*col)//2, (H-(h+space)*row)//2sound1, sound2 = media.load('box.mp3'), media.load('box2.mp3')def randColor():COLOR = []while len(COLOR)<row*col//4:if not ((c:=randcolorTuple()) in COLOR or Color(c).name[-1] in '0123456789'):COLOR.append(c)return sample(COLOR*4, row*col)class Box:def __init__(self, x, y, w, h, color, batch=batch):self.x, self.y, self.w, self.h = x, y, w, hself.cir = shapes.Circle(x+w//2, y+h//2, min(w,h)//2, color=color, batch=batch)self.arc = shapes.Arc(x+w//2, y+h//2, min(w,h)//2, color=Color('WHITE').rgba, batch=batch)def hide(self):self.arc.batch = self.cir.batch = Nonedef show(self):self.arc.batch = self.cir.batch = batchdef on_mouse_over(self, x, y):return self.x<=x<=self.x+self.w and self.y<=y<=self.y+self.hclass Matrix:def __init__(self, r=row, c=col):self.array = [[1]*c for _ in range(r)]self.point = []self.lines = [shapes.Line(*[-3]*4, width=5, color=Color('light gold').rgba,batch=batch2, group=group) for _ in range(5)]for line in self.lines: line.visible = Falsedef __repr__(self):return '\n'.join(map(str,self.array))+'\n'def true(self, point):try: return self.array[point.x+1][point.y+1]except: return 0def alltrue(self, points):if isinstance(points,(tuple,list)) and all(isinstance(p, Point) for p in points):try: return all(self.array[p.x+1][p.y+1] for p in points)except: return 0def adjacent(self, point1, point2):return point1*point2def inline(self, point1, point2):return point1^point2 and self.alltrue(point1**point2)def diagonal(self, point1, point2):if point1&point2:for point in point1%point2:state1 = self.adjacent(point, point1) or self.inline(point, point1)state2 = self.adjacent(point, point2) or self.inline(point, point2)if self.true(point) and state1 and state2:self.point.append(point)return Truedef connect1(self, p1, p2):return self.adjacent(p1, p2) or self.inline(p1, p2) or self.diagonal(p1, p2)def connect2(self, p1, p2):for i in range(1, max(row, col)):for p in zip(i+p1, i+p2):for i in range(2):if self.true(p[i]) and (self.adjacent(p[i],(p1,p2)[i]) orself.inline(p[i],(p1,p2)[i]))and self.diagonal(p[i], (p2,p1)[i]):self.point.append(p[i])return Truedef connect(self, p1, p2):if (ret := self.connect1(p1, p2) or self.connect2(p1, p2)):self.showlines(p1, p2)return retdef getxy(self, row, col):return x0+col*(w+space)+w//2, y0+row*(h+space)+h//2def drawline(self, *args):for i,p in enumerate(args[:-1]):self.lines[i].x, self.lines[i].y = self.getxy(*p)self.lines[i].x2, self.lines[i].y2 = self.getxy(*args[i+1])self.lines[i].visible = Truedef showlines(self, point1, point2):if len(self.point)==3: self.point.pop(0)if len(self.point)==2 and not self.point[0]^point1: self.point.reverse()points = point1, *self.point, point2self.drawline(*points)self.point.clear()def hidelines(self):for line in self.lines: line.visible = Falsedef linevisible(self):return self.lines[0].visibledef initMatrix(row, col):global matrix, Array, Boxesmatrix = Matrix(row+2, col+2)Array, Boxes = matrix.array, Matrix().arrayfor i in range(row):for j in range(col):Array[i+1][j+1] = 0COLOR = randColor()for r,arr in enumerate(Boxes):for c,_ in enumerate(arr):Boxes[r][c] = Box(x0+c*(w+space), y0+r*(h+space), w, h, COLOR[c+r*len(arr)])class Game:def __init__(self):initMatrix(row, col)self.score = 0self.rc, self.rc2 = Point(), Point()self.array, self.arces = Array, Boxesself.last1, self.last2, self.lastz = None, None, Noneself.label1 = text.Label('Congratulations!', color=Color().randcolor().rgba, font_size=50,x=W//2, y=H//2+80, anchor_x='center', anchor_y='center', bold=True, batch=batch)self.label2 = text.Label('Any key to restart...', color=Color().randcolor().rgba, font_size=36,x=W//2, y=H//2-50, anchor_x='center', anchor_y='center', bold=True, batch=batch)def on_mouse_click(self, x, y):if matrix.linevisible(): returnif self.success(): main(event)r, c = (y-y0)//(h+space), (x-x0)//(w+space)if r in range(row) and c in range(col) and self.arces[r][c].on_mouse_over(x, y) and not self.array[r+1][c+1]:if self.last1 is None and self.last2 is None:self.rc, self.last1 = Point(r, c), self.arces[r][c]self.last1.arc.color = Color('RED').rgbaelif self.last1 is not None and self.last2 is None:self.rc2, self.last2 = Point(r, c), self.arces[r][c]self.last2.arc.color = Color('RED').rgbaif self.rc == self.rc2:self.last1.arc.color = Color('WHITE').rgbaself.last1, self.last2 = None, Noneelse:if self.last1.cir.color==self.last2.cir.color:matrix.connect(self.rc, self.rc2)clock.schedule_interval(self.update, 0.5)return (r, c), Color(self.arces[r][c].cir.color).namedef update(self, event):clock.unschedule(self.update)if self.last1.cir.color==self.last2.cir.color and matrix.connect(self.rc, self.rc2):self.hide()sound1.play()self.score += 10window.set_caption(window.caption.split('分数:')[0] + f'分数:{self.score}')else:sound2.play()self.last1.arc.color = self.last2.arc.color = Color('WHITE').rgbaself.lastz = self.last1, self.last2self.last1, self.last2 = None, Nonematrix.hidelines()if game.success():window.set_caption('彩色方块连连看——任务完成!')game.label1.batch = game.label2.batch = batch2clock.schedule_interval(main, 5) # 5秒后自动开始def hide(self):self.last1.hide(); self.last2.hide()self.array[self.rc.x+1][self.rc.y+1] = self.array[self.rc2.x+1][self.rc2.y+1] = 1def unhide(self):self.lastz[0].show(); self.lastz[1].show()self.array[self.rc.x+1][self.rc.y+1] = self.array[self.rc2.x+1][self.rc2.y+1] = 0def success(self):return sum(sum(self.array,[]))==(row+2)*(col+2) def main(event):global gamegame = Game()game.label1.batch = game.label2.batch = Nonewindow.set_caption('彩色方块连连看')clock.unschedule(main)@window.event
def on_draw():window.clear()batch.draw()batch2.draw()@window.event
def on_mouse_press(x, y, dx, dy):global scoreif (ret := game.on_mouse_click(x, y)):window.set_caption(f'彩色方块连连看——坐标:{ret[0]}  颜色:{ret[1]}  分数:{game.score}')@window.event
def on_key_press(symbol, modifiers):if game.success(): main(event)if symbol == key.S and modifiers & key.MOD_CTRL:main(event)elif symbol == key.Z and modifiers & key.MOD_CTRL:game.unhide()elif symbol == key.R and modifiers & key.MOD_CTRL:for i in range(row):for j in range(col):Array[i+1][j+1], Boxes[i][j].arc.batch, Boxes[i][j].cir.batch = 0, batch, batchelif symbol == key.F and modifiers & key.MOD_CTRL:if sum(sum(game.array,[]))%2: returnboxsample = []for i,arr in enumerate(Array[1:-1]):for j,n in enumerate(arr[1:-1]):if n==0: boxsample.append(Boxes[i][j].cir.color)boxsample = sample(boxsample,len(boxsample))for i,arr in enumerate(Array[1:-1]):for j,n in enumerate(arr[1:-1]):if n==0: Boxes[i][j].cir.color = boxsample.pop()main(event)
app.run()

目录

彩色圆圈“连连看”

Box类的修改

Game类的修改 

点击事件的修改

部分代码的替代

完整代码 


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

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

相关文章

Ai2024安装包(亲测可用)

目录 一、软件简介 二、软件下载 一、软件简介 Adobe illustrator&#xff0c;常被称为“AI”&#xff0c;是一种应用于出版、多媒体和在线图像的工业标准矢量插画的软件。作为一款非常好的矢量图形处理工具&#xff0c;该软件主要应用于印刷出版、海报书籍排版、专业插画、多…

Fiddler抓包工具之高级工具栏中的Inspectors的使用

高级工具栏中的Inspectors的使用 Inspectors 页签允许你用多种不同格式查看每个请求和响应的内容。JPG 格式使用 ImageView 就可以看到图片&#xff0c;HTML/JS/CSS 使用 TextView 可以看到响应的内容。Raw标签可以查看原始的符合http标准的请求和响应头。Cookies标签可以看到…

citus 之一 make 安装

os: centos 7.9.2009 citus: v12.1 OS 安装依赖包 sudo cd /etc/yum.repos.d sudo mkdir bak sudo mv *.repo ./baksudo wget -P /etc/yum.repos.d/ http://mirrors.aliyun.com/repo/Centos-7.repo; sudo wget -P /etc/yum.repos.d/ http://mirrors.aliyun.com/repo/epel-7.re…

手机拍照技术

拍照技巧 说明: 本文将主要介绍摄影和手机常见技巧&#xff1b; 1. 摄影的基本知识 **说明&#xff1a;**关于摄影&#xff0c;手机和相机的原理都是相同的&#xff0c;不同的是相机在很多方面优于手机&#xff0c;但是专业的设备对于我们这种的非专业的人来说&#xff0c;刚…

乾坤微前端js沙箱机制

1 快照沙箱 modifyPropsMap对象存储子应用的属性&#xff1b; windowSnapshot对象存储微应用未加载时的window对象属性&#xff1b;进入微应用&#xff0c;利用windowSnapshot对象存储window对象的属性&#xff1b; 并将window对象的属性替换为modifyPropsMap对象的属性&#x…

Linux时间同步练习

题目如下&#xff1a; 一.配置server主机要求如下&#xff1a; 1.server主机的主机名称为 ntp_server.example.com 2.server主机的IP为&#xff1a; 172.25.254.100 3.server主机的时间为1984-11-11 11&#xff1a;11&#xff1a;11 4.配置server主机的时间同步服务要求可以被所…

重磅,巫师3即将发布mod编辑器并开放创意工坊

热乎乎的消息&#xff01;巫师3即将推出mod编辑器和开放创意工坊&#xff01; 根据巫师3官方Steam消息&#xff0c;听说年底将推出mod编辑器&#xff0c;目前已经开始内测。想试用的玩家们&#xff0c;可以到redkit商店页面申请访问权限&#xff0c;体验最新的创意工具。 此外&…

NameError: name ‘init_detector’ is not defined

使用模型提取人体pose&#xff0c;遇到的问题记录。 1. 排查问题直接讲报错的地方拷贝在python中直接运行。 运行后提示&#xff1a; ModuleNotFoundError: No module named mmcv._ext 经过各种的地方去查找问题 github的issue Error in init_detector Issue #3354 ope…

存入Redis的值前面有很多空格

说明&#xff1a;记录一次使用Redis的错误&#xff1b; 场景 在将验证码存入Redis时&#xff0c;发现存入的值前面有很多空格&#xff0c;导致在与前端传入的值比较时&#xff0c;一直是false&#xff0c;验证不通过。如下&#xff1a; 上面这些“□”是占位符&#xff0c;复…

STM32单片机中TogglePin和WritePin的区别及使用方法

目录 1.区别 2.使用方法 3. HAL_GPIO_TogglePin函数 4.HAL_GPIO_WritePin函数 在STM32单片机中&#xff0c;WritePin用于将引脚设置为特定电平&#xff0c;而TogglePin用于切换引脚的电平。 1.区别 TogglePin是切换引脚电平状态&#xff0c;即引脚电平状态在高电平和低电…

学习笔记(4月17日)vector底层原理

1.vector<vector>底层原理 vector是表示可变大小数组的序列容器&#xff0c;相当于一个动态的数组&#xff0c;比数组优越的在于它具有可动态改变的大小&#xff0c;同时&#xff0c;它写成了类模板&#xff0c;说明可以适用于其他类型&#xff0c;包括vector本身&#…

Oracle数据库故障类别及日常运维规划策略

一、故障类别 1、语句故障 单个数据库操作失败&#xff08;select、insert、update或delete&#xff09;&#xff0c;如&#xff1a; 在表中输入无效的数据&#xff0c;解决方法&#xff1a;可与用户合作来验证并更正数据&#xff1b;执行操作&#xff0c;但权限不足&#x…

rust 学习笔记(13-19)

13 迭代器与闭包 Rust 的设计灵感来源于很多现存的语言和技术。其中一个显著的影响就是 函数式编程&#xff08;functional programming&#xff09;。函数式编程风格通常包含将函数作为参数值或其他函数的返回值、将函数赋值给变量以供之后执行等等。 闭包&#xff08;Closu…

游戏、app抓包

文章目录 协议app抓包游戏抓包 协议 在抓包之前&#xff0c;首先我们要对每个程序使用什么协议有个大致的了解&#xff0c;比如网页这种就是走的http协议。 在一些app中我们通过发送一个请求&#xff0c;然后服务器接受&#xff0c;响应&#xff0c;返回一个数据包&#xff0c…

4.17freeRTOS

1.总结串口的发送和接收功能使用到的函数 串口的数据发送 HAL_StatusTypeDef HAL_UART_Transmit(UART_HandleTypeDef *huart, const uint8_t *pData, uint16_t Size, uint32_t Timeout) UART_HandleTypeDef *huart&#xff1a;指定要使用的串口 const uint8_t *pData&#xf…

【Python-基础】列表合集

.tolist() 将其他数据类型转换成列表 1.可以将<class ‘pandas.core.series.Series’>转换为列表 images [img_id[filename].tolist() for img_id in data] # data是一个列表,列表中每一项都是用read_csv函数读取的csv文件内容 # type(img_id[filename]) <class …

网站模板-慈善捐赠基金会网站模板 Bootstrap4 html

目录 一.前言 二.预览 三.下载链接 一.前言 这是一个慈善网站的页面。页面包含了导航栏、横幅部分、关于、使命、新闻、活动、捐赠和页脚等不同的部分。该网站还包含了一些CSS样式和JavaScript脚本来实现交互和样式效果。 这个网站的具体结构如下&#xff1a; 导航栏部分&a…

吐血整理102个Python项目,从基础到高级,练完你就牛了!

前言 Python 初学者在迈过安装编程环境和基本语法的门槛&#xff0c;准备大展身手的时候&#xff0c;可能突然就会进入迷茫期&#xff1a; 不知道做些什么、再学些什么。。。 然后对编程的兴趣就会慢慢消退&#xff0c;找不到坚持下去的理由&#xff0c;从而慢慢淡忘之前学会…

算法中的背包问题

背包问题 背包问题 是经典的动态规划问题&#xff0c;它一共有 9 个分类&#xff1a; 01 背包问题 完全背包问题 多重背包问题 混合背包问题 二维费用背包问题 分组背包问题 背包问题求方案数 求背包问题的方案 有依赖的背包问题 01背包问题 完全背包问题 322.零钱兑换 给…

链表中LinkList L与LinkList *L( * L.elem L->elem)

摘要 LinkList L&#xff1a;L是结构体指针&#xff0c;使用“->“运算符来访问结构体成员&#xff1b;&#xff08;*L&#xff09;是结构体&#xff0c;使用"."运算符访问结构体成员 函数是否有&看是否要返回该链表等&#xff0c;若返回加&&#xff0c…