6. 检查拼图完成
- 初始化标记成功的变量Is_Win
Is_Win=False
- 当鼠标点击小拼图时,判断所有小拼图是否都在正确的位置,并更新Is_Win。
def on_mouse_down(pos,button): # 当鼠标被点击时# 略is_win = Truefor 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 = Falsebreakif 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 randomTITLE="pgzrun 拼图游戏"
Square_size=125
WIDTH=Square_size*4
HEIGHT=Square_size*6click_time=0
clickID_1=clickID_2=-1
Is_Win=FalseSquares=[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*jSquare.top=Square_size*iGird.append(Square)def swap_Square(i,j): # 两个拼图的位置互换temp_pos=Gird[i].posGird[i].pos=Gird[j].posGird[j].pos=temp_posfor 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_Winfor i in range(24):if Gird[i].collidepoint(pos): # 拼图对象被点击breakif click_time%2==0 :clickID_1=ielse:clickID_2=iswap_Square(clickID_1,clickID_2)click_time += 1# 成功判断is_win = Truefor 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 = Falsebreakif is_win:Is_Win=Truedef 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():passpgzrun.go()
pgzrun拼图游戏素材包下载