試著做了一個中空版本的 拿去跑maze也可以 程式碼有點醜
這個技巧比較需要對function有掌握
不過方便起見有先把地圖大小跟起始位置當作常數先定義出來
再附上一個超過1000行的版本
set_max_nb_steps(2000)
travel = [[0, 0, 0, 0, 0, 1],[0, 0, 0, 0, 0, 0],[0, 0, 0, 0, 0, 1],[0, 0, 1, 0, 0, 1],[0, 0, 0, 0, 0, 1],[1, 1, 1, 1, 1, 1]]
current_x, current_y = 3, 2
# 函數
def turn_right():
turn_left()
turn_left()
turn_left()
def turn_back():
turn_left()
turn_left()
def face_north():
while not is_facing_north():
turn_left()
def index_bound_check(x, y):
if x < 0 or x > 2 or y < 0 or y > 3:
return False
def up_available(current_x, current_y):
index_bound_check(current_x - 1, current_y)
return True if travel[current_x - 1][current_y] == 0 else False
def left_available(current_x, current_y):
index_bound_check(current_x, current_y - 1)
return True if travel[current_x][current_y - 1] == 0 else False
def down_available(current_x, current_y):
index_bound_check(current_x + 1, current_y)
return True if travel[current_x + 1][current_y] == 0 else False
def right_available(current_x, current_y):
index_bound_check(current_x, current_y + 1)
return True if travel[current_x][current_y + 1] == 0 else False
def go(current_x, current_y):
if at_goal():
done()
travel[current_x][current_y] = 1
face_north()
if up_available(current_x, current_y) and front_is_clear():
move()
current_x -= 1
go(current_x, current_y)
face_north()
turn_back()
move()
current_x += 1
face_north()
turn_left()
if left_available(current_x, current_y) and front_is_clear():
move()
current_y -= 1
go(current_x, current_y)
face_north()
turn_right()
move()
current_y += 1
face_north()
turn_back()
if down_available(current_x, current_y) and front_is_clear():
move()
current_x += 1
go(current_x, current_y)
face_north()
move()
current_x -= 1
face_north()
turn_right()
if right_available(current_x, current_y) and front_is_clear():
move()
current_y += 1
go(current_x, current_y)
face_north()
turn_left()
move()
current_y -= 1
# 開始操作機器人
go(current_x, current_y)