maze_one = [
[1, 3, 1, 1, 1],
[1, 0, 0, 0, 1],
[1, 0, 0, 0, 1],
[1, 0, 0, 0, 1],
[1, 1, 1, 2, 1],
]
0은 통로, 1은 벽, 2는 플레이어, 3은 도착지
요약하면, 2(플레이어)를 3(도착지)이 있는 곳까지 옮기면 미로탈출 성공!
def print_maze(maze):
for row in maze:
print(row)
print_maze(maze_one)
# 플레이어 위치
def get_player_loc(maze):
for i in range(len(maze)):
for j in range(len(maze[i])):
if maze[i][j] == 2:
return (i,j)
player_loc = get_player_loc(maze_one)
print("player_loc", player_loc)
# 도착지 위치
def get_goal_loc(maze):
for i in range(len(maze)):
for j in range(len(maze[i])):
if maze[i][j] == 3:
return (i,j)
goal_loc = get_goal_loc(maze_one)
print("goal_loc", goal_loc)
directions = {"up": (-1, 0), "down": (1, 0), "right": (0, 1), "left": (0, -1)}
def get_movable_directions(maze, player_loc):
# 이동 가능한 방향 리스트
movable_directions = []
# player의 y, x 값 가져오기
player_y, player_x = player_loc
# 움직일 방향과 움직일 좌표 가져오기
# move의 y, x 값 가져오기
for direction, (move_y, move_x) in directions.items():
# new_player 위치 생성(계산)
new_y = player_y + move_y
new_x = player_x + move_x
# 미로의 범위를 벗어나는 경우
if (new_y < 0) or (new_y > len(maze)-1):
continue
if (new_x < 0) or (new_x > len(maze[0])-1):
continue
# 벽으로 막혀서 진행할 수 없는 경우
if maze[new_y][new_x] == 1:
continue
movable_directions.append(direction)
return movable_directions
# 현재 플레이어(2) 위치 확인
player_loc = get_player_loc(maze_two)
print("player_loc", player_loc)
# 현재 위치에서 이동 가능한 방향 확인
movable_directions = get_movable_directions(maze_two, player_loc)
print("movable directions", movable_directions)
def move_player(maze, player_loc, direction):
player_y, player_x = player_loc
move_y, move_x = directions[direction]
new_y = player_y + move_y
new_x = player_x + move_x
# 원래 위치 2->0
# 새로운 위치 0->2
maze[player_y][player_x] = 0
maze[new_y][new_x] = 2
player_loc = get_player_loc(maze_one)
direction = "left"
move_player(maze_one, player_loc, direction)
# 움직인 위치 확인
print_maze(maze_one)
'up' 2번, 'left' 1번 한 후 결과
def escape_game(maze):
# 도착지 위치
goal_loc = get_goal_loc(maze)
while True:
# 미로의 현재 상태
print_maze(maze)
# 플레이어 현재 위치
player_loc = get_player_loc(maze_one)
if player_loc == goal_loc:
print("미로 탈출 성공!")
break
# 플레이어가 이동 가능한 방향
movable_directions = get_movable_directions(maze, player_loc)
print(movable_directions)
# 이동하고자 하는 방향 입력받기
move_direction = input("어느 방향으로 진행하시겠습니까? ")
while True:
# 입력받은 move_direction이 movable_directions 안에 있으면
if move_direction in movable_directions:
# 이동!
move_player(maze, player_loc, move_direction)
break
# 입력받은 move_direction이 movable_directions 안에 없다면
else:
print("진행 방향을 다시 한 번 입력해주세요.")
move_direction = input("어느 방향으로 진행하시겠습니까? ")
escape_game(maze_one)