If Statements

If statements let our programmes make decisions. We have already met them when controlling our game's direction.

if direction == 'f':
        t.forward(step)
elif direction == 'l':
        t.left(90)
        t.forward(step)
elif direction == 'r':
        t.right(90)
        t.forward(step)
elif direction == 'b':
        t.right(180)
        t.forward(step)
                

We can add as many else if (elif) statements as we want.

Sometimes though, it is useful to be able to test more than one condition at once.

For example, we can test to see if one or more of conditions are true using the or conditional operator:

if x > 3 or y < 2 or z > -1:
    DO SOMETHING

We can also test if all of a set of conditions are true by using the and conditional operator.

if x > 3 and y < 2 and z > -1:
    DO SOMETHING

To see how we might use this, we will modify our game to include a border and test to see if our turtle is outside of the border. If it is, the game is over.

Let's start by drawing a container around our game at the start.

#draw a container
t.penup()
t.goto(250,250)
t.pendown()
t.right(180)
t.forward(500)
t.right(90)
t.forward(500)
t.right(90)
t.forward(500)
t.right(90)
t.forward(500)
t.penup()

This should create a border around our game that looks like this

It is a 500 x 500 square with a centre at (0,0). So the x and y coordinates go from -250 to +250

To test whether or not we are outside of the box and should end the game, we need to know the coordinates of our turtle. To do this we can user the turtle.pos() function. This gives us a 2D vector containing the coordinates.

  • x-coordinate = t.pos()[0]

  • y-coordinate = t.pos()[1]

Lets see how we might test the coordinates of the turtle in our game from within the while loop:

x = t.pos()[0]
y = t.pos()[1]

if x > 250 or x < -250 or y > 250 or y < -250 :
    direction = 'q' 

Modify your game so that it ends when the turtle enters the box.

Last updated