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

这篇具有很好参考价值的文章主要介绍了Python 一步一步教你用pyglet制作“彩色方块连连看”游戏(续)。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

Python 一步一步教你用pyglet制作“彩色方块连连看”游戏(续),# pyglet专栏,python,pyglet,Point类

“彩色方块连连看”游戏(续)

上期讲到相同的色块连接,链接见: Python 一步一步教你用pyglet制作“彩色方块连连看”游戏-CSDN博客

第八步

续上期,接下来要实现相邻方块的连线:

首先来进一步扩展 行列的类:

class RC:
    def __init__(self, r=0, c=0):
        self.r, self.c = r, c
    def __repr__(self):
        return f'Rc({self.r}, {self.c})'
    def __and__(self, other):
        return self.r == other.r and self.c == other.c
    def __or__(self, other):
        return self.r == other.r or self.c == other.c
    def __eq__(self, other):
        return self & other
    def __lt__(self, other):
        return self.r == other.r and self.c != other.c
    def __gt__(self, other):
        return self.r != other.r and self.c == other.c
    def __le__(self, other):
        return self.r == other.r and self.c - other.c
    def __ge__(self, other):
        return self.c == other.c and self.r - other.r
    def __xor__(self, other):
        return self < other or self > other
    def __mod__(self, other):
        return [RC(self.r, other.c), RC(other.r, self.c)]
    def __truediv__(self, other):
        return 1 if self<other and (self<=other)<0 or self>other and (self>=other)<0 else -1
    def __add__(self, other):
        return abs(self<=other)==1 or abs(self>=other)==1
    def __sub__(self, other):
        if self<other: return [RC(self.r,_) for _ in range(self.c+(self/other),other.c,self/other)]
        if self>other: return [RC(_,self.c) for _ in range(self.r+(self/other),other.r,self/other)]
        return []
    def __mul__(self, other):
        if self<other: return not any(Array[self.r+1][_+1] for _ in range(self.c+(self/other),other.c,self/other))
        if self>other: return not any(Array[_+1][self.c+1] for _ in range(self.r+(self/other),other.r,self/other))
        return False

由上面的类可知,self.rc*self.rc2就表示两点相邻,加时update方法中的if语句,就能实现相邻色块的连线并消去:

    def update(self, event):
        self.line.visible = False
        clock.unschedule(self.update)
        if self.last.rect.color==self.last2.rect.color and self.rc*self.rc2:
            self.last.hide(); self.last2.hide()
            self.array[self.rc.r][self.rc.c] = self.array[self.rc2.r][self.rc2.c] = 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('彩色色块连连看——任务完成!') 

代码:

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 = 6, 8, 5
w, h = W//(col+2), H//(row+2)
x0, y0 = (W-(w+space)*col)//2, (H-(h+space)*row)//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, r=0, c=0):
        self.r, self.c = r, c
    def __repr__(self):
        return f'Rc({self.r}, {self.c})'
    def __and__(self, other):
        return self.r == other.r and self.c == other.c
    def __or__(self, other):
        return self.r == other.r or self.c == other.c
    def __eq__(self, other):
        return self & other
    def __lt__(self, other):
        return self.r == other.r and self.c != other.c
    def __gt__(self, other):
        return self.r != other.r and self.c == other.c
    def __le__(self, other):
        return self.r == other.r and self.c - other.c
    def __ge__(self, other):
        return self.c == other.c and self.r - other.r
    def __xor__(self, other):
        return self < other or self > other
    def __mod__(self, other):
        return [RC(self.r, other.c), RC(other.r, self.c)]
    def __truediv__(self, other):
        return 1 if self<other and (self<=other)<0 or self>other and (self>=other)<0 else -1
    def __add__(self, other):
        return abs(self<=other)==1 or abs(self>=other)==1
    def __sub__(self, other):
        if self<other: return [RC(self.r,_) for _ in range(self.c+(self/other),other.c,self/other)]
        if self>other: return [RC(_,self.c) for _ in range(self.r+(self/other),other.r,self/other)]
        return []
    def __mul__(self, other):
        if self<other: return not any(Array[self.r+1][_+1] for _ in range(self.c+(self/other),other.c,self/other))
        if self>other: return not any(Array[_+1][self.c+1] for _ in range(self.r+(self/other),other.r,self/other))
        return False

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.r, self.rc.c)
                    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 and self.rc*self.rc2:
            self.last.hide(); self.last2.hide()
            self.array[self.rc.r][self.rc.c] = self.array[self.rc2.r][self.rc2.c] = 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()

第九步

实现同行或同列的连线,self.rc+self.rc2就能实现同行或同列的点连线。

if self.last.rect.color==self.last2.rect.color and ((self.rc*self.rc2) or (self.rc+self.rc2)):

代码

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+2), H//(row+2)
x0, y0 = (W-(w+space)*col)//2, (H-(h+space)*row)//2

COLOR = []
while len(COLOR)<row*col//8:
    if (c:=randcolorTuple()) not in COLOR:
        COLOR.append(c)
COLOR = sample(COLOR*8, 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.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

class Matrix:
    def __init__(self, row=row, col=col):
        self.array = [[0]*col for _ in range(row)]
    def __repr__(self):
         return '\n'.join(map(str,self.array))+'\n'

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] = 1
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, r=0, c=0):
        self.r, self.c = r, c
    def __repr__(self):
        return f'Rc({self.r}, {self.c})'
    def __and__(self, other):
        return self.r == other.r and self.c == other.c
    def __or__(self, other):
        return self.r == other.r or self.c == other.c
    def __eq__(self, other):
        return self & other
    def __lt__(self, other):
        return self.r == other.r and self.c != other.c
    def __gt__(self, other):
        return self.r != other.r and self.c == other.c
    def __le__(self, other):
        return self.r == other.r and self.c - other.c
    def __ge__(self, other):
        return self.c == other.c and self.r - other.r
    def __xor__(self, other):
        return self < other or self > other
    def __mod__(self, other):
        return [RC(self.r, other.c), RC(other.r, self.c)]
    def __truediv__(self, other):
        return 1 if self<other and (self<=other)<0 or self>other and (self>=other)<0 else -1
    def __add__(self, other):
        return abs(self<=other)==1 or abs(self>=other)==1
    def __sub__(self, other):
        if self<other: return [RC(self.r,_) for _ in range(self.c+(self/other),other.c,self/other)]
        if self>other: return [RC(_,self.c) for _ in range(self.r+(self/other),other.r,self/other)]
        return []
    def __mul__(self, other):
        if self<other: return not any(Array[self.r+1][_+1] for _ in range(self.c+(self/other),other.c,self/other))
        if self>other: return not any(Array[_+1][self.c+1] for _ in range(self.r+(self/other),other.r,self/other))
        return False

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+1][c+1]:
            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.r, self.rc.c)
                    self.line.visible = True
                    clock.schedule_interval(self.update, 0.3)
            return RC(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 and ((self.rc*self.rc2) or (self.rc+self.rc2)):
            self.last.hide(); self.last2.hide()
            self.array[self.rc.r+1][self.rc.c+1] = self.array[self.rc2.r+1][self.rc2.c+1] = 0
            print(matrix)
        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()

第十步

改写RC行列类完善更多的功能,见另一篇博文:

Python 妙用运算符重载——玩出“点”花样来-CSDN博客

RC行列改写成整数坐标点的类,完整的 pointlib.py代码如下:

class Point:
    def __init__(self, x=0, y=0):
        self.x, self.y = x, y
    def __repr__(self):
        return f'Point({self.x}, {self.y})'
    def __str__(self):
        return f'({self.x}, {self.y})'
    def __getitem__(self, index):
        if index in range(-2,2):
            return self.y if index in (1,-1) else self.x
        raise IndexError("Index out of range")
    def __setitem__(self, index, value):
        if index in (0, -2):
            self.x = value
        elif index in (1, -1):
            self.y = value
        else:
            raise IndexError("Index out of range.")
    @property
    def value(self):
        return self.x, self.y
    def __len__(self):
        return 2
    def __abs__(self):
        return Point(*map(abs,(self.x, self.y)))
    def __bool__(self):
        return self.x>=0 and self.y>=0
    def __neg__(self):
        return Point(-self.x, -self.y)
    def __pos__(self):
        return self(0, 1), self(0, -1), self(-1), self(1)
    def __call__(self, dx=0, dy=0):
        return Point(self.x + dx, self.y + dy)
    def __eq__(self, other):
        return self.x == other.x and self.y == other.y
    def __ne__(self, other):
        return self.x != other.x or self.y != other.y
    def __gt__(self, other):
        return self.x == other.x and self.y - other.y
    def __lt__(self, other):
        return self.y == other.y and self.x - other.x
    def __ge__(self, other):
        return self.x == other.x and abs(self.y - other.y)==1
    def __le__(self, other):
        return self.y == other.y and abs(self.x - other.x)==1
    def __and__(self, other):
        return self.x != other.x and self.y != other.y
    def __radd__(self, n):
        return self(0, n), self(0, -n), self(-n), self(n)
    def __or__(self, other):
        return self.x == other.x or self.y == other.y
    def __xor__(self, other):
        return self.x == other.x and self.y != other.y or self.x != other.x and self.y == other.y
    def __invert__(self):
        return Point(self.y, self.x)
    def __lshift__(self, other):
        return Point(self.x + other, self.y)
    def __rshift__(self, other):
        return Point(self.x, self.y + other)
    def __add__(self, other):
        return Point(self.x + other.x, self.y + other.y)
    def __sub__(self, other):
        return ((self.x - other.x)**2 + (self.y - other.y)**2)**0.5
    def __mul__(self, other):
        return self >= other or self <= other
    def __truediv__(self, other):
        return (self^other) and (1 if (self<other)<0 or (self>other)<0 else -1)
    def __pow__(self, other):
        if self^other:
            if self<other: return [Point(_, self.y) for _ in range(self.x+(self/other),other.x,self/other)]
            if self>other: return [Point(self.x, _) for _ in range(self.y+(self/other),other.y,self/other)]
    def __mod__(self, other):
        return [Point(self.x, other.y), Point(other.x, self.y)]
    def __floordiv__(self, other):
        if self&other:
            mod1, mod2 = self % other
            return self**mod1 + [mod1] + mod1**other, self**mod2 + [mod2] + mod2**other
    def __rpow__(self, other):
        assert(isinstance(other, (tuple, list)) and len(other)==3)
        x, y, n = other
        return [Point(i, n) for i in range(min(x, self.x), max(x, self.x)+1)]
    def __rfloordiv__(self, other: tuple):
        assert(isinstance(other, (tuple, list)) and len(other)==3)
        x, y, n = other
        return [Point(n, i) for i in range(min(y, self.y), max(y, self.y)+1)]

第十一步

实现一个折角的连线,如下图a点到b点,只要判断a->c->b或者a->d->b是通路即可:

Python 一步一步教你用pyglet制作“彩色方块连连看”游戏(续),# pyglet专栏,python,pyglet,Point类

对角连线的核心函数:

    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

第十二步

实现两个折角的连线,如下图的P点,如它和指点坐标不是相邻也不是同行或同列并且一个折角也不能相连,那么它向上下左右逐点延伸,只要有一个点能与指点坐标一个折角相连就完成了两个折角的相连。

Python 一步一步教你用pyglet制作“彩色方块连连看”游戏(续),# pyglet专栏,python,pyglet,Point类

最终实现

用前两步的思路,进一步完善和改写各个类,以完成所有的各种连线情况: 

一、相邻

    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

四、以上3种情况

    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

完整代码

再加上键盘事件等功能:

ctrl+Z 恢复一步

ctrl+F 保留剩余方块的随机刷新

ctrl+R 保留所有方块的重新开始 

ctrl+S 全部刷新的重新开始

完整代码: 

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.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

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.rc, self.rc2 = Point(), Point()
        self.array, self.boxes = 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.boxes[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.boxes[r][c]
                self.last1.box.color = Color('RED').rgba
            elif self.last1 is not None and self.last2 is None:
                self.rc2, self.last2 = Point(r, c), self.boxes[r][c]
                self.last2.box.color = Color('RED').rgba
                if self.rc == self.rc2:
                    self.last1.box.color = Color('WHITE').rgba
                    self.last1, self.last2 = None, None
                else:
                    if self.last1.rect.color==self.last2.rect.color:
                        matrix.connect(self.rc, self.rc2)
                    clock.schedule_interval(self.update, 0.5)
            return (r, c), Color(self.boxes[r][c].rect.color).name
    def update(self, event):
        clock.unschedule(self.update)
        if self.last1.rect.color==self.last2.rect.color and matrix.connect(self.rc, self.rc2):
            self.hide()
            sound1.play()
        else:
            sound2.play()
        self.last1.box.color = self.last2.box.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):
    if (ret := game.on_mouse_click(x, y)):
        window.set_caption(f'彩色方块连连看——坐标:{ret[0]}  颜色:{ret[1]}')

@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].box.batch, Boxes[i][j].rect.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].rect.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].rect.color = boxsample.pop()

main(event)
app.run()

运行效果

Python 一步一步教你用pyglet制作“彩色方块连连看”游戏(续),# pyglet专栏,python,pyglet,Point类

目录

“彩色方块连连看”游戏(续)

第八步

第九步

第十步

第十一步

第十二步

最终实现

完整代码

运行效果


文章来源地址https://www.toymoban.com/news/detail-844231.html

到了这里,关于Python 一步一步教你用pyglet制作“彩色方块连连看”游戏(续)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • Python 一步一步教你用pyglet制作可播放音乐的扬声器类

    目录 扬声器类 1. 绘制喇叭 2. 扬声器类 3. 禁音状态  4. 设置状态 5. 切换状态 6. 播放音乐 本篇将教你用pyglet画一个小喇叭,如上图。这里要用到pyglety库shapes模块中的圆弧Arc和多边形Pylygon画出这个扬声器的图片: Arc(x, y, radius, segments=None, angle=6.283185307179586, start_angle=0, closed=

    2024年03月10日
    浏览(47)
  • Python 一步一步教你用pyglet仿制鸿蒙系统里的时钟

    目录 鸿蒙时钟 1. 绘制圆盘 2. 创建表类 3. 绘制刻度 4. 刻度数值 5. 添加指针 6. 转动指针 7. 联动时间 8. 时钟走动 本篇将用python pyglet库复刻华为手机鸿蒙系统闹钟程序的时钟,先在上图中抓取出时分秒针及刻度、表盘的颜色RGB值: bHour = (42, 43, 48, 255) bMinute = (70, 71, 75, 255) rSe

    2024年03月12日
    浏览(53)
  • FastAPI + NGINX + Gunicorn:一步一步教你部署一个高性能的Python网页应用

    部署一个 FastAPI 应用到你的服务器是一项复杂的任务。如果你对 NGINX 、 Gunicorn 和 Uvicorn 这些技术不熟悉,可能会浪费大量的时间。如果你是刚接触 Python 语言不久或者希望利用 Python 构建自己的Web应用程序,本文的内容可能会让你第一次部署时更节省时间。 FastAPI 是用于开发

    2024年02月05日
    浏览(53)
  • Android一步一步教你实现Emoji表情键盘

    背景: 说到聊天,就离不开文字、表情和图片,表情和图片增加了聊天的趣味性,让原本无聊的文字瞬间用表情动了起来,今天给大家带来的是表情键盘,教你一步一步实现,先来看下效果图: 效果图 功能: 1、如何控制表情键盘与输入法的切换 2、如何解析表情 3、如何处

    2024年02月16日
    浏览(30)
  • GitHub入门指南:一步一步教你使用GitHub

    引言: GitHub是一个流行的代码托管平台,它提供了强大的版本控制和协作功能,对于开发者来说是一个不可或缺的工具。本文将一步一步地教你如何使用GitHub,从注册账号到代码同步,让你能够快速上手并充分利用这个平台。 打开GitHub官网(github.com)。 点击右上角的\\\"Sign

    2024年02月15日
    浏览(34)
  • Midjourney:一步一步教你如何使用 AI 绘画 MJ

    一步一步如何使用 Midjourney 教程:教学怎么用 MJ? 原文:如何使用 Midjourney 教程 https://bysocket.com/saas-digital-marketing-channel/ Midjourney是一款使用文字描述来生成高质量图像的AI绘画工具。这篇文章主要介绍了Midjourney及其用途,并针对Midjourney的使用提供了一些指南。该工具可以帮

    2023年04月21日
    浏览(67)
  • 文本转语音-微软Azure-一步一步教你从注册到使用

    牙叔教程 简单易懂 他们的中文也许还行, 但是英文我试了都不满意, 我再网上搜到的我认为最好的是 但是丫真贵 Best Free Text To Speech Voice Reader | Speechify 现在的汇率是 139 × 6.91 = 960.49 一年一千块, 好像还行哈, 但是没卡呀, 擦, 比来比去, 还是微软Azure性价比最高, 没有微软Azure的

    2024年02月07日
    浏览(32)
  • 一步一步教你如何使用 Visual Studio Code 编译一段 C# 代码

    以下是一步一步教你如何使用 Visual Studio Code 编写使用 C# 语言输出当前日期和时间的代码: 1、下载并安装 .NET SDK。您可以从 Microsoft 官网下载并安装它。 2、打开 Visual Studio Code,并安装 C# 扩展。您可以在 Visual Studio Code 中通过扩展菜单安装它。 3、打开 Visual Studio Code 中的文

    2024年02月11日
    浏览(38)
  • 【沐风老师】一步一步教你在3dMax中进行UVW贴图和展开UVW的方法

    将简单或程序材质应用于对象并不难。但是当表面需要在其上显示某种纹理时,它会变得更加复杂。任何纹理贴图都放在材质的 Diffuse 插槽中,但渲染的结果可能无法预测。这就是为什么我们需要了解 3DMAX 如何将纹理应用于 3D 对象,什么是 UVW 贴图,以及为什么要“展开”它

    2024年02月04日
    浏览(48)
  • 一步一步教你如何白嫖谷歌云Google Cloud服务器$300美金羊毛

    我们都知道,Depay(现在改名为Dupay了)卡平常可以用于微信,支付宝,美团消费,直接用USDT做日常小额消费,还免收手续费,小额的话,这点还是很舒服的。 但其实,Depay卡的用途远不止此,平常可以多挖掘挖掘。今天教大家如何用Depay卡白嫖谷歌云服务器。申请成功后随即可

    2024年02月04日
    浏览(93)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包