In this fourth part of six-part series on the Python programming language, we'll explain what object-oriented programming is, and take a look at classes in Python. This article is excerpted from chapter two of the book Beginning Game Development with Python and Pygame: From Novice to Professional, written by Will McGugan (Apress; ISBN: 9781590598726).
Introducing Object-Oriented Programming
You may have heard the term object-oriented programming (OOP) before. But don’t worry if you are unfamiliar with it, because the concept is remarkably simple.
So what exactly is an object in OOP terms? Well, it can literally be anything. In a game we may have an object for a particle—say, a burning ember emitted from an explosion, or the hover tank that caused the explosion. In fact, the entire game world could be an object. The purpose of an object is to contain information and to give the programmer the ability to do things with that information.
When constructing an object, it is usually best to start by working out what information, or properties, it contains. Let’s think about what would be found in an object designed to represent a futuristic hover tank. It should contain a bare minimum of the following properties:
Position: Where is the tank?
Direction: In what direction is it facing?
Speed: How fast is it going?
Armor: How much armor does it have?
Ammo: How many shells does it have?
Now that we have the information to describe a tank and what it is doing, we need to give it the ability to perform all the actions that a tank needs to do in a game. In OOP-speak, these actions are called methods. I can think of the following methods that a tank will definitely require, but there will likely be far more:
Move: Move the tank forward.
Turn: Rotate the tank left/right.
Fire: Launch a shell.
Hit: This is the action when an enemy shell hits the tank.
Explode: Replace the tank with an explosion animation.
You can see that the methods typically change the properties of an object. When theMovemethod is used, it will update the tank’sPosition. Similarly, when theFiremethod is used, the value ofAmmo will be updated (unless of course there is noAmmo left; thenFirewould not do anything!).