🐶

Teaching Karel to Turn Right

Apr 13, 2025

Lecture Notes: Teaching Karel to Turn Right

Introduction

  • Problem Identified: Karel, the robot dog, cannot execute the command to turn right.
  • Example Scenario: In the "Build a Tower" program, Karel needs to place a stack of three tennis balls and face east on top of the tower.
    • Users may attempt to use turnRight(); as a command, but it results in an error as Karel only understands the turnLeft command.

Solution: Using Functions

  • Concept of Functions:
    • Functions allow us to teach Karel new commands.
    • A function defines a new behavior or command that Karel can understand and execute.

Creating a turnRight Function

  • Function Definition:
    • Use the keyword function followed by the name of the function, turnRight.
    • Syntax: function turnRight() { // function body }
  • Function Body:
    • Contains the instructions to execute the desired command.
    • For turnRight, the body consists of turning left three times: turnLeft(); turnLeft(); turnLeft();

Implementation Steps

  1. Write the turnRight Function:
    • Define the function in the code with the correct syntax.
    • Place the commands to turn left three times inside the function.
  2. Using turnRight in the Code:
    • After defining the function, it can be called using turnRight(); wherever needed in the code.

Conclusion

  • Testing the Function:
    • After defining turnRight, reset and run the program.
    • Verify that Karel executes the turn right command correctly, solving the initial problem.