首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我正在用狗CodeHS Karel编程,当frontIsBlocked停止时,我遇到了麻烦。

我正在用狗CodeHS Karel编程,当frontIsBlocked停止时,我遇到了麻烦。
EN

Stack Overflow用户
提问于 2016-11-25 13:07:20
回答 4查看 32.7K关注 0票数 1

所以我的代码是

代码语言:javascript
复制
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();
    }
}

这使得小狗卡雷尔在frontIsBlocked和向上移动时放置了一个球。当前面被清除时,他向上移动并重复yesWall函数。然而,我在最后遇到了麻烦,他放了一个球,然后他就移动了。我不想让他这么做。我只想让他做turnLeft。我已经放置了一个显示正在发生的事情的GIF。

我只是不知道现在该怎么办。我知道使用frontIsBlocked条件不是一个好主意,但这是我能想到的最好的办法。

EN

回答 4

Stack Overflow用户

发布于 2017-03-04 00:54:28

在Karel碰壁的地方,放一个if语句。

代码语言:javascript
复制
function yesWall() {
    while (frontIsBlocked()) {
        putBall();
        turnLeft();
        if(frontIsBlocked()){
            break;
        }
        move();
        turnRight();
    }
}
票数 0
EN

Stack Overflow用户

发布于 2017-09-27 09:36:06

如果你走到墙边,然后左转,然后直走,把球放进去,可能会有所帮助。如下所示:

代码语言:javascript
复制
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. 
    }
}

希望这能有所帮助!

票数 0
EN

Stack Overflow用户

发布于 2018-03-25 01:27:58

代码语言:javascript
复制
function start(){
    while(frontIsClear()){
        move();
    }   
    turnLeft();

    while(frontIsClear()){

        if(rightIsBlocked()){
            putBall();
            move();
            while(rightIsClear()){
                move();
            }

        }
        if(frontIsBlocked()){
            putBall();
        }
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40798070

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档