Our First Robot: BumperBot

The first robot you'll learn to program is very simple. All it can do is move forward, turn left, turn right, and sense whether it can move forward or not by bumping into something.

You can try to execute these commands on the BumperBot to the right. Press each button to issue these commands to the robot.

[ [ [2, 2, 2, 1, 2], [2, 1, 2, 1, 2], [2, 1, 2, 2, 2], ] ]

Making the BumperBot Move

Now that you've controlled the BumperBot manually, let's write a generator function that can control it for us.

A generator function in JavaScript is something that produces items in a sequence. To make it produce items in a sequence, we use the yield keyword. In our case, we want to yield an action every time we want the robot to move.

To perform an action, just yield its name. The Robot will perform it, provided that the its hardware supports that action.

For now, let's try to control a BumperBot. Here are a few example lines of code for how to perform actions for the robot:

  • yield this.moveForward — Yield a move forward (if possible)
  • yield this.turnRight — Yield a 90 degree turn to the right
  • yield this.turnLeft — Yield a 90 degree turn to the left

If you boil it down, a robot is actually just a brain that thinks for a while and eventually produces the next action to take. Our Robot is going to be controlled by a generator function that will do some thinking, then yield an action, repeatedly.

Example BumperBot Implementation

Simple BumperBot Implementation

This example BumperBot senses whether the path in front is obstructed or not, then moves forward if it isn't. It does this until it runs into an obstacle, and then it starts spinning around in place forever.

Later on in this page, we'll see how to do more advanced things, like creating multiple functions and generator functions, and using your browser's JavaScript debugger to step through our Robot's behavior one line at a time.

Use the example BumperBot implementation above to complete the following challenge. A good place to start is to copy-paste the example code.

Challenge: Go around the map and reach the green target.
[ [ [4, 2, 2, 2, 2, 2, 2], [1, 1, 1, 1, 1, 1, 2], [2, 2, 2, 2, 2, 1, 2], [2, 1, 1, 1, 2, 1, 2], [2, 1, 5, 2, 2, 1, 2], [2, 1, 1, 1, 1, 1, 2], [2, 2, 2, 2, 2, 2, 2] ] ]
Hint 1

You're supposed to write the logic for your Robot in the box on the left, then click the run button, and see what happens in the simulator on the right.

The very first thing you should do is copy-paste the example code from the write-up in the beginning. What does the Robot do in the simulation, and can you guess which lines of code are responsible for what you see it do?


Hint 2

The example code makes the Robot move forward three times and then turn around. Modify it to yield the actions that you need it to get to the green target.