After reading lesson 34, you’ll be able to
- Use classes to build a more complex program
- Use classes others have created to improve your program
- Allow users to play a simple version of the card game War
When you make your own object types, you can organize larger programs so that they’re easier to write. The principles of modularity and abstraction introduced with functions also apply to classes. Classes are used to package a set of properties and behaviors common to a set of objects so that the objects can be used consistently in a program.
A common first program with classes is to simulate playing some sort of game with the user.
The problem
You want to simulate playing the card game War. Each round, players will take a card from one deck and compare the cards. The one with the higher card wins the round and gives their card to the other player. The winner is determined after numerous rounds, when the deck is empty. The winner is the person with fewer cards in their hand. You’ll create two types of objects: a Player and a CardDeck. After defining the classes, you’ll write code that simulates a game between two players. You’ll first ask users for their names then create two Player objects. Both players will use the same card deck. Then you’ll use methods defined in the Player and CardDeck classes to automatically simulate the rounds and determine the winner.