Python 一步一步教你用pyglet制作“彩色方块连连看”游戏

简介: Python 一步一步教你用pyglet制作“彩色方块连连看”游戏

彩色方块连连看

本篇除了介绍怎样用pyglet制作连连看游戏,还将介绍如果使用自定义库colorlib,用它来描绘游戏中多种颜色的彩色方块。自定义库colorlib的由来,另请阅读《python 教你如何创建一个自定义库 colorlib.py》,

第一步

见原文中,有一个创建随机彩色霓虹方块的代码:

import pyglet
from colorlib import randcolorTuples as ctpl
window = pyglet.window.Window(800, 600, caption='色块展示')
 
color = ctpl(16)
batch = pyglet.graphics.Batch()
shape = [pyglet.shapes.Rectangle(180+i%4*120, 120+i//4*100, 100, 80, color=color[i], batch=batch) for i in range(len(color))]
 
@window.event
def on_draw():
    window.clear()
    batch.draw()
 
def change_color(e):
    for i,c in enumerate(ctpl(16)):
        shape[i].color = c
 
pyglet.clock.schedule_interval(change_color, 0.1)
 
pyglet.app.run()

运行效果:

第二步

创建更多方块,方块大小由参数决定;随机色由colorlib.randcolorTuples函数产生。

1.from pyglet import *
from colorlib import randcolorTuples as ctpl
 
W, H = 800, 600
window = window.Window(W, H, caption='色块展示')
batch = graphics.Batch()
 
row, col, space = 8, 10, 5
width = w = (W-space)//col-space
height = h = (H-space)//row-space
x0, y0 = (W-(w+space)*col+space)//2, (H-(h+space)*row+space)//2
 
color = ctpl(row*col)
shape = [[1]*col for _ in range(row)]
for r,arr in enumerate(shape):
    for c,num in enumerate(arr):
        shape[r][c] = shapes.Rectangle(x0+c*(w+space), y0+r*(h+space), w, h, color=color[c+r*len(arr)], batch=batch)
 
@window.event
def on_draw():
    window.clear()
    batch.draw()
 
def change_color(e):
    for i,c in enumerate(ctpl(row*col)):
        shape[i//col][i%col].color = c
 
clock.schedule_interval(change_color, 0.1)
 
app.run()

第三步

取消“闪烁”,方块增加边框并改写为Box类、增加一个对应存放方块状态的列表Array。

from pyglet import *
from colorlib import *
 
ctpl = randcolorTuples
W, H = 800, 600
window = window.Window(W, H, caption='色块展示')
gl.glClearColor(*Color('lightblue3').decimal)
batch = graphics.Batch()
 
row, col, space = 8, 10, 5
width = w = (W-space)//col-space
height = h = (H-space)//row-space
x0, y0 = (W-(w+space)*col+space)//2, (H-(h+space)*row+space)//2
 
color = ctpl(row*col)
Array = [[1]*col for _ in range(row)]  # 用于控制方块的状态
 
class Box:
    def __init__(self, x, y, w, h, color, batch=batch):
        self.rect = shapes.Rectangle(x, y, w, h, color=color, batch=batch)
        self.box  = shapes.Box(x, y, w, h, color=(255,255,255), thickness=3, batch=batch)
    def visible(self, visible=True):
        self.box.batch = self.rect.batch = batch if visible else None
 
Array[0][0] = Array[2][2] = Array[5][7] = 0  # 设置三个方块消失
for r,arr in enumerate(Boxes:=[_[:] for _ in Array]):
    for c,_ in enumerate(arr):
        Boxes[r][c] = Box(x0+c*(w+space), y0+r*(h+space), w, h, color[c+r*len(arr)])
        Boxes[r][c].visible(Array[r][c])
 
@window.event
def on_draw():
    window.clear()
    batch.draw()
 
app.run()

运行效果:

注:顺带测试一下在for...in...语句enumerate()函数中使用海象操作符:=。

for r,arr in enumerate(Boxes:=[_[:] for _ in Array]):

第四步

限制生产颜色时,每种颜色只能出现4次,即2组连连看。

COLOR = []
while len(COLOR)<row*col//4:
    if (c:=randcolorTuple()) not in COLOR:
        COLOR.append(c)
COLOR = sample(COLOR*4, row*col
from pyglet import *
from colorlib import *
 
ctpl = randcolorTuples
W, H = 800, 600
window = window.Window(W, H, caption='色块展示')
gl.glClearColor(*Color('lightblue3').decimal)
batch = graphics.Batch()
 
row, col, space = 8, 10, 5
width = w = (W-space)//col-space
height = h = (H-space)//row-space
x0, y0 = (W-(w+space)*col+space)//2, (H-(h+space)*row+space)//2
 
COLOR = []
while len(COLOR)<row*col//4:
    if (c:=randcolorTuple()) not in COLOR:
        COLOR.append(c)
COLOR = sample(COLOR*4, row*col)
 
class Box:
    def __init__(self, x, y, w, h, color, batch=batch):
        self.rect = shapes.Rectangle(x, y, w, h, color=color, batch=batch)
        self.box  = shapes.Box(x, y, w, h, color=(255,255,255), thickness=3, batch=batch)
        self.visible = True
    def visible(self, visible=True):
        self.box.batch = self.rect.batch = batch if visible else None
 
Array, Boxes = [[[1]*col for _ in range(row)] for _ in range(2)]
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)])
 
@window.event
def on_draw():
    window.clear()
    batch.draw()
 
app.run()

运行效果:

第五步

增加Game类,并加入点击坐标和状态,可以记录方块的位置和状态。

方块的行列坐标与窗口中实际坐标的转换:

r, c = (y-y0)//(h+space), (x-x0)//(w+space)

from pyglet import *
from colorlib import *
 
W, H = 800, 600
window = window.Window(W, H, caption='色块展示')
gl.glClearColor(*Color('lightblue3').decimal)
batch = graphics.Batch()
 
row, col, space = 8, 10, 5
width = w = (W-space)//col-space
height = h = (H-space)//row-space
x0, y0 = (W-(w+space)*col+space)//2, (H-(h+space)*row+space)//2
 
COLOR = []
while len(COLOR)<row*col//4:
    if (c:=randcolorTuple()) not in COLOR:
        COLOR.append(c)
COLOR = sample(COLOR*4, row*col)
Array, Boxes = [[[[11]]*col for _ in range(row)] for _ in range(2)]
 
class Box:
    def __init__(self, x, y, w, h, color, batch=batch):
        self.x, self.y = x, y
        self.w, self.h = w, h
        self.visible, self.pressed = True, False
        self.rect = shapes.Rectangle(x, y, w, h, color=color, batch=batch)
        self.box  = shapes.Box(x, y, w, h, color=(255,255,255), thickness=3, batch=batch)
    def show(self, visible=True):
        self.visible, self.pressed = visible, False
        self.box.batch = self.rect.batch = batch if visible else None
    def hide(self):
        self.show(False)
    def on_mouse_over(self, x, y):
        return self.x<=x<=self.x+self.w and self.y<=y<=self.y+self.h
    def on_mouse_click(self):
        if self.visible:
            self.pressed = True
            if Color('RED').equal(self.box.color):
                self.hide()
        else:
            self.pressed = False
            self.show()
        self.box.color = Color('RED' if self.pressed else 'WHITE').rgba
 
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):
        self.array = Array
        self.boxes = Boxes
    def on_mouse_click(self, x, y):
        r, c = (y - y0)//(h+space), (x - x0)//(w+space)
        if r in range(row) and c in range(col) and self.boxes[r][c].on_mouse_over(x, y):
            self.boxes[r][c].on_mouse_click()
            self.array[r][c] = self.boxes[r][c].visible*10+self.boxes[r][c].pressed
            return r, c, self.array[r][c]
 
game = Game()
 
@window.event
def on_mouse_press(x, y, dx, dy):
    window.set_caption(f'色块展示——坐标和状态:{game.on_mouse_click(x, y)}')
 
@window.event
def on_draw():
    window.clear()
    batch.draw()
 
app.run()

运行效果:

第六步

增加连线功能,用shapes.Line画一根淡金色的直线来表示:

self.line = shapes.Line(0, 0, 0, 0, width=5, color=Color('light gold').rgba)

再增加一个属性self.click来存储一组连线方块的坐标;增加方法getxy(),以获取方块在窗口中的实际坐标:


   def getxy(self, row, col):

       return x0+col*(w+space)+w//2, y0+row*(h+space)+h//2

from pyglet import *
from colorlib import *
 
W, H = 800, 600
window = window.Window(W, H, caption='彩色色块连连看')
gl.glClearColor(*Color('lightblue3').decimal)
batch = graphics.Batch()
group = graphics.Group()
 
row, col, space = 8, 10, 5
width = w = (W-space)//col-space
height = h = (H-space)//row-space
x0, y0 = (W-(w+space)*col+space)//2, (H-(h+space)*row+space)//2
 
COLOR = []
while len(COLOR)<row*col//4:
    if (c:=randcolorTuple()) not in COLOR:
        COLOR.append(c)
COLOR = sample(COLOR*4, row*col)
Array, Boxes = [[[1]*col for _ in range(row)] for _ in range(2)]
 
class Box:
    def __init__(self, x, y, w, h, color, batch=batch):
        self.x, self.y = x, y
        self.w, self.h = w, h
        self.pressed = False
        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)
        self.box.group = group
    def hide(self):
        self.box.batch = self.rect.batch = None
    def on_mouse_over(self, x, y):
        return self.x<=x<=self.x+self.w and self.y<=y<=self.y+self.h
 
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):
        self.array = Array
        self.boxes = Boxes
        self.click = []
        self.last = None
        self.row, self.col = 0, 0
        self.line = shapes.Line(0, 0, 0, 0, width=5, color=Color('light gold').rgba)
        self.line.batch = batch
        self.line.group = group
        self.line.visible = False
    def on_mouse_click(self, x, y):
        if self.line.visible: return
        r, c = (y-y0)//(h+space), (x-x0)//(w+space)
        if r in range(row) and c in range(col) and self.boxes[r][c].on_mouse_over(x, y) and self.array[r][c]:
            self.row, self.col = r, c
            if len(self.click)==0:
                self.click.append((r,c))
                self.last = r, c, self.boxes[r][c]
                self.boxes[r][c].box.color = Color('RED').rgba
            elif len(self.click)==1:
                if (r,c) in self.click:
                    r,c = self.click.pop()
                    self.boxes[r][c].box.color = Color('WHITE').rgba
                else:
                    self.click.append((r,c))
                    self.boxes[r][c].box.color = Color('RED').rgba
                    r2, c2 = self.click[0][0], self.click[0][1]
                    self.line.x, self.line.y = self.getxy(r, c)
                    self.line.x2, self.line.y2 = self.getxy(r2, c2)
                    self.array[r2][c2] = self.array[r][c] = 0
                    self.line.visible = True
                    self.click.clear()
                    clock.schedule_interval(self.update, 0.3)
            return r, c, self.array[r][c]
    def getxy(self, row, col):
        return x0+col*(w+space)+w//2, y0+row*(h+space)+h//2
    def update(self, event):
        self.line.visible = False
        one, another = self.last, self.boxes[self.row][self.col]
        if one[-1].rect.color==another.rect.color:
            one[-1].hide(); another.hide()
            self.last = None
        else:
            self.array[self.row][self.col] = self.array[one[0]][one[1]] = 1
            one[-1].box.color = another.box.color = Color('WHITE').rgba
        clock.unschedule(self.update)
 
@window.event
def on_mouse_press(x, y, dx, dy):
    window.set_caption(f'彩色色块连连看——坐标和状态:{game.on_mouse_click(x, y)}')
 
@window.event
def on_draw():
    window.clear()
    batch.draw()
 
game = Game()
app.run()

运行效果:

第七步

继续优化代码,放弃self.click记录方块的坐标,改为直接用self.last和self.last2来记录一组方块,同样也能操作它们的位置和状态;增加判断任务完成的方法。

   def success(self):

       return sum(sum(self.array,[]))==0

再增加一个记录行列坐标的类,方便代码的书写:

class RC:
    def __init__(self, x=0, y=0):
        self.r, self.c = x, y
    def __eq__(self, other):
        return self.rc == other.rc
    @property
    def rc(self):
        return self.r, self.c
 
from pyglet import *
from colorlib import *
 
W, H = 800, 600
window = window.Window(W, H, caption='彩色色块连连看')
gl.glClearColor(*Color('lightblue3').decimal)
batch, group = graphics.Batch(),graphics.Group()
 
row, col, space = 8, 10, 5
w, h = W//col-space*2, H//row-space*2
x0, y0 = (W-(w+space)*col+space)//2, (H-(h+space)*row+space)//2
 
COLOR = []
while len(COLOR)<row*col//4:
    if (c:=randcolorTuple()) not in COLOR:
        COLOR.append(c)
COLOR = sample(COLOR*4, row*col)
Array, Boxes = [[[1]*col for _ in range(row)] for _ in range(2)]
 
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)
        self.box.group = group
    def hide(self):
        self.box.batch = self.rect.batch = None
    def on_mouse_over(self, x, y):
        return self.x<=x<=self.x+self.w and self.y<=y<=self.y+self.h
 
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 RC:
    def __init__(self, x=0, y=0):
        self.x, self.y = x, y
    def __eq__(self, other):
        return self.rc == other.rc
    @property
    def rc(self):
        return self.x, self.y
 
class Game:
    def __init__(self):
        self.array = Array
        self.boxes = Boxes
        self.rc, self.rc2 = RC(), RC()
        self.last, self.last2 = None, None
        self.line = shapes.Line(0, 0, 0, 0, width=5, color=Color('light gold').rgba, batch=batch, group=group)
        self.line.visible = False
    def on_mouse_click(self, x, y):
        if self.line.visible or self.success(): return
        r, c = (y-y0)//(h+space), (x-x0)//(w+space)
        if r in range(row) and c in range(col) and self.boxes[r][c].on_mouse_over(x, y) and self.array[r][c]:
            if self.last is None and self.last2 is None:
                self.rc, self.last = RC(r, c), self.boxes[r][c]
                self.last.box.color = Color('RED').rgba
            elif self.last is not None and self.last2 is None:
                self.rc2, self.last2 = RC(r, c), self.boxes[r][c]
                self.last2.box.color = Color('RED').rgba
                if self.rc == self.rc2:
                    self.last.box.color = Color('WHITE').rgba
                    self.last, self.last2 = None, None
                else:
                    self.line.x, self.line.y = self.getxy(r, c)
                    self.line.x2, self.line.y2 = self.getxy(self.rc.x, self.rc.y)
                    self.line.visible = True
                    clock.schedule_interval(self.update, 0.3)
            return (r, c), Color(self.boxes[r][c].rect.color).name
    def getxy(self, row, col):
        return x0+col*(w+space)+w//2, y0+row*(h+space)+h//2
    def update(self, event):
        self.line.visible = False
        clock.unschedule(self.update)
        if self.last.rect.color==self.last2.rect.color:
            self.last.hide(); self.last2.hide()
            self.array[self.rc.x][self.rc.y] = self.array[self.rc2.x][self.rc2.y] = 0
        else:
            self.last.box.color = self.last2.box.color = Color('WHITE').rgba
        self.last, self.last2 = None, None
        if game.success():
            window.set_caption('彩色色块连连看——任务完成!')         
    def success(self):
        return sum(sum(self.array,[]))==0    
 
@window.event
def on_draw():
    window.clear()
    batch.draw()
 
@window.event
def on_mouse_press(x, y, dx, dy):
    ret = game.on_mouse_click(x, y)
    if ret and not game.success():
        window.set_caption(f'彩色色块连连看——坐标:{ret[0]}  颜色:{ret[1]}')
 
game = Game()
app.run()

运行效果:

动态效果展示

为节省截图时间把第9行代码的8行10列暂改为4行5列。


小结

至此,一个代码不到100行的简单的“彩色方块连连看”游戏完成了。下一期文章将继续探讨“连连看”的直线规则,即不能有斜线连接方块,只能由水平和垂直的直线相连方块且直线最多转弯2次。

待续......


附录

colorlib库Color类的主代码介绍

class Color:
    '''
    Color(3-tuple: tuple) -> Color # 3-tuple as (r, g, b)
    Color(4-tuple: tuple) -> Color # 4-tuple as (r, g, b, a)
    Color(color_name: str) -> Color # color_name as 'Red','Blue',...
    Color(color_string: str) -> Color # color_string as '#rrggbb'
    Object for color representations.
    '''
    def __init__(self, r=0, g=0, b=0, a=None): 
        self.__alpha = (a is not None) and isinstance(a, (int, float))
        if all(map(lambda r:isinstance(r, (int, float)),(r,g,b))):
            self.r, self.g, self.b = map(lambda n:int(n)%256,(r,g,b))
        elif isinstance(r, (tuple, list)) and len(r) in (3, 4):
            self.r, self.g, self.b, self.a = *[int(c)%256 for c in r[:3]], 255
            if len(r)==4: a, self.__alpha = int(r[3])%256, True 
        elif isinstance(r, str) and len(r)==7 and r.startswith('#'):  
            self.r, self.g, self.b = str2tuple(r)  
        elif isinstance(r, str):
            if (rgb := ColorDict.get(r, None)) is None:
                raise ValueError("Invalid Color Name")
            self.r, self.g, self.b, a = *rgb, 255
        else:
            raise ValueError("Invalid argument for class Color")
        self.a = a if self.__alpha else 255
        self.rgb = self.r, self.g, self.b
        self.rgba = self.r, self.g, self.b, self.a
        self.value = self.rgba if self.__alpha else self.rgb
        self.string = tuple2str(self.value[:3])
        self.decimal = tuple(map(lambda x:x/255, self.rgba))
        self.name = {v:k for k,v in ColorDict.items()}.get(self.rgb, 'Noname')
    def __repr__(self):
        rgba = 'RGBA(' if self.__alpha else 'RGB('
        return ', '.join(map(lambda x:str(x).rjust(3),self.value)).join((rgba,')'))
    def randcolor(self):
        '''Convert the Color to any random color in ColorDict.keys().'''
        rgb = randcolorTuple()
        return Color(*rgb, self.a) if self.__alpha else Color(rgb)
    def random(self):
        '''Convert rgb to a 3-tuple of random integer between 0 and 255.'''
        rgb = randint(0,255), randint(0,255), randint(0,255)
        return Color(*rgb, self.a) if self.__alpha else Color(rgb)
    def alpha(self, a=255):
        '''Set alpha value of the Color, or change RGB to RGBA.'''
        self.__init__(*self.rgb, a)
    def equal(self, other):
        '''Compare self.rgba with another color's RGBA tuple.'''
        return self.rgba == other
 

其中,属性 self.decimal 用在了窗口背景设置的代码上:

gl.glClearColor(*Color('lightblue3').decimal)

游戏代码中还用到以下属性:

self.rgba = self.r, self.g, self.b, self.a

self.name = {v:k for k,v in ColorDict.items()}.get(self.rgb, 'Noname')


目录
相关文章
|
2月前
|
IDE 开发工具 Python
Python扑克游戏编程---摸大点
Python扑克游戏编程---摸大点
|
3月前
|
Python
python编写下象棋游戏|4-14
python编写下象棋游戏|4-14
|
3月前
|
人工智能 算法 图形学
总有一个是你想要的分享40个Python游戏源代码
这是一系列基于Python开发的游戏项目集合,包括中国象棋、麻将、足球、坦克大战、扑克等多种类型游戏,运用了Pygame等库实现图形界面与AI算法。此外还包含迷宫、数独、推箱子等益智游戏及经典游戏如《仙剑奇侠传二战棋版》和《星露谷物语》的Python版本,适合编程学习与娱乐。
123 11
|
2月前
|
数据采集 前端开发 Python
Python pygame 实现游戏 彩色 五子棋 详细注释 附源码 单机版
Python pygame 实现游戏 彩色 五子棋 详细注释 附源码 单机版
74 0
|
3月前
|
消息中间件 数据采集 数据库
庆祝吧!Python IPC让进程间的合作,比团队游戏还默契
【9月更文挑战第7天】在这个数字化时代,软件系统日益复杂,单进程已难以高效处理海量数据。Python IPC(进程间通信)技术应运而生,使多进程协作如同训练有素的电竞战队般默契。通过`multiprocessing`模块中的Pipe等功能,进程间可以直接传递数据,无需依赖低效的文件共享或数据库读写。此外,Python IPC还提供了消息队列、共享内存和套接字等多种机制,适用于不同场景,使进程间的合作更加高效、精准。这一技术革新让开发者能轻松应对复杂挑战,构建更健壮的软件系统。
39 1
|
4月前
|
机器学习/深度学习 存储 定位技术
强化学习Agent系列(一)——PyGame游戏编程,Python 贪吃蛇制作实战教学
本文是关于使用Pygame库开发Python贪吃蛇游戏的实战教学,介绍了Pygame的基本使用、窗口初始化、事件处理、键盘控制移动、以及实现游戏逻辑和对象交互的方法。
|
4月前
|
机器学习/深度学习 人工智能 自然语言处理
【机器学习】python之人工智能应用篇--游戏生成技术
游戏生成技术,特别是生成式人工智能(Generative Artificial Intelligence, 简称Generative AI),正逐步革新游戏开发的多个层面,从内容创作到体验设计。这些技术主要利用机器学习、深度学习以及程序化内容生成(Procedural Content Generation, PCG)来自动创造游戏内的各种元素,显著提高了开发效率、丰富了游戏内容并增强了玩家体验。以下是生成式AI在游戏开发中的几个关键应用场景概述
79 2
|
9天前
|
存储 数据挖掘 开发者
Python编程入门:从零到英雄
在这篇文章中,我们将一起踏上Python编程的奇幻之旅。无论你是编程新手,还是希望拓展技能的开发者,本教程都将为你提供一条清晰的道路,引导你从基础语法走向实际应用。通过精心设计的代码示例和练习,你将学会如何用Python解决实际问题,并准备好迎接更复杂的编程挑战。让我们一起探索这个强大的语言,开启你的编程生涯吧!
|
15天前
|
机器学习/深度学习 人工智能 TensorFlow
人工智能浪潮下的自我修养:从Python编程入门到深度学习实践
【10月更文挑战第39天】本文旨在为初学者提供一条清晰的道路,从Python基础语法的掌握到深度学习领域的探索。我们将通过简明扼要的语言和实际代码示例,引导读者逐步构建起对人工智能技术的理解和应用能力。文章不仅涵盖Python编程的基础,还将深入探讨深度学习的核心概念、工具和实战技巧,帮助读者在AI的浪潮中找到自己的位置。
|
15天前
|
机器学习/深度学习 数据挖掘 Python
Python编程入门——从零开始构建你的第一个程序
【10月更文挑战第39天】本文将带你走进Python的世界,通过简单易懂的语言和实际的代码示例,让你快速掌握Python的基础语法。无论你是编程新手还是想学习新语言的老手,这篇文章都能为你提供有价值的信息。我们将从变量、数据类型、控制结构等基本概念入手,逐步过渡到函数、模块等高级特性,最后通过一个综合示例来巩固所学知识。让我们一起开启Python编程之旅吧!