public class MidpointKarel extends SuperKarel
{
public void run()
{
// count how many columns there are
if(frontIsClear())
{
placeBalls();
goHome();
while(frontIsClear())
{
goToStack();
}
goToStack();
// cut stack in half
divideStack();
// grab one
// move one
// put one down
// go home
// grab one
// move until empty
// put one down
takeBall();
while(ballsPresent())
{
takeBall();
move();
while(ballsPresent())
{
move();
}
putBall();
goHome();
}
move();
while(ballsPresent())
{
takeBall();
move();
}
turnAround();
move();
turnAround();
putBall();
}
else
{
putBall();
}
}
private void divideStack()
{
turnLeft();
move();
turnRight();
while(ballsPresent())
{
takeBall();
if(ballsPresent())
{
takeBall();
}
turnRight();
move();
putBall();
turnAround();
move();
turnRight();
}
turnRight();
move();
turnLeft();
}
private void placeBalls()
{
while(frontIsClear())
{
putBall();
move();
}
putBall();
}
private void goHome()
{
turnAround();
while(frontIsClear())
{
move();
}
turnAround();
}
private void goToStack()
{
if(ballsPresent())
{
takeBall();
turnAround();
while(frontIsClear())
{
move();
}
turnRight();
move();
putBall();
turnAround();
move();
turnLeft();
}
else if(frontIsClear())
{
move();
}
else if(frontIsBlocked())
{
if(ballsPresent())
{
takeBall();
goToStack();
}
}
}
}