In this tutorial we will focus on Python's PyGame library that allow to create all staff needed to create all sort of games. But we will not learn Python itself. You must know Python. Classes and modules are obligatory also modules to load files but no other extra knowledge.
PyGame
PyGame can handle time, video (both images and vids), music, fonts, different image formats, cursors, mouse, keyboard, Joysticks and much much more. And all of that is very simple.
SDL
PyGame is extension of SDL an C library that was created to allow easy migration form one operating system to another (e.g. Windows to Linux). Its means that PyGame is easy multi-platform multimedia library.
Game loop
Before writing first lines of code I will mention about how game loop is designed in PyGame. Game loop is the place where events, game logic and rendering onto screen is performed. It should look similar to:
while 1: events() loop() render()
Where event() proceeds events like pressed keys, mouse motion etc. loop() compute changes in the game world like NPC's moves, player moves, AI, game score. And render() just print out on the screen graphic. That separation of tasks makes your game design easier and allow to easy changes in code when new ideas rise in you head.
First code
Its time for more code:
import pygame from pygame.locals import * class App: def on_execute(self): pass if __name__ == "__main__" : theApp = App() theApp.on_execute()
As you can see I prefer classes than functions. That is because OOP is getting more and more fans in game programming due to it correlation with game design. Simply in game we have objects, theirs tasks etc. even when programing without classes.
CApp will be our main class. To run game we will only need call OnExecute() function. Yes this function will contain our Game Loop.
Creating simple window
Lets add some more code:
import pygame from pygame.locals import * class App: def __init__(self): self._running = True self._surf_display = None self.size = self.weight, self.height = 640, 400 def on_init(self): pygame.init() self._display_surf = pygame.display.set_mode(self.size, pygame.HWSURFACE | pygame.DOUBLEBUF) self._running = True def on_event(self, event): if event.type == pygame.QUIT: self._running = False def on_loop(self): pass def on_render(self): pass def on_cleanup(self): pygame.quit() def on_execute(self): if self.on_init() == False: self._running = False while( self._running ): for event in pygame.event.get(): self.on_event(event) self.on_loop() self.on_render() self.on_cleanup() if __name__ == "__main__" : theApp = App() theApp.on_execute()
Test
You should see black window. If window don't wont to quit use 'xkill' under linux or task manager under windows.
on_init on_event on_loop on_render on_cleanup
on_init calls pygame.init() that initialize all PyGame modules. Then it create main display - 640x400 window and try to use hardware acceleration. At the end this routine sets _running to True.
on_event check if Quit event happened if so sets _running to False wich will break game loop.
on_loop and OnRender do nothing.
on_cleanup call pygame.quit() that quits all PyGame modules. Anything else will be cleaned up by Python.
on_execute
on_execute initialize pygame than enter main loop in witch check events and then compute and render everything till _running is "True" and only Quit event will set it to "False".
Before quitting it will cleanup.
If you will run this file as program it will create instance of App and call its on_execute(). (3 last lines)
Note: PyGame can create your game's window in multiple modes:
pygame.FULLSCREEN a fullscreen display
pygame.DOUBLEBUF recommended for HWSURFACE or OPENGL
pygame.HWSURFACE hardware accelerated, only in FULLSCREEN
pygame.OPENGL an opengl renderable display
pygame.RESIZABLE display window should be sizeable
pygame.NOFRAME display window will have no border or controls






Thanks, this is a good tutorial. Short and simple, good for people just starting out like me.
witch should be which..
brake should be break..
quiting should be quitting..
programing should be programming
Seriously, how can I use this with students when they cringe at the errors!!
thx I've fixed them.
Keep fixing? Most sections have at least one typo. Read it aloud? Might help.
Not trying to be picky, i honestly found it very distracting.
First line:
"In this tutorial we will focus on Python's PyGame library that allow to create all staff needed to create all sort of games."
What?
keep fixing! And do not make a fuzz about it ! I am sure you are an able programmer, but it serves the wrong impression to people looking into the site if the English is faulty.
I found these errors:
1. line one "…PyGame library that allow…" 3.p.singular extra s that ALLOWS and preferably with an added pronoun after …allows you to…
2. you still need to explain what is meant by "all the staff". Staff normally denotes a group of people that work in a certain place.
3. line two "…all sort of games…" the expression goes "…all sorts of games…"
4. below the heading SDL:
…PyGame is extension of SDL an C library that was…
here you need to rephrase this to read like this:
…PyGame is an extension of SDL, a C library that was…
5. and likewise the next line:
…Its means that PyGame is easy multi-platform multimedia library…
I am sure you can tell yourself that there is something wrong here.
…This means that PyGame is an easy-to-learn multi-platform multimedia library…
I will not keep going on here, because I really appreciate what you are doing here, so keep at it. I am not a native English speaker, so I think I grasp the meaning, but obviously it confuses natives.
On a more general basis I would like to add that you should state clearly at the top of the page which python edition and pyGame installment the tutorial is made for, and there also seem to be some keyboard issues, that you might want to comment on, like suggesting user to change keyboard layout, etc.
I realize that this thread probably died out last autumn, so don't bother if you have started anew somewhere else.Sorry.
import sys, pygame
pygame.init()
size = width, height = 500, 500
black = 0, 0, 0
screen = pygame.display.set_mode(size)
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT: sys.exit()
screen.fill(black)
pygame.display.flip()
The content aside, for Python conventions, this is a terrible tutorial.
A loop should use True, not integers (while True), "import *" statements are generally frowned upon (and really, what's so hard about writing "pygame.QUIT" rather than "QUIT"?), classes should be in CamelCase, methods in lowercase_with_underscores, a "c" prefix in class names implies the class is implemented in C (and thus faster than a pure Python equivalent) and so on.
The general technique may be okay, but the source code is VERY painful to read.
@Alan give me a link to PEP or everything that I can read and learn (source code should be enough if nothing else)
But 1 + True = 2 in Python !!! ;) so I don't see any problems ;P
@David thx a lot
There is nothing wrong with "import * " statements when you're sure there will be no name conflicts. The code "from pygame.locals import * " has been in every pygame tutorial, and probably every pygame program, I've seen to date.
You don't have to use camelcase for classes, and you don't have to use underscores for methods.
Well, name clashes may occure if PyGame will be one of many librrary. Also you can't reload modules that are imported form import *.
But worst is when you use many modules, you have bug and you simple not know which module it is. (possible even if you use only PyGame)
Very nicely done .. I like these tutorials. Python is an awesome language to program in, and pygame is very good to beginners. I've started my own set of tutorials on my site : http://lameness-prevails.com/
Check it out and let me know if you like it!
Very nice introduction tutorial you got here pal. I like how you managed to talk about game logic in a generic way, as fun as python. I also liked the way you put O.O. concepts into your example so that it could be more readable for beginners. Congratz.
Excellent tutorial. I always follow this structure to get a clean code.
Great tutorial, it's nice to keep it OO.
One thing: self._surf_display and self._display_surf should probably be the same.
Nice tuto, thx.
I like your structure. As a fact with this I can start the program with a launcher, which I have not managed to do my work previously. I have tried to locate an answer in varies forums with out any lock.
Is et the "class App"-thing that does the trick ?
Congratulations on having the courage and good will to write this tutorial (and others!).
While your English /could/ use some improvement… I suspect that it isn't your mother tongue, so in knowing this, you're doing really well - the reader can see that you know what you're talking about.
So:
1) Either be the "life-long student" and take the (sometimes too harsh) criticisms with an open mind, and do the corrections
2) To play it safe, maybe give a little fore-warning at the beginning of the tutorial that English isn't your mother tongue but that you're doing your best! That'll keep the ruthless critics at bay…
3) Keep writing the tutorials!!! Trust that what you're conveying is relatively understandable, and trust that if ever there's anything that doesn't make sense, someone, somewhere, will leave a comment-question for you
4) You Rule! Bravo, and thanks for the tutorials - I'm having a great time with them!