6. 检查拼图完成
- 初始化标记成功的变量Is_Win
Is_Win=False
- 当鼠标点击小拼图时,判断所有小拼图是否都在正确的位置,并更新Is_Win。
def on_mouse_down(pos,button): # 当鼠标被点击时
# 略
is_win = True
for i in range(6):
for j in range(4):
Square = Squares[i * 4 + j]
if not (Square.left == Square_size * j and Square.top == Square_size * i) :
is_win = False
break
if is_win:
Is_Win=True
- 在draw()绘制函数中加入成功判断,并在窗口打印出成功信息。
def draw():
# 略
if Is_Win:
screen.draw.text("游戏胜利!",(WIDTH/2-100,HEIGHT/2-50),\
fontsize=50,fontname='s',color="blue")
执行效果如下图所示:
7. 添加游戏提示线
- 当拼图未完成时,为每一个小拼图绘制黑色边框,用以区分每一个小拼图的边界。
def draw():
# 略
for i in range(5):
screen.draw.line((i*Square_size,0),(i*Square_size,HEIGHT),"black")
for i in range(7):
screen.draw.line((0,i*Square_size),(WIDTH,i*Square_size),"black")
- 当拼图未完成时,为当下鼠标点击的小拼图绘制红色边框。
def draw():
# 略
if clickID_1!=-1:
screen.draw.rect(Rect((Gird[clickID_1].left,Gird[clickID_1].top),\
(Square_size,Square_size)),"red")
执行效果如下图所示:
完整代码如下:
import pgzrun
import random
TITLE="pgzrun 拼图游戏"
Square_size=125
WIDTH=Square_size*4
HEIGHT=Square_size*6
click_time=0
clickID_1=clickID_2=-1
Is_Win=False
Squares=[Actor("girl_01"),Actor("girl_02"),Actor("girl_03"),Actor("girl_04")
,Actor("girl_05"),Actor("girl_06"),Actor("girl_07"),Actor("girl_08")
,Actor("girl_09"),Actor("girl_10"),Actor("girl_11"),Actor("girl_12")
,Actor("girl_13"),Actor("girl_14"),Actor("girl_15"),Actor("girl_16")
,Actor("girl_17"),Actor("girl_18"),Actor("girl_19"),Actor("girl_20")
,Actor("girl_21"),Actor("girl_22"),Actor("girl_23"),Actor("girl_24")
]
Gird=[]
for i in range(6):
for j in range(4):
Square=Squares[i*4+j]
Square.left=Square_size*j
Square.top=Square_size*i
Gird.append(Square)
def swap_Square(i,j): # 两个拼图的位置互换
temp_pos=Gird[i].pos
Gird[i].pos=Gird[j].pos
Gird[j].pos=temp_pos
for k in range(10): # 随机抽取10组拼图 进行位置互换
i=random.randint(0,23)
j=random.randint(0,23)
swap_Square(i, j)
def on_mouse_down(pos,button): # 当鼠标被点击时
global click_time ,clickID_1 , clickID_2,Is_Win
for i in range(24):
if Gird[i].collidepoint(pos): # 拼图对象被点击
break
if click_time%2==0 :
clickID_1=i
else:
clickID_2=i
swap_Square(clickID_1,clickID_2)
click_time += 1
# 成功判断
is_win = True
for i in range(6):
for j in range(4):
Square = Squares[i * 4 + j]
if not (Square.left == Square_size * j and Square.top == Square_size * i) :
is_win = False
break
if is_win:
Is_Win=True
def draw():
screen.clear()
for Square in Gird:
Square.draw()
if Is_Win:
screen.draw.text("游戏胜利!",(WIDTH/2-100,HEIGHT/2-50),fontsize=50,fontname='s',color="blue")
else :
for i in range(5):
screen.draw.line((i*Square_size,0),(i*Square_size,HEIGHT),"black")
for i in range(7):
screen.draw.line((0,i*Square_size),(WIDTH,i*Square_size),"black")
if clickID_1!=-1:
screen.draw.rect(Rect((Gird[clickID_1].left,Gird[clickID_1].top),\
(Square_size,Square_size)),"red")
def update():
pass
pgzrun.go()
pgzrun拼图游戏素材包下载