2016-08-24 2 views
0

나는이 작업을 통해 사용자의 위치를 ​​제공하는 미로를 인쇄해야합니다. 그러나이 위치는 다른 기능에서 생성 된 위치에 따라 달라질 수 있습니다. 제 말은 포지션이 여러 가지 가능성을 가질 수 있다는 것입니다.2D 미로에서 사용자 위치 표시 - Python

'A'로 표기된 사용자의 위치로 문자를 변경하려면 .replace 메소드를 조합하여 슬라이싱을 사용하려고했습니다.

아래 코드를 참조하십시오. 여기서 잘못된 것이 있습니까? 내 결과를

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

당신이 어렵게 될 필요 이상으로하고있는 것처럼 보인다. 미로를 하나의 문자열로로드하는 대신 배열로 읽어들입니다. print-maze()에 대한 모든 호출이 아닌 load_maze에서 .strip() 하나를 수행하십시오.

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))