## Posted By

MediaTechWare on 04/24/13

## Who likes this?

1 person have marked this snippet as a favorite

# CheckerboardKarel

/ Published in: Java

This code solves the CheckerboardKarel problem presented in Assignment 1 of the Stanford University CS106A Programming Methodology course.

`/* * File: CheckerboardKarel.java * ---------------------------- * The CheckerboardKarel class draws a checkerboard using beepers, * as described in Assignment 1.  The program works for all of the sample * worlds supplied in the starter folder. */ import stanford.karel.*; public class CheckerboardKarel extends SuperKarel { 	/* Karel starts on the corner of 1st St. and 1st Ave. at the beginning 	 * of the program. Conceptually, the streets are separated as ones with odd	 * numbers and even numbers. Odd numbered streets start with a beeper on the first	 * corner, while even numbered streets start with a beeper on the second corner	 * to create the checkerboard effect. Karel lays the beepers on the first street through	 * the layOddStreet() command. At the end of the street, Karel is left facing East. If	 * at this point Karel detects that there is another street above, Karel moves all the	 * way to the beginning of the street, moves one street up and lays beepers, this time	 * for through the layEvenStreet() command. Karel alternates laying beepers on odd and	 * even numbered streets until it detects that there are no streets above.*/	public void run() {		layOddStreet();		while(leftIsClear()) {			getBackAndMoveOneStreetUp();			layEvenStreet();			if(leftIsClear()) {				getBackAndMoveOneStreetUp();				layOddStreet();			}		} 	}	/* The layOddStreet command assumes Karel is on one of the odd numbered streets.	 * Karel starts with laying down a beeper, and then carries on skipping one corner	 * and laying a beeper on the next corner until it detects a wall. At the end of	 * the execution of the command, Karel is left immediately against the wall at the	 * end of the street, facing East.	 */	private void layOddStreet() {		putBeeper();		while(frontIsClear()) {			move();			if(frontIsClear()) {				move();				putBeeper();				} 		}	}	/* The layEvenStreet() command assumes Karel is on one of the even numbered streets.	 * Karel starts with moving one corner ahead if it detects that its front is clear.	 * From here, Karel treats the remainder of the street as an odd numbered street and	 * executes the layOddStreet() command.	 */	private void layEvenStreet() {		while(frontIsClear()) {			move();			layOddStreet();		}	} 	/* This command assumes Karel is standing at the end of an odd or even numbered street	 * facing East. The command turns Karel around and moves him until he reaches the	 * western wall of the room. When he reaches the wall, Karel turns right, moves one corner	 * up and turns right once more to face East again.*/	private void getBackAndMoveOneStreetUp() {		turnAround();		while(frontIsClear()) {			move();		}		turnRight();		move();		turnRight();	} }`