“彩色方塊連連看”游戲(續(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是通路即可:
對(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è)折角的相連。
最終實(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)行效果
目錄
“彩色方塊連連看”游戲(續(xù))
第八步
第九步
第十步
第十一步
第十二步
最終實(shí)現(xiàn)
完整代碼
運(yùn)行效果文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-844231.html
完文章來(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)!