I've started to learn making games with python/pygame and as though it is easy to make a working game quickly in pygame, there's no real tutorial on how to organize the code in a sensible way.
On the pygame tutorials page, I've found 3 ways to do it.
1- No use of classes, for small projects
2- MVC ruby-on-rails kind of structure but without the rails framework which results in something overly complicated and obscure (even with OO programming and rails knowledge)
3- C++-like structure as follows: (clean and intuitive but maybe not very much python-like?)
import pygame
from pygame.locals import *
class MyGame:
def __init__(self):
self._running = True
self._surf_display = None
self.size = self.width, self.height = 150, 150
def on_init(self):
pygame.init()
self._display_surf = pygame.display.set_mode(self.size)
pygame.display.set_caption('MyGame')
#some more actions
pygame.display.flip()
self._running = True
def on_event(self, event):
if event.type == pygame.QUIT:
self._running = False
elif event.type == KEYDOWN:
if event.key == K_ESCAPE:
self._running = False
elif event.type == MOUSEBUTTONDOWN:
if event.button == 1:
print event.pos
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__" :
mygame = MyGame()
mygame.on_execute()
I'm used to make SDL games in C++ and I use this exact structure but I'm wondering if it's usable for both small and large projects or if there's a cleaner way in pygame.
For example I found a game organized like this:
imports
def functionx
def functiony
class MyGameObject:
class AnotherObject:
class Game: #pygame init, event handler, win, lose...etc
while True: #event loop
display update
It also looks very well organized and easy to follow.
Which structure should I use consistently in all my projects so as to have a clean code usable in small and large games?
on_foomethod your probably using some form of MVC. martinfowler.com/eaaDev/uiArchs.html - nate con_loop()andon_render()methods? As I understand it inon_renderwe make some drawings, right? And inon_loop()we perform some logic. Is it correct? - DaZzz