我有这个任务,我必须打印一个也提供用户位置的迷宫。但是,此位置可能取决于另一个函数生成的位置。我的意思是该职位可以有许多不同的可能性。
我尝试使用.replace方法的组合切片,以便能够将字符更改为用户的位置,标记为“A”。
请参阅下面的代码,我在这里做错了吗?
def print_maze(maze, position):
"""
Returns maze string from text file and position of the player
print_maze(str, int) -> object
"""
p1 = position[0]
p2 = position[1]
position = position_to_index((p1,p2), len(maze))
for line in maze:
maze = maze[:position].replace(' ', 'A') + maze[position:]
for line in maze:
maze.strip().split('\n')
print(maze)
到目前为止,我得到的结果是:
>>> maze = load_maze('maze1.txt')
>>> print_maze(maze, (1,1))
#####
#AAZ#
#A###
#AAP#
#####
答案 0 :(得分:0)
您似乎正在努力使其变得更加困难。而不是将迷宫加载为一个字符串,将其读入数组。在load_maze中执行.strip()
,而不是每次调用print-maze()
:
def load_maze(filename):
"""
Returns maze string from text file
load_maze(str) -> list
"""
maze = []
with open(filename) as file:
for line in file:
maze.append(line.strip())
return maze
def print_maze(maze, position):
"""
Prints maze with position of the player
print_maze(str, (int, int)) -> None
"""
(x, y) = position
for row, line in enumerate(maze):
if row == y:
print(line[:x] + 'A' + line[x + 1:])
else:
print(line)
maze = load_maze('maze1.txt')
print_maze(maze, (1, 1))