22.7. Exercises

For exercises, you can expand the Tamagotchi game even further. Try these out.

Here’s all the code we just saw for our new and improved game, with a few additions. You can run this and play the game again.

    1. Change the above code to allow you to adopt a Tiger pet (that you’re about to create). HINT: look at the whichtype function, and think about what’s happening in the code for that function.

    2. Now, modify the code to define a new class, Tiger. The Tiger class should inherit from the Cat class, but its default meow count should be 5, not 3, and it should have an extra instance method, roar, that prints out the string ROOOOOAR!.

    3. Next, modify the code so that when the hi method is called for the Tiger class, the roar method is called. HINT: You’ll have to call one instance method inside another, and you’ll have to redefine a method for the Tiger class. See the overriding methods section.

    4. Now, modify the code to define another new class, Retriever. This class should inherit from Lab. It should be exactly like Lab, except instead of printing just I found the tennis ball! when the fetch method is called, it should say I found the tennis ball! I can fetch anything!.

    5. Add your own new pets and modifications as you like – remember, to use them in the game, you’ll also have to alter the whichtype function so they can be used in game play. Otherwise, you’ll have different classes that may work just fine, but you won’t see the effects in the game, since the code that actually makes the game play is found in the second half of the provided code (look for the while loop!).

22.7.1. Contributed Exercises

You have attempted of activities on this page