Pages

Tuesday, May 24, 2011

Solution to the checkerboard problem

/ * When you finish writing it, the CheckerboardKarel class
*should draw a checkerboard using beepers.
*You should make sure that your program works for all of the
* sample worlds supplied in the starter folder.
*/

import stanford.karel.*;

public class CheckerboardKarel extends SuperKarel
{
int j=1;
public void run()
{
putBeeper();
turnLeft();
movement();
while(j==1)
{
if(facingNorth())
{
if(rightIsClear())
{
sidewayright();
movement();
}
if(leftIsBlocked())
j=0;
}
if(facingSouth())
{
if(leftIsClear())
{
sidewayleft();
movement();
}
if(rightIsBlocked())
j=0;
}
}
}
private void movement()
{
while(frontIsClear())
{
move();
if(frontIsClear())
{
move();
putBeeper();
}
}
}
private void sidewayright()
{
turnRight();
if(beepersPresent())
{
move();
turnRight();
if(frontIsClear())
{
move();
putBeeper();
}
}
else
{ move();
putBeeper();
turnRight();
}
}
private void sidewayleft()
{
turnLeft();
if(beepersPresent())
{
move();
turnLeft();
if(frontIsClear())
{
move();
putBeeper();
}
}
else
{
move();
putBeeper();
turnLeft();
}
}
}

No comments:

Post a Comment