国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

Python 一步一步教你用pyglet制作“彩色方塊連連看”游戲(續(xù))

這篇具有很好參考價(jià)值的文章主要介紹了Python 一步一步教你用pyglet制作“彩色方塊連連看”游戲(續(xù))。希望對(duì)大家有所幫助。如果存在錯(cuò)誤或未考慮完全的地方,請(qǐng)大家不吝賜教,您也可以點(diǎn)擊"舉報(bào)違法"按鈕提交疑問(wèn)。

Python 一步一步教你用pyglet制作“彩色方塊連連看”游戲(續(xù)),# pyglet專欄,python,pyglet,Point類

“彩色方塊連連看”游戲(續(xù))

上期講到相同的色塊連接,鏈接見(jiàn):?Python 一步一步教你用pyglet制作“彩色方塊連連看”游戲-CSDN博客

第八步

續(xù)上期,接下來(lái)要實(shí)現(xiàn)相鄰方塊的連線:

首先來(lái)進(jìn)一步擴(kuò)展 行列的類:

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就表示兩點(diǎn)相鄰,加時(shí)update方法中的if語(yǔ)句,就能實(shí)現(xiàn)相鄰色塊的連線并消去:

? ? 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('彩色色塊連連看——任務(wù)完成!')?

代碼:

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('彩色色塊連連看——任務(wù)完成!')         
    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'彩色色塊連連看——坐標(biāo):{ret[0]}  顏色:{ret[1]}')

game = Game()
app.run()

第九步

實(shí)現(xiàn)同行或同列的連線,self.rc+self.rc2就能實(shí)現(xiàn)同行或同列的點(diǎn)連線。

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('彩色色塊連連看——任務(wù)完成!')         
    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'彩色色塊連連看——坐標(biāo):{ret[0]}  顏色:{ret[1]}')

game = Game()
app.run()

第十步

改寫RC行列類完善更多的功能,見(jiàn)另一篇博文:

Python 妙用運(yùn)算符重載——玩出“點(diǎn)”花樣來(lái)-CSDN博客

RC行列改寫成整數(shù)坐標(biāo)點(diǎn)的類,完整的 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)]

第十一步

實(shí)現(xiàn)一個(gè)折角的連線,如下圖a點(diǎn)到b點(diǎn),只要判斷a->c->b或者a->d->b是通路即可:

Python 一步一步教你用pyglet制作“彩色方塊連連看”游戲(續(xù)),# pyglet專欄,python,pyglet,Point類

對(duì)角連線的核心函數(shù):

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

第十二步

實(shí)現(xiàn)兩個(gè)折角的連線,如下圖的P點(diǎn),如它和指點(diǎn)坐標(biāo)不是相鄰也不是同行或同列并且一個(gè)折角也不能相連,那么它向上下左右逐點(diǎn)延伸,只要有一個(gè)點(diǎn)能與指點(diǎn)坐標(biāo)一個(gè)折角相連就完成了兩個(gè)折角的相連。

Python 一步一步教你用pyglet制作“彩色方塊連連看”游戲(續(xù)),# pyglet專欄,python,pyglet,Point類

最終實(shí)現(xiàn)

用前兩步的思路,進(jìn)一步完善和改寫各個(gè)類,以完成所有的各種連線情況:?

一、相鄰

? ? def adjacent(self, point1, point2):
? ? ? ? return point1*point2

二、同行列

? ? def inline(self, point1, point2):
? ? ? ? return point1^point2 and self.alltrue(point1**point2)

三、對(duì)角線

? ? 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 恢復(fù)一步

ctrl+F 保留剩余方塊的隨機(jī)刷新

ctrl+R 保留所有方塊的重新開(kāi)始?

ctrl+S 全部刷新的重新開(kāi)始

完整代碼:?

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('彩色方塊連連看——任務(wù)完成!')
            game.label1.batch = game.label2.batch = batch2
            clock.schedule_interval(main, 5) # 5秒后自動(dòng)開(kāi)始
    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'彩色方塊連連看——坐標(biāo):{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()

運(yùn)行效果

Python 一步一步教你用pyglet制作“彩色方塊連連看”游戲(續(xù)),# pyglet專欄,python,pyglet,Point類

目錄

“彩色方塊連連看”游戲(續(xù))

第八步

第九步

第十步

第十一步

第十二步

最終實(shí)現(xiàn)

完整代碼

運(yùn)行效果


文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-844231.html

到了這里,關(guān)于Python 一步一步教你用pyglet制作“彩色方塊連連看”游戲(續(xù))的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來(lái)自互聯(lián)網(wǎng)用戶投稿,該文觀點(diǎn)僅代表作者本人,不代表本站立場(chǎng)。本站僅提供信息存儲(chǔ)空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請(qǐng)注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實(shí)不符,請(qǐng)點(diǎn)擊違法舉報(bào)進(jìn)行投訴反饋,一經(jīng)查實(shí),立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費(fèi)用

相關(guān)文章

  • Python 一步一步教你用pyglet制作可播放音樂(lè)的揚(yáng)聲器類

    Python 一步一步教你用pyglet制作可播放音樂(lè)的揚(yáng)聲器類

    目錄 揚(yáng)聲器類 1. 繪制喇叭 2. 揚(yáng)聲器類 3. 禁音狀態(tài)? 4. 設(shè)置狀態(tài) 5. 切換狀態(tài) 6. 播放音樂(lè) 本篇將教你用pyglet畫一個(gè)小喇叭,如上圖。這里要用到pyglety庫(kù)shapes模塊中的圓弧Arc和多邊形Pylygon畫出這個(gè)揚(yáng)聲器的圖片: Arc(x, y, radius, segments=None, angle=6.283185307179586, start_angle=0, closed=

    2024年03月10日
    瀏覽(35)
  • Python 一步一步教你用pyglet仿制鴻蒙系統(tǒng)里的時(shí)鐘

    Python 一步一步教你用pyglet仿制鴻蒙系統(tǒng)里的時(shí)鐘

    目錄 鴻蒙時(shí)鐘 1. 繪制圓盤 2. 創(chuàng)建表類 3. 繪制刻度 4. 刻度數(shù)值 5. 添加指針 6. 轉(zhuǎn)動(dòng)指針 7. 聯(lián)動(dòng)時(shí)間 8. 時(shí)鐘走動(dòng) 本篇將用python pyglet庫(kù)復(fù)刻華為手機(jī)鴻蒙系統(tǒng)鬧鐘程序的時(shí)鐘,先在上圖中抓取出時(shí)分秒針及刻度、表盤的顏色RGB值: bHour = (42, 43, 48, 255) bMinute = (70, 71, 75, 255) rSe

    2024年03月12日
    瀏覽(29)
  • FastAPI + NGINX + Gunicorn:一步一步教你部署一個(gè)高性能的Python網(wǎng)頁(yè)應(yīng)用

    FastAPI + NGINX + Gunicorn:一步一步教你部署一個(gè)高性能的Python網(wǎng)頁(yè)應(yīng)用

    部署一個(gè) FastAPI 應(yīng)用到你的服務(wù)器是一項(xiàng)復(fù)雜的任務(wù)。如果你對(duì) NGINX 、 Gunicorn 和 Uvicorn 這些技術(shù)不熟悉,可能會(huì)浪費(fèi)大量的時(shí)間。如果你是剛接觸 Python 語(yǔ)言不久或者希望利用 Python 構(gòu)建自己的Web應(yīng)用程序,本文的內(nèi)容可能會(huì)讓你第一次部署時(shí)更節(jié)省時(shí)間。 FastAPI 是用于開(kāi)發(fā)

    2024年02月05日
    瀏覽(24)
  • Android一步一步教你實(shí)現(xiàn)Emoji表情鍵盤

    Android一步一步教你實(shí)現(xiàn)Emoji表情鍵盤

    背景: 說(shuō)到聊天,就離不開(kāi)文字、表情和圖片,表情和圖片增加了聊天的趣味性,讓原本無(wú)聊的文字瞬間用表情動(dòng)了起來(lái),今天給大家?guī)?lái)的是表情鍵盤,教你一步一步實(shí)現(xiàn),先來(lái)看下效果圖: 效果圖 功能: 1、如何控制表情鍵盤與輸入法的切換 2、如何解析表情 3、如何處

    2024年02月16日
    瀏覽(17)
  • GitHub入門指南:一步一步教你使用GitHub

    GitHub入門指南:一步一步教你使用GitHub

    引言: GitHub是一個(gè)流行的代碼托管平臺(tái),它提供了強(qiáng)大的版本控制和協(xié)作功能,對(duì)于開(kāi)發(fā)者來(lái)說(shuō)是一個(gè)不可或缺的工具。本文將一步一步地教你如何使用GitHub,從注冊(cè)賬號(hào)到代碼同步,讓你能夠快速上手并充分利用這個(gè)平臺(tái)。 打開(kāi)GitHub官網(wǎng)(github.com)。 點(diǎn)擊右上角的\\\"Sign

    2024年02月15日
    瀏覽(21)
  • Midjourney:一步一步教你如何使用 AI 繪畫 MJ

    Midjourney:一步一步教你如何使用 AI 繪畫 MJ

    一步一步如何使用 Midjourney 教程:教學(xué)怎么用 MJ? 原文:如何使用 Midjourney 教程 https://bysocket.com/saas-digital-marketing-channel/ Midjourney是一款使用文字描述來(lái)生成高質(zhì)量圖像的AI繪畫工具。這篇文章主要介紹了Midjourney及其用途,并針對(duì)Midjourney的使用提供了一些指南。該工具可以幫

    2023年04月21日
    瀏覽(25)
  • 文本轉(zhuǎn)語(yǔ)音-微軟Azure-一步一步教你從注冊(cè)到使用

    文本轉(zhuǎn)語(yǔ)音-微軟Azure-一步一步教你從注冊(cè)到使用

    牙叔教程 簡(jiǎn)單易懂 他們的中文也許還行, 但是英文我試了都不滿意, 我再網(wǎng)上搜到的我認(rèn)為最好的是 但是丫真貴 Best Free Text To Speech Voice Reader | Speechify 現(xiàn)在的匯率是 139 × 6.91 = 960.49 一年一千塊, 好像還行哈, 但是沒(méi)卡呀, 擦, 比來(lái)比去, 還是微軟Azure性價(jià)比最高, 沒(méi)有微軟Azure的

    2024年02月07日
    瀏覽(27)
  • 一步一步教你如何使用 Visual Studio Code 編譯一段 C# 代碼

    一步一步教你如何使用 Visual Studio Code 編譯一段 C# 代碼

    以下是一步一步教你如何使用 Visual Studio Code 編寫使用 C# 語(yǔ)言輸出當(dāng)前日期和時(shí)間的代碼: 1、下載并安裝 .NET SDK。您可以從 Microsoft 官網(wǎng)下載并安裝它。 2、打開(kāi) Visual Studio Code,并安裝 C# 擴(kuò)展。您可以在 Visual Studio Code 中通過(guò)擴(kuò)展菜單安裝它。 3、打開(kāi) Visual Studio Code 中的文

    2024年02月11日
    瀏覽(33)
  • 【沐風(fēng)老師】一步一步教你在3dMax中進(jìn)行UVW貼圖和展開(kāi)UVW的方法

    【沐風(fēng)老師】一步一步教你在3dMax中進(jìn)行UVW貼圖和展開(kāi)UVW的方法

    將簡(jiǎn)單或程序材質(zhì)應(yīng)用于對(duì)象并不難。但是當(dāng)表面需要在其上顯示某種紋理時(shí),它會(huì)變得更加復(fù)雜。任何紋理貼圖都放在材質(zhì)的 Diffuse 插槽中,但渲染的結(jié)果可能無(wú)法預(yù)測(cè)。這就是為什么我們需要了解 3DMAX 如何將紋理應(yīng)用于 3D 對(duì)象,什么是 UVW 貼圖,以及為什么要“展開(kāi)”它

    2024年02月04日
    瀏覽(23)
  • 一步一步教你如何白嫖谷歌云Google Cloud服務(wù)器$300美金羊毛

    一步一步教你如何白嫖谷歌云Google Cloud服務(wù)器$300美金羊毛

    我們都知道,Depay(現(xiàn)在改名為Dupay了)卡平??梢杂糜谖⑿牛Ц秾?,美團(tuán)消費(fèi),直接用USDT做日常小額消費(fèi),還免收手續(xù)費(fèi),小額的話,這點(diǎn)還是很舒服的。 但其實(shí),Depay卡的用途遠(yuǎn)不止此,平??梢远嗤诰蛲诰?。今天教大家如何用Depay卡白嫖谷歌云服務(wù)器。申請(qǐng)成功后隨即可

    2024年02月04日
    瀏覽(33)

覺(jué)得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請(qǐng)作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包