Commands
move();
|
|
turnLeft();
|
turnRight();
|
|
turnAround();
|
putBall();
|
|
takeBall();
|
randomChance();
|
|
colorIs(color);
|
// Paints a square red.
paint(Color.red);
Colors:
Color.red
Color.blue
Color.green
Color.yellow
Color.cyan
Color.orange
Color.white
Color.black
Color.gray
Color.purple
// Special Random color function
Color.random()
// Determine if a square is a certain color
if(colorIs(Color.red))
{
move();
}
Random
// Returns true 50% of the time
randomChance()
// Returns true probability percentage of the time
randomChance(probability)
// Returns true 20% of the time.
randomChance(0.2)
// Example
if(randomChance(0.8))
{
putBall();
}
Writing a method is like teaching karel a new word.
Naming Methods: You can name your methods whatever you want, but
you can't have spaces in the method name.
Remember that each open bracket { must match with a close bracket }
private void turnRight()
{
turnLeft();
turnLeft();
turnLeft();
}
private void turnAround()
{
turnLeft();
turnLeft();
}
private void yourMethodName()
{
// Code that will run when you make a call to
// this method.
}
Remember that each open bracket
{ must match with a close bracket
}
if (condition)
{
// code that will run if the condition is true
}
if (condition)
{
//code that will run if the condition is true
}
else
{
//code that will run if condition is not true
}
Example of if statements
if(frontIsClear())
{
move();
}
if(ballsPresent())
{
takeBall();
}
else
{
move();
}
Don't forget the
()
at the end
frontIsClear()
leftIsClear()
rightIsClear()
facingNorth()
facingSouth()
facingEast()
facingWest()
ballsPresent()
|
|
frontIsBlocked()
leftIsBlocked()
rightIsBlocked()
notFacingNorth()
notFacingSouth()
notFacingEast()
notFacingWest()
noBallsPresent()
|
Remember that each open bracket
{ must match with a close bracket
}
while (CONDITION)
{
// Code that will run while the CONDITION is true.
// Once the CONDITION is no longer true,
// it will stop.
}
Example of while loops
/* This moves Karel to a wall */
while(frontIsClear())
{
move();
}
for (int i=0; i < COUNT; i++)
{
// Code that will run 'COUNT' times
}
Example of for loops
/* This puts down 10 balls */
for(int i = 0; i < 10; i++)
{
putBall();
}
You can have multiple statements or function calls in a for loop.
/* This puts down five balls and
moves after each one */
for(int i = 0; i < 5; i++)
{
putBall();
move();
}
Use for-loops when you want to repeat something a fixed number of times.
Use while-loops when you want to repeat something as long as a condition is true.