11a-class-examples

11a-class-examples - * that Karel is at the bottom of the...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
Handout #11a CS 106A June 25, 2009 Solution to the “Banish Winter” Problem Thanks to Eric Roberts for basically this entire handout /* * File: BanishWinterKarel.java * ---------------------------- * The BanishWinterKarel subclass gets Karel adorn a series * of trees with a cluster of beeper leaves. */ import stanford.karel.*; public class BanishWinterKarel extends SuperKarel { public void run() { while (beepersInBag()) { findTree(); processOneTree(); } } /* * Moves Karel up to the next tree. Since a tree is simply * a wall, this method can simply call moveToWall. You could * therefore replace the findTree call in the main program * with moveToWall, but the program might then be harder to * read because it violates the "tree" metaphor used at the * level of the main program. */ private void findTree() { moveToWall(); } /* * Adorns a single tree with a cluster of leaves. The * precondition is that Karel must be immediately * west of the tree, facing east; the postcondition is
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Background image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: * that Karel is at the bottom of the other side of the * tree, facing east. */ private void processOneTree() { turnLeft(); climbTree(); distributeLeaves(); descendToGround(); turnLeft(); } 2 /* * Climbs to the top of the tree. */ private void climbTree() { while (rightIsBlocked()) { move(); } } /* * Moves Karel back to the ground. Both the pre- and * postconditions have Karel facing south. */ private void descendToGround() { moveToWall(); } /* * Creates the cluster of leaves at the top of a tree. * The precondition is that Karel must be facing north at * the top of the tree; the postcondition is that Karel * is still at the top, but on the other side of the * trunk, facing south. */ private void distributeLeaves() { putBeeper(); for (int i = 0; i < 2; i++) { move(); turnRight(); putBeeper(); } move(); putBeeper(); } /* * Moves Karel forward until it is blocked by a wall. */ private void moveToWall() { while (frontIsClear()) { move(); } } }...
View Full Document

This note was uploaded on 10/14/2010 for the course CS 106A taught by Professor Sahami,m during the Fall '08 term at Stanford.

Page1 / 2

11a-class-examples - * that Karel is at the bottom of the...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online