gpt4 book ai didi

python - 理解 Python 推箱子代码的问题

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:07:58 25 4
gpt4 key购买 nike

我正在尝试用 Python 构建一个推箱子拼图应用程序。

(规则说明: http://en.m.wikipedia.org/wiki/Sokoban )

我成功地实现了这个游戏,但我认为如果计算机能够计算出解决特定难题的最佳解决方案会更好。

当我在寻找引用资料时,我遇到了这个 Python implementation on Rosetta Code :

from array import array
from collections import deque
import psyco

data = []
nrows = 0
px = py = 0
sdata = ""
ddata = ""

def init(board):
global data, nrows, sdata, ddata, px, py
data = filter(None, board.splitlines())
nrows = max(len(r) for r in data)

maps = {' ':' ', '.': '.', '@':' ', '#':'#', '$':' '}
mapd = {' ':' ', '.': ' ', '@':'@', '#':' ', '$':'*'}

for r, row in enumerate(data):
for c, ch in enumerate(row):
sdata += maps[ch]
ddata += mapd[ch]
if ch == '@':
px = c
py = r

def push(x, y, dx, dy, data):
if sdata[(y+2*dy) * nrows + x+2*dx] == '#' or \
data[(y+2*dy) * nrows + x+2*dx] != ' ':
return None

data2 = array("c", data)
data2[y * nrows + x] = ' '
data2[(y+dy) * nrows + x+dx] = '@'
data2[(y+2*dy) * nrows + x+2*dx] = '*'
return data2.tostring()

def is_solved(data):
for i in xrange(len(data)):
if (sdata[i] == '.') != (data[i] == '*'):
return False
return True

def solve():
open = deque([(ddata, "", px, py)])
visited = set([ddata])
dirs = ((0, -1, 'u', 'U'), ( 1, 0, 'r', 'R'),
(0, 1, 'd', 'D'), (-1, 0, 'l', 'L'))

lnrows = nrows
while open:
cur, csol, x, y = open.popleft()

for di in dirs:
temp = cur
dx, dy = di[0], di[1]

if temp[(y+dy) * lnrows + x+dx] == '*':
temp = push(x, y, dx, dy, temp)
if temp and temp not in visited:
if is_solved(temp):
return csol + di[3]
open.append((temp, csol + di[3], x+dx, y+dy))
visited.add(temp)
else:
if sdata[(y+dy) * lnrows + x+dx] == '#' or \
temp[(y+dy) * lnrows + x+dx] != ' ':
continue

data2 = array("c", temp)
data2[y * lnrows + x] = ' '
data2[(y+dy) * lnrows + x+dx] = '@'
temp = data2.tostring()

if temp not in visited:
if is_solved(temp):
return csol + di[2]
open.append((temp, csol + di[2], x+dx, y+dy))
visited.add(temp)

return "No solution"


level = """\
#######
# #
# #
#. # #
#. $$ #
#.$$ #
#.# @#
#######"""

psyco.full()
init(level)
print level, "\n\n", solve()

它基本上是读取一个表示谜题的文本字符串,然后使用 BFS 解决它。

然而,我难以理解的一件事是 sdataddata 分别代表什么。看起来 sdataddata 映射不同的字符,但我不明白为什么。

有什么想法吗?

谢谢:)

最佳答案

如果您查看数据映射到的内容:

. = end point
@ = the guy
# = wall
$ = diamond
maps = {' ':' ', '.': '.', '@':' ', '#':'#', '$':' '}
mapd = {' ':' ', '.': ' ', '@':'@', '#':' ', '$':'*'}

ssata 似乎是终点和墙壁的 map 。

ddata 似乎是玩家和方 block 的 map 。

关于python - 理解 Python 推箱子代码的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19251591/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com