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:
while True: 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.
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:
import pygame from pygame.locals import * class App: def __init__(self): self._running = True self._display_surf = 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 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
Thanks, this is a good tutorial. Short and simple, good for people just starting out like me.
how good are you now?
Bro replied 13 years later 💀
jajaj
I am china
And I'm Thomas turbando
And my axe!
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 ?
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.
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!
Shouldn't it be width instead of weight?
hi that was great
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!
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.
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.
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
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.
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.