4. 将小拼图位置随机打乱
- 建立swap_Square(i,j)坐标互换函数
将Gird[i]和Gird[j] 中的小拼图信息进行互换
def swap_Square(i,j): # 两个拼图的位置互换
temp_pos=Gird[i].pos
Gird[i].pos=Gird[j].pos
Gird[j].pos=temp_pos
- 导入随机数模块
import random
- 随机抽取10组小拼图将其坐标进行互换
for k in range(10): # 随机抽取10组拼图 进行位置互换
i=random.randint(0,23)
j=random.randint(0,23)
swap_Square(i, j)
执行效果如下图所示:
5. 实现拼图交换:
- 设定变量click_time来储存鼠标点击次数,clickID_1、clickID_2分别来储存两个要互换的小拼图的索引。
click_time=0
clickID_1=clickID_2=-1
- 监听鼠标点击事件,遍历所有小拼图,获取被点击小拼图的索引。
def on_mouse_down(pos,button): # 当鼠标被点击时
global click_time ,clickID_1 , clickID_2
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
click_time += 1
完整代码如下:
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
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
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
def draw():
screen.clear()
for Square in Gird:
Square.draw()
def update():
pass
pgzrun.go()
pgzrun拼图游戏素材包下载