所以我的代码是
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();
}
}
这让Karel the Dog在frontIsBlocked向上移动时放了一个球。当前面被清除时,他向上移动并重复yesWall功能。但是我最后在他放球的时候遇到了麻烦,然后他就开始了。我不希望他这样做。我希望他转身离开。我已经放置了一个GIF来展示正在发生的事情。
我现在不知道该怎么做。我知道使用frontIsBlocked条件并不是一个好主意,但这是我能想到的最好的。
答案 0 :(得分:0)
在Karel撞墙的地方,发表了一个if声明。
function yesWall() {
while (frontIsBlocked()) {
putBall();
turnLeft();
if(frontIsBlocked()){
break;
}
move();
turnRight();
}
}
答案 1 :(得分:0)
如果你走到墙上,然后向左转,然后直行,放球......这可能会有所帮助:
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.
}
}
希望这有帮助!
答案 2 :(得分:0)
function start(){
while(frontIsClear()){
move();
}
turnLeft();
while(frontIsClear()){
if(rightIsBlocked()){
putBall();
move();
while(rightIsClear()){
move();
}
}
if(frontIsBlocked()){
putBall();
}
}
}
答案 3 :(得分:0)
您可以尝试以下操作:
function start(){
while(frontIsClear()) {
move();
}
turnLeft();
while(frontIsClear()){
if(rightIsBlocked()){
putBall();
move();
}else{
move();
}
}
putBall();
}