[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

Re: [pygame] main game object using singleton/global/static?



Either singletons or globals would work fine.  Singletons are more useful when you see a need to enforce a rule that the class must be instanced only once, but if you are the only developer and can trust yourself not to do something silly, globals work just as well.  I tend to use singletons because I avoid globals as a matter of principle (except in prototype programs).

On Fri, Jul 17, 2009 at 5:47 PM, Jake b <ninmonkeys@xxxxxxxxx> wrote:
Summery:
How do I organize my data structures to read or pass my Game() object in ship.py ?

Here is Pseudo code of what i'm talking about:
http://pastebin.com/m985fe2f

Long:

How do you use your 'game' class? I created one class that handles screen creation, game main loop, list of Sprites, etc... But I'm not sure on how I should access the game members.

In Ship.draw() I have a couple of potential examples, where the one i'm using right now is:
self.screen.blit(self.image)
(It saves a reference to Game.screen)

But, this requires me to create my objects inside of Game(), passing a reference to the game instance every time a sprite is created, like so:
# def Game.spawn():
self.sprites.add( Ship( self ) )

This seems wrong/hackish to me. Is there a way I can have a (semi?) global function / method? Or should I do this?

I didn't want to make 'screen' a global variable, because I want access to Game(), since there are multiple members/methods I need access to. 

Another example: of a function that needs access to game members: This is called in ship.py when the sprite is spawned.

# def Game.randLoc(self):
"""returns random location that exists in boundries of current map"""
return randint( 0, self.map.width ), randint( 0, self.map.height)

--
Jake



--
--Ostsol

http://cheesesun.blogspot.com/