Example - A Stony Corridor
[1]:
import roboworld as rw
[2]:
length = 25
nstones = 4
world = rw.corridor(length=length, random_headway=True, nstones=nstones)
robo = world.robo
Look at the following world
where your robo
is at the far left and is oriented randomly, i.e., either to the north, west, south, or east. Our goal is to move robo
to its purple goal.
[3]:
world.show()
[3]:
Exercise 1. Define and implement the following two functions:
turn_east(robo)
: turnsrobo
towards east.turn_west(robo)
: turnsrobo
towards west.
Hint: Avoid duplicated code!
[4]:
def turn(robo):
robo.turn_left()
robo.turn_left()
def turn_north(robo):
while not robo.is_facing_north():
robo.turn_left()
def turn_west(robo):
turn_north(robo)
robo.turn_left()
def turn_east(robo):
turn_west(robo)
turn(robo)
Exercise 2. Define and implement displace_stone(robo)
that will take a stone in front of robo
and puts it behind robo
. displace_stone(robo)
should not change the state of robo
.
[5]:
def displace_stone(robo):
robo.take_stone_in_front()
turn(robo)
robo.put_stone_in_front()
turn(robo)
Exercise 3. Use the implemented functions to traverse the stony corridor. Assume that you neither know the length of the corridor nor the positions of the stones.
Hint: Avoid duplicated code.
[6]:
turn_east(robo)
while not robo.is_at_goal():
if not robo.is_stone_in_front():
robo.move()
else:
displace_stone(robo)
turn E -> N
turn N -> W
turn W -> S
turn S -> E
move (0, 0) -> (0, 1)
move (0, 1) -> (0, 2)
move (0, 2) -> (0, 3)
move (0, 3) -> (0, 4)
take stone at (0, 5)
turn E -> N
turn N -> W
put stone at (0, 3)
turn W -> S
turn S -> E
move (0, 4) -> (0, 5)
move (0, 5) -> (0, 6)
move (0, 6) -> (0, 7)
move (0, 7) -> (0, 8)
move (0, 8) -> (0, 9)
take stone at (0, 10)
turn E -> N
turn N -> W
put stone at (0, 8)
turn W -> S
turn S -> E
move (0, 9) -> (0, 10)
move (0, 10) -> (0, 11)
move (0, 11) -> (0, 12)
move (0, 12) -> (0, 13)
move (0, 13) -> (0, 14)
move (0, 14) -> (0, 15)
move (0, 15) -> (0, 16)
move (0, 16) -> (0, 17)
move (0, 17) -> (0, 18)
take stone at (0, 19)
turn E -> N
turn N -> W
put stone at (0, 17)
turn W -> S
turn S -> E
move (0, 18) -> (0, 19)
move (0, 19) -> (0, 20)
take stone at (0, 21)
turn E -> N
turn N -> W
put stone at (0, 19)
turn W -> S
turn S -> E
move (0, 20) -> (0, 21)
move (0, 21) -> (0, 22)
move (0, 22) -> (0, 23)
move (0, 23) -> (0, 24)
Exercise 4. Animate your solutiion.
[7]:
rw.animate(world)