Section Handout
让Karel把地图的内圈布满方块,起始和完成后的效果如图
思路:
很简单,先移到起始点(2,2),然后开始放方块就OK了。至于放方块就要考虑每行或列的最后一个位置不放,而且为了简化代码,能循环。每放置一行或列需要回到下一行或列的起始点(也就是上行或列的最后1个方块的位置),当然,这时Karel要做好开始放方块的准备,即面向新的行或列。
代码:
1 * File: StoneMasonKarel.java
2 */
3
4 import stanford.karel.*;
5
6 public class StoneMasonKarel extends SuperKarel {
7
8 // main program
9 // step 1: move to the (2,2) corner
10 // step 2: put all beepers as the task asked.
11
12 public void run(){
13 moveToRowDown();
14 putSquareBeepers();
15 }
16
17 // move to the start point
18 private void moveToRowDown(){
19 turnLeft();
20 move();
21 turnRight();
22 }
23
24 // put beepers
25 private void putSquareBeepers(){
26 move();
27 putLineBeepers();
28
29
30 }
31
32 // fill each inside row or column full of beepers
33 private void putLineBeepers(){
34 while (noBeepersPresent()){
35 if (frontIsClear()){
36 putBeeper();
37
38 }else{
39 turnAround();
40 move();
41 turnRight();
42
43 }
44 move();
45 }
46 }
47
48 }