Robots; introductory examples
Here are some short programs that demonstrate how
you can add robots to a world.
Robots have more characteristics than a block or a beeper
and must be created before they are added. You create a
robot with one instruction:
Robot ringo = new Robot();
And you add it to the world with another (assumng the world is called
space):
space.add(ringo);
This adds the robot to cell(0, 0).
The following program shows this.
Example
|
|
Ringo.java
//
// Add a robot to a world
public class Ringo
{
public static void main(String [] args)
{
World stage = new World();
Robot ringo = new Robot();
stage.add(ringo);
}
}
|
|
|
Notice that the robot is in cell(0, 0) and is facing east. (It looks like an arrow head
pointing in the direction that it is facing.)
Now that ringo's on the stage, what can he do?
Well he can move. Simply call ringo's move
method; the instruction looks like
ringo.move();
This instruction will move the robot one square forward.
Execute this instruction every time you move.
Note: This time you see a run and a step button. These
instructions let you control the rate of the robot's instructions.
When the robot has finished his instructions, the "finished" message
appears.
|
|
Dancer.java
//
// Let's dance!
public class Dancer
{
public static void main(String [] args)
{
World stage = new World();
Robot ringo = new Robot();
stage.add(ringo);
// once ringo's been added
// to the stage, he can move
ringo.move();
ringo.move();
ringo.move();
}
}
|
|
|
Of course ringo would be quite constrained if he couldn't
change direction.
Robot's can turn using the instruction
ringo.turnLeft();
which turns the robot left.
|
|
Explorer.java
public class Explorer
{
public static void main(String [] args)
{
World stage = new World();
Robot ringo = new Robot();
stage.add(ringo);
ringo.move();
ringo.move();
ringo.move();
ringo.turnLeft();
ringo.move();
ringo.move();
ringo.turnLeft();
ringo.turnLeft();
ringo.move();
}
}
|
|
|