110 likes | 235 Views
Wrapping Up Crabs and Greenfoot. Mrs. C. Furman. Count How Many Worms Crab Has Eaten…. Lets decide that if Crab eats 8 worms it wins the game. What will we need???. What We Need To Track Worms?. An instance variable to store the current count of worms eaten;
E N D
Wrapping Up Crabs and Greenfoot Mrs. C. Furman
Count How Many Worms Crab Has Eaten… • Lets decide that if Crab eats 8 worms it wins the game. • What will we need???
What We Need To Track Worms? • An instance variable to store the current count of worms eaten; • An assignment that initializes this variable to 0 at the beginning; • Code to increment our count each time we eat a worm; • Code that checks whether we have eaten eight worms, and stops the game and plays a winning sound.
Instance Data • Where to put the instance data? • What should we name it? • What should the type be? • public or private?
Add instance data • Add an instance variable in the same place as the GreenfootImage instance data • private int wormsEaten;
Initialize Instance Data • Where do we initialize the instance data? • Write a statement that will initialize wormsEaten to 0
Add to the Constructor • Hopefully you decided to initialize the instance data in the constructor. • Add this line to the Crab constructor… • wormsEaten = 0;
Counting Worms Eaten • Where does crab eat worms? • Add an 1 to wormsEaten when Crab eats a worm.
Modify lookForWorm method • Add the following line to the lookForWorm method so that it will add 1 when a worm is eaten public void lookForworm () { if (this.canSee(Worm.class) ){ this.eat(Worm.class); wormsEaten = wormsEaten + 1; } }
Stopping at 8 • Where should we check for 8? • What should this if statement look for?
public void lookForWorm() { if (this.canSee(Worm.class) ) { this.eat(Worm.class); Greenfoot.playSound(“slurp.wav”); wormsEaten = wormsEaten + 1; if (wormsEaten == 8) { Greenfoot.playSound(“fanfare.wav”); Greenfoot.stop(); } } }