Python Code
Output
Goal
Guide the blue triangle from the start (top left) to the green goal square (bottom right) without walking into walls using Python code.
Controls
The Python Code pane contains an area to write code for solving the maze. To move the triangle to the end goal, you must write code in Python utilising the following functions:
at_goal() – Returns True if
the triangle is on the green goal square, else returns
False.
move() – Moves the triangle one square
forward. Throws a RuntimeError if there is
a wall.
turn_left() – Turns the triangle 90 degrees
left.
turn_right() – Turns the triangle 90
degrees right.
path_ahead() – Returns True if
the cell in front of the triangle can be moved to, else
returns False.
path_behind() – Returns True
if the cell behind the triangle can be moved to, else
returns False.
path_left() – Returns True if
the cell to the left of the triangle can be moved to,
else returns False.
path_right() – Returns True if
the cell to the right of the triangle can be moved to,
else returns False.
To complete the maze, you can use variables, loops, conditional statements, and functions among other Python language features.
The Output pane will contain any
print statement or errors thrown when you run
your code.
Loops
Both for and while loops can be
used:
steps = 0
while path_ahead():
move()
steps += 1
print(f"I moved {steps} steps")
A while loop to run until you reach the end is
likely a core component of any implementation
Conditions
Standard conditional statements in if, elif
and else are available and crucial in
navigating the maze:
if path_ahead():
move()
elif path_right():
turn_right()
else:
turn_left()
New Functions
Both more complex solutions, you can create your own functions:
def go_forward_until_wall():
while path_ahead():
move()
go_forward_until_wall()
Common Mistakes
:) - "SyntaxError:
expected ':'" certain lines of code such as
conditionals (if, elif and
else and loops (while and
for ) must end in a :
character.
"IndentationError" Code
after conditionals, loops and function declarations must
be evenly indented using spaces or tabs. Use the same
amount of spaces for all indentation (by default 4
spaces).
"StepLimitError: Program
stopped" When using loops, make sure there is a
way to exit, or it will run forever! This may also
happen if your program cannot find the goal. We
automatically stop the program for this exercise in both
cases.
RuntimeError: Wall
ahead If you attempt to move into a wall the
program will stop. Try using a function to check if
there is something where you want to move first.
Beginner guide
This activity is about giving the triangle instructions using Python code to move it through the maze.
Your program runs from top to bottom. If it tries to walk into a wall, it stops and shows an error in the Output box.
In Python, spaces matter. Lines inside an
if or while must be indented
(usually 4 spaces). The Tab key on the right of the keyboard
can be used to enter 4 spaces in the code box.
Step 1: Your first commands
Try these one at a time and press Run program:
move()
turn_right()
move()
move()
turn_left()
move()
What happens for each of them? What happens if you do not remove the previous code before adding the next?
Step 2: Checking for a wall (if statements)
Before moving, you can ask “is there space ahead?”. These
functions return True or False.
if path_ahead():
move()
else:
turn_right()
Try adding turn_right() and/or turn_left()
before and see what happens how does this change the
triangles movement from before?
Step 3: Repeating actions (while loops)
A loop repeats code. while loops continue until
a condition is met. This one keeps moving until a wall is
directly ahead:
while path_ahead():
move()
In this case, the goal is to reach the green square, so we
will want to add a condition somewhere using an if or loop
to end any loops when at_goal() becomes True.
Step 4: Build a simple maze solver
We are going to build a small solver that follows these rules:
The key idea is: we keep repeating these rules until we reach the goal.
Step 4a: Create a main loop
Start with a loop that will keep running until the triangle reaches the green square:
while not at_goal():
move()
Try running this. You will find it runs into a wall soon, but it will keep moving until then.
Step 4b: Add a step counter (optional)
Next let’s count how many actions we take. This is useful for tracking progress. To do this we will create a variable called "steps" and set it to 0. Add this to your current code, including your line to move the triangle. It should look somthing like this:
steps = 0
while not at_goal():
steps = steps + 1
print("Step", steps)
Try running your program with these additions. If we are making progress and still moving you should see a few steps printed before we run into a wall. If you see many print-outs and the tab freezes for a few seconds, you may be in an infinite loop. Try adding some movement code to your program.
Step 4c: Rule 1 — move forward when possible
Now we add the first rule: if there is space ahead, move forward.
while not at_goal():
if path_ahead():
move()
The triangle should move forward until it hits a wall, then it will get stuck because we haven’t told it what to do when forward is blocked.
Remember: indentation matters in Python! The
move() line must be indented under the
if. This can also be used to move your print
statement outside the loop if you find the multiple print
outs annoying and just want the final count at the end.
Step 4d: Rule 2 — if forward is blocked, try right
Extend the if with an elif (“else
if”, another condition to check if the first is
False) We want to use the
path_right() function to check if we can turn
and turn_right() to orient our triangle.
while not at_goal():
if path_ahead():
move()
elif path_right():
turn_right()
move()
We should get further now, as the triangle can turn right when it hits a wall.
Step 4e: Rule 3 — if right is blocked, try left
Now do the same, but with functions to move left.
while not at_goal():
if path_ahead():
move()
elif path_right():
turn_right()
move()
elif path_left():
turn_left()
move()
If your program runs correctly, you should notice that this is enough to reach the end of this maze and reach the goal! Good job!
Step 4f: Rule 4 — dead ends (turn around)
What if forward, left, and right are all blocked in a
different maze? That means we are in a dead end.
We can turn around by turning right twice. Add an
else block to handle this case, which runs of
none of the other conditionals are true.
while not at_goal():
if path_ahead():
move()
elif path_right():
turn_right()
move()
elif path_left():
turn_left()
move()
else:
turn_right()
turn_right()
If you want to do extra, try changing the solver and see how this changes the code, maze animation and output
path_left() and path_right()
blocks.
def
turn_around(): and call it instead of repeating
two right turns.