Personal tools
You are here: Home Subsections Intro Game Programming Student Work Shock Circuit Object Oriented Programming Tutorial

Object Oriented Programming Tutorial

A basic introduction to Object Oriented Programming. If you want to make games, you need to know OOP.

Python Menu Tutorial

Python Menu Tutorial

Introduction

Menus are an important part of games. Without them we would be unable to do things like:

  • Start a new game rather than pick up a save game.
  • Continue a save game rather than starting a new game.
  • Change your display options to better suit your computer.
  • Change your control scheme to better fit your play style.
  • Exit your game!

The purpose of this tutorial is to illustrate the methodologies behind Object Oriented Programming..
While we're at it, we can touch on things like classes and instantiation in the Python programming language.

Before starting this tutorial a few things are expected:

  • It is expected you understand the basics of programming. This includes things like...
    • You should know what a variable is.
    • Understand the concept of a function and/or method (they're the same thing really...python calls them methods).
  • You need to be at least a little familiar with the python programming language. This includes things like...
    • Know how to write basic scripts with a text editor.
    • Know how to execute basic python code in the command line.
    • or...
    • Use Idle to write scripts and execute basic python commands.
    • and...
    • Define variables in Python.
    • Define basic Python datastructures (Lists in specific!)
    • Basic Python decision-making structures (If, Else If, etc...).
    • Basic looping structures (Do, While, For, Foreach, etc...).
    • The Python Range() method.
    • Print output to the command line/Idle interpreter.
If any of this looks strange you'll need to brush up on your basic Python skills before continuing or nothing is going to make sense. Go on. I can wait.

 

Honest. I can seriously wait a long, long, long time. No need to feel guilty on my account. I'm sure the server at www.python.org will be happy to entertain you. *sniff*

Example 1:
How not to make a menu

What's wrong with this psuedocode?
		//render our menu
		//set locx
		locx = 800/2 - 50
		
		//set locy
		locy = 50
		
		//set font
		font = FontString("comic sans MS")
		
		//set surface to draw on
		drawArea = Surface(800, 600)
		
		//draw the menu
		loop
			if (mouseXPosition is not in previousFontStringRectangle)
				renderFontString(drawArea, locx, locy, font, 50px, "Start")
				locy = locy + 100
			else
				renderFontString(drawArea, locx, locy, font, 75px, "Start")
				locy = locy + 75
			endif
			
			if (mouseXPosition is not in previousFontStringRectangle)
				renderFontString(drawArea, locx, locy, font, 50px, "Load")
				locy = locy + 100
			else
				renderFontString(drawArea, locx, locy, font, 75px, "Load")
				locy = locy + 75
			endif
			
			if (mouseXPosition is not in previousFontStringRectangle)
				renderFontString(drawArea, locx, locy, font, 50px, "Options")
				locy = locy + 100
			else
				renderFontString(drawArea, locx, locy, font, 75px, "Options")
				locy = locy + 75
			endif
			
			
			if (mouseXPosition is not in previousFontStringRectangle)
				renderFontString(drawArea, locx, locy, font, 50px, "Exit")
				locy = locy + 100
			else
				renderFontString(drawArea, locx, locy, font, 75px, "Exit")
				locy = locy + 75
			endif
		end loop
Answer: A lot actually.

While it might function, it probably won't function very well, and trying to do anything beyond simply
displaying the menu will take far more effort that it's worth.

This kind of programming is called procedural programming, and is generally considered to be
less efficient than Object Oriented Programming as will be demonstrated in example 2.

Example 2:
Building a better mousetrap

What if the code to display the same menu as Example 1 looked like this?
			//define the menu
			menu = MenuSystem(startXPosition, startYPosition)
			menu.addMenuItem("Start")
			menu.addMenuItem("Load")
			menu.addMenuItem("Options")
			menu.addMenuItem("Exit")
			
			//draw the menu
			loop
				menu.render()
			end loop

That's quite a bit easier to follow isn't it?

In order to demonstrate how we get Example 1 to look like Example 2 we need to use Object Oriented Programming methods. These include:

  • Classes
  • Objects
  • Object Orientation

Classes

Classes in Theory

Techhnicaly a class is a collection of variables and methods related by a common purpose. To make an analogy, a class is like
a set of blueprints that tell you how to do a specific thing or set of things. An often-used example is the blueprints for a car.
By defining a class you associate a number of variables and methods with each other based on what they do and represent.

When constructing classes, consider what you're trying to do and what operations are necessary to achieve your goal.
In the case of a menu we need to do the following:

  • Draw the different menu options to the screen.
  • Respond to user input by...
    • Enlarging menu items when they're moused over.
    • Changing menu options when a menu item is clicked.
  • Start the game when the proper menu item is selected.

If your menu needs to do all this, then you'll need to make a class, or collection of classes that allow your menu to do all this.

Classes are generally made of three parts:

  1. The class declaration
  2. The class constructor
  3. A number of class member methods
Member methods are where your classes get their usefulness. Anything your class is going to have to handle itself goes into what's called a member method

.

The general rule of thumb is that anything a class can do on it's own, will have to do repeatedly, and can very from class instance to class instance gets put into a

member method.

 

...I'm pretty sure that made no sense

Just in case the person reading this tutorial isn't some variation of a child genious I'll show you an example to illustrate.
...and in case this example doesn't help you can find more documentation at www.python.org.

Classes in Python

Classes in python are easy to make. Just make sure you follow the syntax:

			class [class name]:
				def __init__(self, [variable list]):
					...
					
				def [member function name](self, [variable list]):
					...
					

Just replace [class name] with the name of your class, and remember to leave off the brackets.
The same goes for [member function name].
self, [variable list] is a bit of a special case. For one it's totally optional, and for two it's going to be a comma-divided list of passed variables.
Other than the basic syntax just remember that you can't start a class name with anything other than an underscore or a character from A to Z either uppercase or lowercase.
Your ability to start class names with characters outside A to Z and a to z may vary from language to language, but usually it's a bad idea.

I promised you an example didn't I? Well...here it is:

			class menu:
				def displayMenu(self, menuItems):
					for x in range(menuItems):
						print 'Menu Item', x+1

Take that code, pop it into Idle, instantiate a menu object and run the displayMenu method. I dare ya!
You should get output that looks something like this:

			Menu Item 1
			Menu Item 2
			Menu Item 3
			Menu Item 4
			Menu Item 5
			Menu Item 6
			Menu Item 7
			Menu Item 8
			Menu Item 9
			Menu Item 10

What's that? You don't know how to instantiate a menu object or run the displayMenu method?
Don't worry. We'll get to that in the next section!

Objects

Objects in Theory

An Object is an instantiation of a class. To continue the analogy from the section on classes: if a class is the blueprint of a car,
then an instantiation of that class would be a car off the assembly line capable of doing all the things you allow it to do in the class.

Objects in Python

Objects in python, believe it or not, are even easier to work with than classes are. The only bad part is that you need to be able to write
a class before you can use an object.

Why is that?

Well, look back at the two pictures. You've got one picture of a set of car blue prints and another picture of a car.
Classes and objects have the exact same relationship! If a class is a set of blueprints, then an object is the physical representation of whatever
is on the blueprints (at least...as physical as data in a computer can be but you get the point right?).
When you make an object from a class definition, it's called an instance of that class. Hence the term from above: instantiate.

To go over some basic terminology:

  1. A class is a collection of related variables and methods grouped together by a class definition.
  2. An object is the instantiation of a class. A class object will have access to it's own collection of variables and methods as defined in it's class definition.
  3. An instance of a class is an object created from a specific class definition.
  4. To instantiate a class is the verb used to refer to the creation of an instance of a class.

 

So how do you make an object and, say, make it do something? Something like the output from the previous example maybe?

BEHOLD!

			x = menu()
			x.displaymenu(10)

Yep. That's it. We'll continue on in the next section.

Object Orientation

Object Orientation in Theory

How can you tell if something should be a class rather than free-standing code?
How can you tell if coding something as a class will result in less code?

To answer the first one, ask yourself these questions:
How is this built? (Where this is whatever you're building). If your answer comes out something like "this has several of these"
then you're probably looking at something that could be written as a class.

Take a menu for example:

  • A menu has several menu items
  • Each menu item can have a click-function
  • There can be several different click-functions

Sounds simple right?
Actually, so far as things go it is pretty simple. A menu is made up of menu items that do something when you click them.

Object Orienting a Menu

But how do we make a menu object oriented? Why make it object oriented?
Confused yet? (I know I was when I was learning object oriented programming practices...)

This calls for another example! However, first thing first we're going to restart Idle. Don't skip this part. It's important.
Now, I want you to duplicate the output from the previous example, only don't use a class to do it. Output it by hand, use a raw for loop,
use a function. However you do it your output should look like this:

			Menu Item 1
			Menu Item 2
			Menu Item 3
			Menu Item 4
			Menu Item 5
			Menu Item 6
			Menu Item 7
			Menu Item 8
			Menu Item 9
			Menu Item 10

About as much work as making a class and then making an instance right?
Well...do it again. Only this time make five menu items.

Now one more time, only make 12 menu items and each menu item needs to have a meaningful name like "Start", or "Options", or "Display", or "Adjust Sound Settings".
It's okay. I've got time.

I know what you're thinking. "You first buddy!". Right? It's okay to admit defeat. The point of the excercise wasn't about a menu anyway.
Still, make 12 lines of output like the previous two. Go ahead.

Now, enter the following code into Idle:

			class menu:
				def __init__(self, menuItemCount):
					self.menuItems = menuItemCount
				def displayMenu(self):
					for x in range(self.menuItems):
						print 'Menu Item', x+1

Follow it with the following:

			m = [menu(10), menu(5), menu(12)]
			
			for sub in m:
			sub.displayMenu()
			print ''

Why didn't you do that the first time? Wasn't that easier?

More on Python

If you want more on the Python programming language check out the following...

Pygame

A more advanced example of Object Oriented Programmin at work is the menu system in the Shock Circuit game.
Before you're ready to tackle that you'll need to familiarize yourself a little with Pygame.
In particular you'll need to go over Font.render(), Mouse.get_pos(), and the Rect and Surface classes.

More Game Related Menus

Now you should be ready to start digging through my menu code in Shock Circuit.
Check out Main.py for instantiation examples.
For a complete and extendible example of a graphical menu check out Menu.py and Menuitem.py.
For more information on the graphical portions of the menus check out...

Document Actions