03/21 17:53

3.程序设计步骤

Python处理图片切割

1．定义常量及加载图片

2．图像块（拼块）类

3。初始化游戏

random.shuffle(board)只能按行打乱二维列表，所以使用一维列表来实现打乱图像块的功能，再根据编号生成对应的图像块（拼块）到board列表中。

4。绘制游戏界面的各个元素

5。鼠标事件

6．判断输赢

7．重置游戏

8．“重新开始”按钮的单击事件

4.代码参考

``````from tkinter import *
from tkinter.messagebox import *
import random

root=Tk('拼图游戏')
root.title("拼图")

Pics=[]
for i in range(9):
filename="girl"+str(i)+'.png'
Pics.append(PhotoImage(file=filename))

WIDTH=575
HEIGHT=575

IMAGE_WIDTH=WIDTH//3
IMAGE_HEIGHT=HEIGHT//3

ROWS=3
COLS=3

steps=0

board=[[0,1,2],[3,4,5],[6,7,8]]

class Square:
def __init__(self,orderID):
self.orderID=orderID
def draw(self,canvas,board_pos):
img=Pics[self.orderID]
canvas.create_image(board_pos,image=img)

def init_board():
L=list(range(8))
L.append(None)
random.shuffle(L)
for i in range(ROWS):
for j in range(COLS):
idx=i*ROWS+j
orderID=L[idx]
if orderID is None:
board[i][j]=None
else:
board[i][j]=Square(orderID)

def play_game():
global steps
steps=0
init_board()

def drawBoard(canvas):
canvas.create_polygon((0,0,WIDTH,0,WIDTH,HEIGHT,0,HEIGHT),width=1,outline='Black',fill='green')
for i in range(ROWS):
for j in range(COLS):
if board[i][j] is not None:
board[i][j].draw(canvas,(IMAGE_WIDTH*(j+0.5),IMAGE_HEIGHT*(i+0.5)))

def mouseclick(pos):
global steps
r=int(pos.y//IMAGE_HEIGHT)
c=int(pos.x//IMAGE_WIDTH)
print(r,c)
if r<3 and c<3:
if board[r][c] is None:
return
else:
current_square=board[r][c]
if r-1>=0 and board[r-1][c] is None:
board[r][c]=None
board[r-1][c]=current_square
steps+=1
elif c+1<=2 and board[r][c+1] is None:
board[r][c]=None
board[r][c+1]=current_square
steps+=1
elif r+1<=2 and board[r+1][c] is None:
board[r][c]=None
board[r+1][c]=current_square
steps+=1
elif c-1>=0 and board[r][c-1] is None:
board[r][c]=None
board[r][c-1]=current_square
steps+=1
Label1["text"]=str(steps)
cv.delete('all')
drawBoard(cv)
if win():
showinfo(title="恭喜",message="你成功了！")

def win():
for i in range(ROWS):
for j in range(COLS):
if board[i][j] is not None and board[i][j].orderID!=i*ROWS+j:
return False
return True

def callBack2():
print("重新开始")
play_game()
cv.delete('all')
drawBoard(cv)

cv=Canvas(root,bg='white',width=WIDTH,height=HEIGHT)
b1=Button(root,text="重新开始",command=callBack2,width=20)
Label1=Label(root,text="0",fg='red',width=20)
Label1.pack()
cv.bind('<Button-1>',mouseclick)

cv.pack()
b1.pack()
play_game()
drawBoard(cv)
root.mainloop()
``````

0
0 收藏

0 评论
0 收藏
0