I am coding with CodeHS Karel the Dog and I'm having trouble making Karel stop when frontIsBlocked

So my code is

function start(){ while(frontIsClear()) { move(); } yesWall(); noWall(); } function placeBall() { putBall(); } function yesWall() { while (frontIsBlocked()) { putBall(); turnLeft(); move(); turnRight(); } } function noWall() { while (frontIsClear()) { turnLeft(); move(); turnRight(); yesWall(); } } 

This makes Karel the Dog place a ball when the frontIsBlocked and moves up. When the front is cleared, he moves up and repeats the yesWall function. However I'm having trouble at the end where he places a ball and then he moves. Which I don't want him to do. I want him to just turnLeft. I've placed a GIF showing what is happening. enter image description here

I just don't know what to do now. I know that using the frontIsBlocked condition wasn't a good idea but that was the best I could come up with.

4 Answers

At the point where Karel's hitting the wall, put an if statement.

function yesWall() { while (frontIsBlocked()) { putBall(); turnLeft(); if(frontIsBlocked()){ break; } move(); turnRight(); } } 

It might help if you went to the wall, then turned left, and went straight, putting balls... like this:

function start() { moveToWall(); decorateFence(); } function moveToWall() { while(frontIsClear()) { move(); } } function decorateFence() { while(frontIsClear()){ //Since karel should not bump into the wall at any cost, put this while front is clear first if(rightIsBlocked()) { putBall(); move(); }else{ move(); //this way, karel is already pointing north, and if the right is blocked(if there's a fence) then a ball is put and karel moves, if there is no fence there, then karel moves anyway. } } 

Hope this helped!

function start(){ while(frontIsClear()){ move(); } turnLeft(); while(frontIsClear()){ if(rightIsBlocked()){ putBall(); move(); while(rightIsClear()){ move(); } } if(frontIsBlocked()){ putBall(); } } } 

You could try this:

function start(){ while(frontIsClear()) { move(); } turnLeft(); while(frontIsClear()){ if(rightIsBlocked()){ putBall(); move(); }else{ move(); } } putBall(); } 
1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like