斯坦福大学公开课 编程方法学 Karel the Robot 寻找中点问题解决

时间:2021-09-13 20:14:13

斯坦福大学公开课的《 编程方法学》是学习Java很好的课程,课程开始是学习Karel,本文是作业MidpointFindingKarel的解决方案,运行结果如下:

斯坦福大学公开课 编程方法学 Karel the Robot 寻找中点问题解决

思路是先确定方块的总数,然后将方块依次减半直到方块为1,即为找到中点。代码如下:

import stanford.karel.*;

public class MidpointFindingKarel extends SuperKarel {
public void run() {
createBeeperLine();
collectAllBeeper();
putBeeperToCentre();
}

private void createBeeperLine() {
while (frontIsClear()) {
putBeeper();
move();
}
putBeeper();
}

private void collectAllBeeper() {
while (frontIsBlocked() && facingEast()) {
turnAround();
move();
while (frontIsClear()) {
pickBeeperToBack();
while (noBeepersPresent() && frontIsClear()) {
move();
}
}
pickBeeperToBack();
}
while (frontIsBlocked() && facingWest()) {
turnAround();
while (frontIsClear()) {
move();
}
}
}

private void pickBeeperToBack() {
while (beepersPresent() && facingWest()) {
pickBeeper();
turnAround();
while (frontIsClear()) {
move();
}
putBeeper();
}
}

private void putBeeperToCentre() {
while (beepersPresent()) {
decreaseHalfBeeper();
turnAround();
move();
turnAround();
}
putBeeper();
}

private void decreaseHalfBeeper() {
while (beepersPresent() && facingEast()) {
pickBeeper();
turnAround();
move();
turnAround();
move();
if (beepersPresent()) {
pickBeeper();
turnAround();
move();
putBeeper();
turnAround();
move();
}
}
}
}