Start Here

Media Resources

File Conversion

Conditions

All the following exercises are intended to be implemented in the Greenfoot scenario "turtle-v7". Download the scenario here and open it in Greenfoot before continuing.

Conditions

This video shows you how to make the turtle take a turn when it hits the edge of the world.

Methods with boolean return types

An int value can be any number. A boolean value can be either true or false.

Methods with boolean return type tell us when a certain condition is true or false. For example,

isAtEdge()

is true if the turtle is at the edge of the world, or false if it's not.

We have seen that we can store the result of a call to getX() in an int variable:

int x = this.getX();	    // Store the x location of the turtle in a local variable called x.
this.forward(x);			// Move the turtle forward x pixels.

We can also use the call to getX() directly:

this.forward(this.getX());			// Move the turtle forward x pixels, where x is the x location of the turtle.
this.setColor(this.getX(), this.getY(), this.getRotation());   // Set rgb colors with x, y and rotation of turtle.

Try using isAtEdge() directly like this:

        if(isAtEdge()) {
            this.turn(160);
            this.forward(4);
        }

Picturing if statements

We can think of boolean expressions like isAtEdge() as tests to check for some condition. For example, isAtEdge() checks to see whether or not the turtle is at the edge of the world. The picture below captures the general idea of what an if statement is about.

The if-else statement

You might want to do one thing if your condition is true, and another thing if your condition is false. For that, use an if-else statement.

For example, try this:

    /**
     * Act - do whatever the Turtle wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act() 
    {
		int x = getX();
		boolean onLeft = x < 240;	
		
		if (onLeft) {
			this.setColor("red");
		}
		else {
			this.setColor("blue");
		}
        this.poly(this.side, 95);
        this.side += 5;
    }    

The expression x < 240 has a value of true if x is less than 240. If x is equal to or greater than 240, the value of the expression is false.

Did the turtle what you expected? What do you think is happening?