您的位置:首页 > 编程语言

斯坦福大学开放课程——编程方法 作业1-3,个人实现方法。

2014-09-17 00:42 549 查看
/*
* File: CheckerboardKarel.java
* ----------------------------
* When you finish writing it, the CheckerboardKarel class should draw
* a checkerboard using beepers, as described in Assignment 1. You
* should make sure that your program works for all of the sample
* worlds supplied in the starter folder.
*/

import stanford.karel.*;

public class CheckerboardKarel extends SuperKarel {

public void run(){
//确定一开始前方无障碍,以排除单列情况出现,单列情况采用特殊方法。
if(frontIsClear()){
//非单列情况
//转向北
turnToNorth();
//放置第一个Beeper
putBeeper();
//开始循环
while(frontIsClear()){
//确定Karel在最左还是最右,接着智能转向
leftOrRight();
//填充整行
fillOneLine();
//转到下一行
nextLine();
}
//到达顶部,把最后一行填充
leftOrRight();
fillOneLine();
}else{
//此单列情况,特殊处理
turnToNorth();
putBeeper();
fillOneLine();
}
}

//转向北
public void turnToNorth(){
while(notFacingNorth()){
turnLeft();
}
}

/**填充并向前移动
* 先检测前方有无路可走,若有不断则执行
* 接着检测自身位置有无Beeper,有着往前移动一步,无则往前移动一步再放置Beeper
*/
public void fillOneLine(){

while(frontIsClear()){
if(beepersPresent()){
moveTo();
}else{
moveTo();
putBeeper();
}
}
}

//向前移动
public void moveTo(){
if(frontIsClear()){
move();
}
}

//判断在左边还是在右边,然后智能转向
public void leftOrRight(){
if(rightIsBlocked()){
//karel在右边,脸朝北,故往左转
turnLeft();
}else{
//karel在左边,脸朝北,故往右转
turnRight();
}
}

/**首先脸朝北
* 判断当前位置有无Beeper
* 有则向前移动并智能转向
* 无则向前移动一步,再放置Beeper
* 无论是哪一种情况,结束后脸朝北
*/
public void nextLine(){
turnToNorth();

if(noBeepersPresent()){
moveTo();
putBeeper();
turnToNorth();
}else{
moveTo();
leftOrRight();
turnToNorth();
}
}

}


Problem 3 

In this exercise, your job is to get Karel to create a checkerboard pattern of beepers inside an empty rectangular world, as illustrated in the following before-and-after diagram:



This problem has a nice decomposition structure along with some interesting algorithmic issues. As you think about how you will solve the problem, you should make sure that your solution works with checkerboards that are different in size from the standard
8x8 checkerboard shown in the example. Odd-sized checkerboards are tricky, and you should make sure that your program generates the following pattern in a 5x3 world:

 



 Another special case you need to consider is  that of a world which is only one column wide or one row high.  The starter folder contains several sample worlds that test these special cases, and you should make sure that your program works for each of them.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息