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

news2024/10/5 16:23:39

原文链接: 

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 key
 
W, 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)//2
 
sound1, 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, h
        self.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 = None
    def show(self):
        self.arc.batch = self.cir.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
 
class 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 = False
    def __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 0
    def 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 0
    def adjacent(self, point1, point2):
        return point1*point2
    def 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 True
    def 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]) or
                            self.inline(p[i],(p1,p2)[i]))and self.diagonal(p[i], (p2,p1)[i]):
                        self.point.append(p[i])
                        return True
    def connect(self, p1, p2):
        if (ret := self.connect1(p1, p2) or self.connect2(p1, p2)):
            self.showlines(p1, p2)
        return ret
    def getxy(self, row, col):
        return x0+col*(w+space)+w//2, y0+row*(h+space)+h//2
    def 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 = True
    def 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, point2
        self.drawline(*points)
        self.point.clear()
    def hidelines(self):
        for line in self.lines: line.visible = False
    def linevisible(self):
        return self.lines[0].visible
 
def initMatrix(row, col):
    global matrix, Array, Boxes
    matrix = Matrix(row+2, col+2)
    Array, Boxes = matrix.array, Matrix().array
    for i in range(row):
        for j in range(col):
            Array[i+1][j+1] = 0
    COLOR = 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 = 0
        self.rc, self.rc2 = Point(), Point()
        self.array, self.arces = Array, Boxes
        self.last1, self.last2, self.lastz = None, None, None
        self.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(): return
        if 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').rgba
            elif 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').rgba
                if self.rc == self.rc2:
                    self.last1.arc.color = Color('WHITE').rgba
                    self.last1, self.last2 = None, None
                else:
                    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).name
    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}')
        else:
            sound2.play()
        self.last1.arc.color = self.last2.arc.color = Color('WHITE').rgba
        self.lastz = self.last1, self.last2
        self.last1, self.last2 = None, None
        matrix.hidelines()
        if game.success():
            window.set_caption('彩色方块连连看——任务完成!')
            game.label1.batch = game.label2.batch = batch2
            clock.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] = 1
    def 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] = 0
    def success(self):
        return sum(sum(self.array,[]))==(row+2)*(col+2) 
 
def main(event):
    global game
    game = Game()
    game.label1.batch = game.label2.batch = None
    window.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 score
    if (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, batch
    elif symbol == key.F and modifiers & key.MOD_CTRL:
        if sum(sum(game.array,[]))%2: return
        boxsample = []
        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.coloradmin.cn/o/1602685.html

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

相关文章

Java中的容器

Java中的容器主要包括以下几类&#xff1a; Collection接口及其子接口/实现类&#xff1a; List 接口及其实现类&#xff1a; ArrayList&#xff1a;基于动态数组实现的列表&#xff0c;支持随机访问&#xff0c;插入和删除元素可能导致大量元素移动。LinkedList&#xff1a;基…

【数据结构与算法】:关于时间复杂度与空间复杂度的计算(C/C++篇)——含Leetcode刷题

文章目录 一、什么是时间复杂度和空间复杂度&#xff1f;1.1 算法效率1.2 时间复杂度的概念1.3 空间复杂度的概念1.4 复杂度计算在算法中的意义 二、时间复杂度的计算2.1 大O渐进表示法2.2 常见时间复杂度计算举例 三、空间复杂度的计算四、Leetcode刷题1. 消失的数2. 旋转数组…

对接实例:致远OA对接金蝶云星空场景解决方案

正文&#xff1a;很多企业在数字化建设得时候&#xff0c;对内部系统间的高效协同与数据流转提出了更高要求。金蝶云星空作为行业领先的ERP解决方案&#xff0c;与专业协同办公平台致远OA的深度对接&#xff0c;在人员管理、组织架构、采购与销售合同、费用审批等在内的全方位企…

javaWeb项目-网上图书商城系统功能介绍

项目关键技术 开发工具&#xff1a;IDEA 、Eclipse 编程语言: Java 数据库: MySQL5.7 框架&#xff1a;ssm、Springboot 前端&#xff1a;Vue、ElementUI 关键技术&#xff1a;springboot、SSM、vue、MYSQL、MAVEN 数据库工具&#xff1a;Navicat、SQLyog 1、Java技术 Java语…

Flask框架初探-如何在本机发布一个web服务并通过requests访问自己发布的服务-简易入门版

Flask框架初探 在接触到网络框架之前我其实一直对一个事情有疑惑&#xff0c;跨语言的API在需要传参的情况下究竟应该如何调用&#xff0c;之前做过的项目里&#xff0c;我用python做了一个代码使用一个算法得到一个结果之后我应该怎么给到做前端的同学或者同事&#xff0c;之前…

2024腾讯一道笔试题--大小写字母移动

题目&#x1f357; 有一个字符数组,其中只有大写字母和小写字母,将小写字母移到前面, 大写字符移到后面,保持小写字母本身的顺序不变,大写字母本身的顺序不变, 注意,不要分配新的数组.(如:wCelOlME,变为wellCOME). 思路分析&#x1f357; 类似于冒泡排序&#xff0c;两两比较…

JavaSE中的String类

1.定义方式 常见的三种字符串构造 public class Test1 {public static void main(String[] args) {// 使用常量串构造String str1 "abc";System.out.println(str1);// 直接newString对象String str2 new String("ABC");System.out.println(str2);// 使用…

ssm056基于Java语言校园快递代取系统的设计与实现+jsp

校园快递代取系统设计与实现 摘 要 现代经济快节奏发展以及不断完善升级的信息化技术&#xff0c;让传统数据信息的管理升级为软件存储&#xff0c;归纳&#xff0c;集中处理数据信息的管理方式。本校园快递代取系统就是在这样的大环境下诞生&#xff0c;其可以帮助管理者在短…

node基础 第二篇

01 ffmpeg开源跨平台多媒体处理工具&#xff0c;处理音视频&#xff0c;剪辑&#xff0c;合并&#xff0c;转码等 FFmpeg 的主要功能和特性:1.格式转换:FFmpeg 可以将一个媒体文件从一种格式转换为另一种格式&#xff0c;支持几乎所有常见的音频和视频格式&#xff0c;包括 MP…

工业控制(ICS)---OMRON

OMRON FINS 欧姆龙厂商 命令代码(Command CODE)特别多&#xff0c;主要关注读写相关&#xff0c;如&#xff1a; Memory Area Read (0x0101) Memory Area Write (0x0102) Multiple Memory Area Read (0x0104) Memory Area Transfer (0x0105) Parameter Area Read (0x0201) Pa…

ARM_day8:温湿度数据采集应用

1、IIC通信过程 主机发送起始信号、主机发送8位(7位从机地址1位传送方向(0W&#xff0c;1R))、从机应答、发数据、应答、数据传输完&#xff0c;主机发送停止信号 2、起始信号和终止信号 SCL时钟线&#xff0c;SDA数据线 SCL高电平&#xff0c;SDA由高到低——起始信号 SC…

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主机的时间同步服务要求可以被所…

突破数据存储瓶颈!转转业财系统亿级数据存储优化实践

1.背景 1.1 现状 目前转转业财系统接收了上游各个业务系统&#xff08;例如&#xff1a;订单、oms、支付、售后等系统&#xff09;的数据&#xff0c;并将其转换为财务数据&#xff0c;最终输出财务相关报表和指标数据&#xff0c;帮助公司有效地进行财务管理和决策。 转转业…

Matlab|基于改进遗传算法的配电网故障定位

目录 1 主要内容 2 部分代码 3 部分程序结果 4 下载链接 1 主要内容 该程序复现文章《基于改进遗传算法的配电网故障定位》&#xff0c;将改进的遗传算法应用于配电网故障定位中, 并引入分级处理思想, 利用配电网呈辐射状的特点, 首先把整个配电网划分为主干支路和若干独立…

Pr2024安装包(亲测可用)

目录 一、软件简介 二、软件下载 一、软件简介 Premiere简称“Pr”&#xff0c;是一款超强大的视频编辑软件&#xff0c;它可以提升您的创作能力和创作自由度&#xff0c;它是易学、高效、精确的视频剪辑软件&#xff0c;提供了采集、剪辑、调色、美化音频、字幕添加、输出、D…

minio如何配置防盗链

MinIO 是一个开源的对象存储服务器&#xff0c;用于存储大量的数据&#xff0c;同时提供了丰富的功能和 API。配置防盗链可以帮助你控制谁可以访问存储在 MinIO 上的对象。以下是在 MinIO 中配置防盗链的一般步骤&#xff1a; 编辑 config.json 文件&#xff1a; 找到 MinIO 服…

【Godot4自学手册】第三十七节钥匙控制开门

有些日子没有更新了&#xff0c;实在是琐事缠身啊&#xff0c;今天继续开始自学Godot4&#xff0c;继续完善地宫相关功能&#xff0c;在地宫中安装第二道门&#xff0c;只有主人公拿到钥匙才能开启这扇门&#xff0c;所以我们在合适位置放置一个宝箱&#xff0c;主人公开启宝箱…

vue+element作用域插槽

作用域插槽的样式由父组件决定&#xff0c;内容却由子组件控制。 在el-table使用作用域插槽 <el-table><el-table-column slot-scope" { row, column, $index }"></el-table-column> </el-table>在el-tree使用作用域插槽 <el-tree>…

【Java开发指南 | 第十一篇】Java运算符

读者可订阅专栏&#xff1a;Java开发指南 |【CSDN秋说】 文章目录 算术运算符关系运算符位运算符逻辑运算符赋值运算符条件运算符&#xff08;?:&#xff09;instanceof 运算符Java运算符优先级 Java运算符包括&#xff1a;算术运算符、关系运算符、位运算符、逻辑运算符、赋值…

C语言入门案例-学生管理系统

要求&#xff1a;学员管理系统可以实现对学员的添加、全部显示、查询、修改、删除功能 完整代码示例&#xff1a; #include <stdio.h> // 定义容量 #define NUM 100//自定义结构体 typedef struct st {char name[30];int age;char sex[10]; }STU;//传入四个初始数据 STU…