BeeperCollectingKarel

Retired DISLab
이동: 둘러보기, 찾기
/**
 * File: BeeperCollectingKarel.java
 * --------------------------------
 * The BeeperCollectingKarel class collects all the beepers in a series
 * of vertical towers and deposits them at the rightmost corner
 * on 1st street.
 */
 
import stanford.karel.*;
 
public class BeeperCollectingKarel extends CountKarel {
	/**
	 * Specifies the program entry point.
	 */
	public void run() {
		collectAllBeepers();
		dropAllBeepers();
		returnHome();
	}
 
	/**
	 * Collects the beepers from every tower by moving along 1st street,
	 * calling collectOneTower at every corner.
	 * The postcondition for this method is that Karel is in the
	 * eastermost corner of 1st Street facing east.
	 */
	private void collectAllBeepers() {
		while (frontIsClear()) {
			collectOneTower();
			move();
		}
		collectOneTower();
	}
 
	/**
	 * Collects the beepers in a single tower. When collectOneTower is
	 * called, Karel must be on 1st Street facing east.
	 * The postcondition for collectOneTower is that Karel must again be
	 * facing east on that same corner.
	 */	
	private void collectOneTower() {
		turnLeft();
		collectLineOfBeepers();
		turnAround();
		moveToWall();
		turnLeft();
	}
 
	/**
	 * Collects a consecutive line of beepers. The end of the beeper line
	 * is indicated by a corner that contains no beepers.
	 */
	private void collectLineOfBeepers() {
		while (beepersPresent()) {
			pickBeeper();
			if (frontIsClear()) {
				move();
			}
		}
	}
 
	/**
	 * Drops all the beepers on the current corner.
	 */
	private void dropAllBeepers() {
		while (beepersInBag()) {
			putBeeper();
		}
	}
 
	/**
	 * Returns Karel to its initial position at the corner of 1st Avenue
	 * and 1st Street, facing east.  The precondition for this method
	 * is that Karel must be facing east somewhere on 1st Street,
	 * which is true at the conclusion of collectAllBeepers.
	 */
	private void returnHome() {
		turnAround();
		moveToWall();
		turnAround();
	}
 
	/**
	 * Moves Karel forward until it is blocked by a wall.
	 */
	private void moveToWall() {
		while (frontIsClear()) {
			move();
		}
	}
 
	public static void main(String[] args) {
		String[] newArgs = new String[args.length + 1];
		System.arraycopy(args, 0, newArgs, 0, args.length);
		newArgs[args.length] = "code=" + new SecurityManager(){
			public String className() {
				return this.getClassContext()[1].getCanonicalName();
			}
		}.className();
		SuperKarel.main(newArgs);
	}
}
개인 도구
이름공간
변수
행위
둘러보기
구성원
연구
연구실
기타
도구모음
인쇄/내보내기