滑动拼图是一种常见的游戏,本教程将通过 Python 标准模块来实现无类的滑动拼图游戏。
在开始之前,需要导入以下 Python 标准模块:
import random
from copy import deepcopy
接下来,定义行和列的数量以及横向和纵向的偏移量:
ROWS = 4
COLS = 4
DX = [0, 0, 1, -1]
DY = [1, -1, 0, 0]
定义初始和结束状态:
INIT_STATE = [[1,2,3,4],
[5,6,7,8],
[9,10,11,12],
[13,14,15,0]]
GOAL_STATE = [[0,1,2,3],
[4,5,6,7],
[8,9,10,11],
[12,13,14,15]]
接着,定义移动函数:
def move(state, x, y, nx, ny):
new_state = deepcopy(state)
new_state[x][y], new_state[nx][ny] = new_state[nx][ny], new_state[x][y]
return new_state
然后,定义启发函数:
def heuristic(state):
res = 0
for i in range(ROWS):
for j in range(COLS):
if state[i][j] == 0:
continue
x, y = (state[i][j]-1) // COLS, (state[i][j]-1) % COLS
res += abs(x-i) + abs(y-j)
return res
接下来,定义主函数:
def main():
state = INIT_STATE
steps = []
steps.append(state)
while state != GOAL_STATE:
candidates = []
x, y = 0, 0
for i in range(ROWS):
for j in range(COLS):
if state[i][j] == 0:
x, y = i, j
break
if state[i][j] == 0:
break
for i in range(4):
nx, ny = x+DX[i], y+DY[i]
if 0 <= nx < ROWS and 0 <= ny < COLS:
new_state =