Tutorials Basic

Here you can find tutorial guiding you through process of making simple game with Python and PyGame. Starting from scratch we will make simple yet useful game engine (backbone of every game), and few games showing by example how complete games look like.
Hope you will enjoy it!

Python

Probably best programming language out there! Chosen because of its simplicity and small learning curve.

PyGame

PyGame can handle time, video (both still 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 based on SDL. A C library that is cross platform and also very simple. PyGame however is not just simple wrapper for it, but also add its own features, so writing games is even simpler.

Versions used during this tutorial:

  • Python 2.7
  • PyGame 1.9.1

If you can not run tutorial examples in Python 3, pleas report it as bugs. However there are many out there who still use Python 2, so it will be used as primary version.

Source code

Last thing before we start our codding.
Source code for this tutorial is hosted at bitbucket.com
If you want to you can clone whole repo. Each tutorial have its own tag or multiple tags if there are more then one version of code discussed during tutorial.
If you do not know what I'm talking about, then do not worry! I will provide links to downloads of source code for and at the bottom of each tutorial.

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:

whileTrue:
 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:

importpygamefrompygame.localsimport *
 
classApp:
 defon_execute(self):
 passif__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.

App will be our main class. To run game we will only need call on_execute() function. Yes this function will contain our Game Loop.

Creating simple window

Lets add some more code:

importpygamefrompygame.localsimport *
 
classApp:
 def__init__(self):
 self._running = Trueself._display_surf = Noneself.size = self.weight, self.height = 640, 400defon_init(self):
 pygame.init()self._display_surf = pygame.display.set_mode(self.size, pygame.HWSURFACE | pygame.DOUBLEBUF)self._running = Truedefon_event(self, event):
 ifevent.type == pygame.QUIT:
 self._running = Falsedefon_loop(self):
 passdefon_render(self):
 passdefon_cleanup(self):
 pygame.quit()defon_execute(self):
 ifself.on_init() == False:
 self._running = Falsewhile(self._running):
 foreventinpygame.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 which 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)

Big thx to people who helped me to improve this tutorial by woicing their ideas in comments (which are now deleted):

  • Sin
  • fidget
  • Alan
  • aanund
  • Kwright

Zipped source code:

Small example.
Big example

page 1 of 31
thanks
fipi (guest) 29 May 2009 01:20

Thanks, this is a good tutorial. Short and simple, good for people just starting out like me.

by fipi (guest), 29 May 2009 01:20
billy (guest) 12 May 2022 13:28

how good are you now?

by billy (guest), 12 May 2022 13:28
bruhMoment (guest) 20 Sep 2022 14:59

Bro replied 13 years later πŸ’€

by bruhMoment (guest), 20 Sep 2022 14:59
jlsomg (guest) 03 Dec 2022 22:19

jajaj

by jlsomg (guest), 03 Dec 2022 22:19
china (guest) 05 Apr 2023 02:00

I am china

by china (guest), 05 Apr 2023 02:00
Tomas Turbando (guest) 27 May 2023 23:09

And I'm Thomas turbando

by Tomas Turbando (guest), 27 May 2023 23:09
my-axe (guest) 30 Nov 2023 16:33

And my axe!

by my-axe (guest), 30 Nov 2023 16:33
is-my-buddy (guest) 13 Feb 2025 09:29

and is my buddy!

by is-my-buddy (guest), 13 Feb 2025 09:29
Dad (guest) 16 Mar 2025 23:29

Hi, China. I'm dad!

by Dad (guest), 16 Mar 2025 23:29
protogen (guest) 31 Mar 2025 18:02

and protogen

by protogen (guest), 31 Mar 2025 18:02
Khan :3 (guest) 08 May 2025 16:30

and Khan :3 too!

by Khan :3 (guest), 08 May 2025 16:30
Hey
Karanveer (guest) 15 Jun 2010 16:45

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!

by Karanveer (guest), 15 Jun 2010 16:45
DZONI VERNI PROGRAMER (guest) 12 Jul 2024 22:01

Me too

by DZONI VERNI PROGRAMER (guest), 12 Jul 2024 22:01
mmmmmmmmmmmmmmmmm (guest) 31 Mar 2025 18:05

me 3

by mmmmmmmmmmmmmmmmm (guest), 31 Mar 2025 18:05
Enki (guest) 31 Dec 2010 22:42

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.

by Enki (guest), 31 Dec 2010 22:42
repe (guest) 05 Jan 2011 12:49

Excellent tutorial. I always follow this structure to get a clean code.

by repe (guest), 05 Jan 2011 12:49
livelite (guest) 13 Mar 2011 02:17

Great tutorial, it's nice to keep it OO.

One thing: self._surf_display and self._display_surf should probably be the same.

by livelite (guest), 13 Mar 2011 02:17
Frede (guest) 09 Apr 2011 12:59

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 ?

by Frede (guest), 09 Apr 2011 12:59
przemo_li przemo_li 11 Mar 2012 12:13

If you need "Launcher" as "stand alone app" that after setting setting, checking for updates, etc. start your main aplication, then I can not help you :| Never needed it myself.

However if I had to make one I would look for ways to execute other apps, because you need separete launcher when you can not build required functionality into game (app) itself.
Eg. if you want to add autoupdate functionality to game (app), its hard to do if game (app) is trying to applay patch on itself. (OS will complain that you want to change files that are used by running app, I suppose).
General solution is to provide separate app, that applay patch, and then lunch game (app).

Look for execfile or other such python techniques.

PS If you meant something different by "launcher" then replay with more details so we can help you.

Last edited on 11 Mar 2012 13:03 by przemo_li
by przemo_li przemo_li , 11 Mar 2012 12:13
Thomas (guest) 01 Oct 2011 10:34

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!

by Thomas (guest), 01 Oct 2011 10:34
Zenger (guest) 27 Jan 2013 14:27

Shouldn't it be width instead of weight?

by Zenger (guest), 27 Jan 2013 14:27
bob (guest) 26 Sep 2013 16:10

hi that was great

by bob (guest), 26 Sep 2013 16:10
arun (guest) 27 Jan 2014 03:02

Hey,
i have a question…
on_init() does not have any return statement to return a value, so what value is being checked in
def on_execute(self):
if self.on_init() == False: ? Thanks for the tutorial too!

by arun (guest), 27 Jan 2014 03:02
Dave (guest) 26 Mar 2014 18:01

I was thinking that myself, also why have on_init and init? Why not just put everything in init and return false if the display cannot be created.

Dave.

by Dave (guest), 26 Mar 2014 18:01
Martyn (guest) 21 Apr 2014 17:00

def on_init(self):
pygame.init()
self._display_surf = pygame.display.set_mode(self.size, pygame.HWSURFACE)
return self._display_surf

def on_execute(self):
if self.on_init() == None:
self._running = False

'The self._running = True' in on_init is completely redundant, as the class initialises it to True when the App object is instantiated in main anyway.

The above makes far more sense. If self._display_surf does not work, it will set self._running to False and won't execute the While loop in on_execute.

The reason on_init and init are not combined is probably for future code expansion. You might want to do other tasks via other methods before displaying the window. Change the window size, load sprites, etc.

by Martyn (guest), 21 Apr 2014 17:00
Das (guest) 25 Jun 2014 05:46

I think rather than having

if self.on_init() == None:
self._running = False

something efficient would be

try: self.on_init()
except: self._running = False

by Das (guest), 25 Jun 2014 05:46
Dash (guest) 26 Aug 2014 02:03

When I ran that program, it came up with a message like this:
Traceback (most recent call last):
File "C:/Python27/For new programs for Ken/first pygame.py", line 1, in <module>
import pygame
File "C:\Python27\lib\site-packages\pygame\init.py", line 95, in <module>
from pygame.base import *
ImportError: DLL load failed: %1 is not a valid Win32 application.

by Dash (guest), 26 Aug 2014 02:03
Sheldon (guest) 10 Jan 2020 14:15

the same is happening with me. I want to learn pygame and nothing is helping right now. If someone can hep please suggest some tutorials.

by Sheldon (guest), 10 Jan 2020 14:15
Cherprang (guest) 18 Jan 2025 05:48

This is error is due to version mismatch between Python and Pygame.

Update to latest version of Python and Pygame and you should be good.

by Cherprang (guest), 18 Jan 2025 05:48
page 1 of 31
page revision: 36, last edited: 27 Mar 2012 08:41
Click here to edit contents of this page.
Click here to toggle editing of individual sections of the page (if possible). Watch headings for an "edit" link when available.
Append content without editing the whole page source.
Check out how this page has evolved in the past.
If you want to discuss contents of this page - this is the easiest way to do it.
View and manage file attachments for this page.
A few useful tools to manage this Site.
Change the name (also URL address, possibly the category) of the page.
View wiki source for this page without editing.
View/set parent page (used for creating breadcrumbs and structured layout).
Notify administrators if there is objectionable content in this page.
Something does not work as expected? Find out what you can do.
General Wikidot.com documentation and help section.
Wikidot.com Terms of Service - what you can, what you should not etc.
Wikidot.com Privacy Policy.

AltStyle γ«γ‚ˆγ£γ¦ε€‰ζ›γ•γ‚ŒγŸγƒšγƒΌγ‚Έ (->γ‚ͺγƒͺγ‚ΈγƒŠγƒ«) /