新的编码和Javascript。现在正在读斯坦福卡雷尔课程,并且在这一个上遇到了困难。
这是我的代码:
//Make Karel fill the world
//with beepers
function main() {
step1();
reset();
step2();
}
function putBeeperLine(){
putBeeper();
while(frontIsClear()) {
move();
putBeeper();
}
}
function right(){
turnRight();
move();
turnRight();
}
function left(){
turnLeft();
move();
turnLeft();
}
function step1(){
repeat(2){
putBeeperLine();
left();
putBeeperLine();
right();
}
putBeeperLine();
}
function step2() {
putBeeperLine();
left();
putBeeperLine();
right();
putBeeperLine();
}
function reset(){
left();
while(frontIsClear()){
move();}
turnAround();
}如果我运行函数step1(),代码就会执行,并且满足5x5世界的要求。但是,如果我继续并运行其余的代码,8x8就会满足,但是5x5突然不再有效。有人能解释一下这个问题吗?理想情况下,可以帮助我思考这个问题而不给我答案吗?
太感谢你们了!
发布于 2020-04-05 02:27:39
我也一直在尝试这些课程,经过多次尝试,我终于克服了上述问题,但我用'if‘语句“欺骗”了一些人,我很确定这句话还没有涵盖(我刚刚完成了单元8)。
这一点在第5课中并不十分清楚,但是在单元8第2课中,代码中的注释是“不管世界有多大”。换句话说,您的代码必须能够自动填写任何大小的(例如5x5、8x8、16x16 .)。这也是为什么有两个目标。我相信,因为您使用硬编码了的次数(例如,使用())逐行填充世界,因此程序不接受您的答案,因为它只适用于ONE特定的世界大小。
我目前正在开发一种解决方案,不涉及' if‘的使用,如果我能够让它正常工作,我将在这里分享它,但是,没有任何保证。
编辑:我仍然无法想出一个不涉及'if‘语句的解决方案,但是下面是我对这个练习的解决方案(对于那些想进入下一节的人来说)。它的工作原理:首先填充一行传呼机,然后卡雷尔会检查上面是否有障碍物(墙壁)(使用leftIsClear())。如果确实没有障碍,卡雷尔将重新定位到第一列,并填补一条线的寻呼机。如果有障碍,程序终止。下面是破坏者。
//Make Karel fill the world
//with beepers
function main() {
//your code here
putBeeperLine();
while(leftIsClear()){
checkRowAbove();
putBeeperLine();
}
}
function checkRowAbove(){
if(leftIsClear()){
turnLeft();
move();
resetPosition();
}
}
function resetPosition(){
turnLeft();
while(frontIsClear()){
move();
}
turnAround();
}
function putBeeperLine(){
putBeeper();
while(frontIsClear()) {
move();
putBeeper();
}
}
发布于 2021-12-20 07:35:37
//Make Karel fill the world
//with beepers
function main() {
//your code here
while(leftIsClear()){
putBeeperLine();
reset();
moveUp();
}
putBeeperLine();
}
function putBeeperLine(){
putBeeper();
while(frontIsClear()) {
move();
putBeeper();
}
}
function reset(){
turnLeft();
turnLeft();
while(frontIsClear()){
move();
}
turnLeft();
turnLeft();
}
function moveUp(){
turnLeft();
move();
turnRight();
}发布于 2020-04-24 20:45:23
一旦Hollow说了一些关于任何大小的代码,我终于明白了。谢谢。这是我的代码:
//Make Karel fill the world
//with beepers
function main() {
//your code here
putBeeperLine();
while(leftIsClear()){
reset();
moveUp();
putBeeperLine();
}
}
function putBeeperLine(){
putBeeper();
while(frontIsClear()) {
move();
putBeeper();
}
}
function turnAround(){
turnLeft();
turnLeft();
}
function turnRight(){
turnLeft();
turnLeft();
turnLeft();
}
function reset(){
turnAround();
while(frontIsClear()){
move();
}
turnAround();
}
function moveUp(){
turnLeft();
move();
turnRight();
}https://stackoverflow.com/questions/60751017
复制相似问题