Problem 2
Karel has been hired to repair the damage done to the Quad in the 1989 earthquake. In particular, Karel is to repair a set of arches where some of the stones (represented by beepers, of course) are missing from the columns supporting the arches, as follows:
Your program should work on the world shown above, but it should be general enough to handle any world that meets certain basic conditions as outlined at the end of this problem. There are several example worlds in the starter folder, and your program should work correctly with all of them.
When Karel is done, the missing stones in the columns should be replaced by beepers, so that the final picture resulting from the world shown above would look like this:
Karel may count on the following facts about the world, list on the next page:
- Karel starts at 1st Avenue and 1st Street, facing east, with an infinite number of beepers.
- The columns are exactly four units apart, on 1st, 5th, 9th Avenue, and so forth.
- The end of the columns is marked by a wall immediately after the final column. This wall section appears after 13th Avenue in the example, but your program should work for any number of columns.
- The top of the column is marked by a wall, but Karel cannot assume that columns are always five units high, or even that all columns are the same height.
- Some of the corners in the column may already contain beepers representing stones that are still in place. Your program should not put a second beeper on these corners.
/*
* 本程序是让雷卡尔修复斯坦福支撑柱,需要条件及达到目的如下:
* 1、卡雷尔的初始位置位于第一列、第一行,面向东,携带无限的支撑石(灰色方块);
* 2、每隔三列有一个支撑柱,分别位于第一、五、九和十三列,依此类推;
* 3、 最后一个支撑柱右侧紧贴一堵墙;
* 4、 每组支撑柱顶端为墙体,支撑柱不一定等高;
* 5、有些支撑柱中的石头并未完全缺损,程序不能在已有石头的位置再次置放。
*/
import stanford.karel.*;
public class StoneMasonKarel extends SuperKarel {
public void run(){
/**
* 1、确定Karel在顶部还是在底部,同时智能转向。
* 2、填充一列
* 3、填充完毕后转为东向。
* 4、水平移动四步。
*/
while(frontIsClear()){
TopOrUnder();
startToFillOneLine();
turnToEast();
moveToNextStoneOrStop();
}
//到达最后一列,把最后一列填充完毕,结束。
TopOrUnder();
startToFillOneLine();
}
//检查并填充Beeper
public void checkAndFill(){
if(!beepersPresent()){
putBeeper();
}
}
//向水平方向移动四步,如果有障碍则停止
public void moveToNextStoneOrStop(){
if(frontIsClear()){
for(int i = 0 ; i<4; i++){
if(frontIsClear()){
move();
}
}
}
}
//方向转为东
public void turnToEast(){
while(!facingEast()){
turnLeft();
}
}
//确定Karel在顶部还是在底部
public void TopOrUnder(){
turnToEast();
if(rightIsClear()){
//Karel is on the Top
//turn right
turnRight();
}else{
//Karel is under
turnLeft();
}
}
//如果前方无障碍物,则填充石块并移动
public void startToFillOneLine(){
while(frontIsClear()){
checkAndFill();
move();
}
checkAndFill();
}
}