Main | CS106A: Programming Methodology Assignment 1.4 »
Friday
Dec072012

CS106A: Programming Methodology Assignment Problem Set 1


import stanford.karel.*;

public class defendingDemocracy extends Karel {

	public void run() {
		move();
		while (frontIsClear()){
			checkVote();
			nextVote();
		}
	}
	
	//assumes Karel in center of vote
	private void checkVote(){
		cleanVote();
	}
	
	private void cleanVote(){
		//Voter intends yes
		if (beepersPresent()){
			cleanAndPlace();
			goTopChad();
			cleanAndPlace();
			goBottomChad();
			cleanAndPlace();
			goCenterChad();
		} 
	
		//Voted intends no
		if (noBeepersPresent()) {
			cleanChad();
			goTopChad();
			cleanChad();
			goBottomChad();
			cleanChad();
			goCenterChad();
		}
		
	}
	
		private void goCenterChad() {
			turnAround();
			move();
			turnRight();
		}
	
		private void goTopChad() {
			turnLeft();
			move();
		}
		
		private void goBottomChad() {
			turnAround();
			move();
			move();
		}
		
		private void cleanChad() {
			while (beepersPresent()){
				pickBeeper();
			}		
		}
		
		private void cleanAndPlace() {
			//Check for hanging chad
				cleanChad();
				putBeeper();
		}
	
		//Assumes Karel in in center facing east
		private void nextVote(){
			move();
			if (frontIsClear()){
				move();
			}
		}
		
		private void turnAround() {
			for (int i=0; i < 2; i++) {
				turnLeft();
			}
		}
			
		private void turnRight () {
			for (int i=0; i < 3; i++) {
				turnLeft();
			}
		}
	}