解决如下图所示问题:(生成间隔棋盘状图案)
要求程序可以在 各类形状的地图中正常运行(如1x8 8x1 5x6 6x6 7x7 等等)
代码如下:
/*
* File: CheckerboardKarel.java
* ----------------------------
* The CheckerboardKarel class is able to 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() {
goToOrigin();
genReferenceRow(); //generate a reference row, choose 1st row as reference
toFaceNorth(); //to face north
while ( frontIsClear() ) {
if ( beepersPresent() ) {
moveToNextRow();
if ( frontIsClear() ) {
move();
genReferenceRow();
} //to deal with world with only one column
} else {
moveToNextRow();
genReferenceRow();
}
toFaceNorth();
} //end of while loop
} //end of main method
/*
* Make Karel move to the next row without changing column number
* Karel is always moving toward north part
* Precondition: facing north
* Postcondition: facing east/west depending on Karel is standing on
* left end or right end
*/
private void moveToNextRow() {
if ( leftIsBlocked() ) { //at left end wall of the world
move();
turnRight(); //to face east
} else { //at right end wall of the world
move();
turnLeft(); //to face west
} // end of if-else
} // end of moveToNextRow()
/*
* Is defined to generate one row of beepers, beepers are exactly 2 units apart
* Precondition: any case
* Postcondition: arrive at the end of one row
*/
private void genReferenceRow() {
if ( frontIsBlocked() ) {
putBeeper(); //dealing with the world with only one column
}
while ( frontIsClear() ) {
putBeeper();
move(); //enter while means can move forward at least one step
if ( frontIsClear() ) {
//if width is even, second move could not be made
move(); //second move
//if width is odd, second move should make, one beeper should be added
//in front of wall
if ( frontIsBlocked() ) {
putBeeper();
}
}
}
}
/*Move Karel back to origin of map (1,1), make it facing east
* Precondition: can be any case
* Postcondition: standing on (1,1) facing east
*/
private void goToOrigin() {
while (notFacingSouth()) {
turnLeft();
}
moveToWall();
while (notFacingWest()) {
turnLeft();
}
moveToWall();
while (notFacingEast()) {
turnLeft(); //Karel will face east
}
}
private void moveToWall() { //move Karel to wall
while (frontIsClear()) {
move();
}
}
private void toFaceNorth() {
while ( notFacingNorth() ) {
turnLeft();
}
}
}