I'm trying to write a simple game and decided I need an eventmanager.
<code>
import weakref
from collections import defaultdict
class _EventManager( object ):
def __init__( self ):
self._handled_events =
defaultdict( weakref.WeakKeyDictionary )
def register( self, handler, event_type, filter=None ):
self._handled_events[event_type][handler] = filter
def deregister( self, handler, event_type ):
self._handled_events[event_type].pop( handler, None )
def handle_event( self, event ):
event_type = event.type
for handler, filter in
self._handled_events[event_type].items():
if filter == None or filter(event):
handler( event )
eventmanager = _EventManager()
__all__ = [ eventmanager ]
</code>
Fairly simple, yet there was some strange bug that prevented my game
from exiting.
I think what happened was that when __init__ ends, self goes out of
scope, and by extension so does self.handle_quit, Now there are no
more refeences to self.handle_quit, because weakrefs don't count, and
the event gets automatically dropped from my eventmanager. I thought
that wouldn't happen because handle_quit is part of the class and
instance MainGame.
Am I right in my guess? If so, how should I adress this bug? If not,
what is the bug?
<code>
import pygame
from eventmanager import eventmanager
class MainGame( object ):
def __init__( self, width=1024, height=768 ):
#Initialize PyGame
pygame.init()
self.width = width
self.height = height
self.quit_game = False
#Create the Screen
self.screen = pygame.display.set_mode( ( self.width,
self.height ) )
eventmanager.register( self.handle_quit, pygame.QUIT )
eventmanager.register( self.handle_quit, pygame.KEYDOWN,
key_filter( pygame.K_ESCAPE ) )
def mainloop( self ):
handle_event = eventmanager.handle_event
self.quit_game = False
while not self.quit_game:
for event in pygame.event.get():
handle_event( event )
def handle_quit( self, event=None ):
self.quit_game = True
def key_filter( key ):
def filter( event ):
return event.key == key
return filter
def handle_print_event( event ):
print str( event )
if __name__ == "__main__":
game = MainGame()
game.mainloop()
</code> 3 2009
On Oct 20, 2:47 pm, Odalrick <odalr...@hotmail.comwrote:
I'm trying to write a simple game and decided I need an eventmanager.
<code>
import weakref
from collections import defaultdict
class _EventManager( object ):
def __init__( self ):
self._handled_events =
defaultdict( weakref.WeakKeyDictionary )
def register( self, handler, event_type, filter=None ):
self._handled_events[event_type][handler] = filter
def deregister( self, handler, event_type ):
self._handled_events[event_type].pop( handler, None )
def handle_event( self, event ):
event_type = event.type
for handler, filter in
self._handled_events[event_type].items():
if filter == None or filter(event):
handler( event )
eventmanager = _EventManager()
__all__ = [ eventmanager ]
</code>
Fairly simple, yet there was some strange bug that prevented my game
from exiting.
I think what happened was that when __init__ ends, self goes out of
scope, and by extension so does self.handle_quit, Now there are no
more refeences to self.handle_quit, because weakrefs don't count, and
the event gets automatically dropped from my eventmanager. I thought
that wouldn't happen because handle_quit is part of the class and
instance MainGame.
Am I right in my guess? If so, how should I adress this bug? If not,
what is the bug?
The next stage in debugging is to think of a test that will prove your
guess right or wrong. I'd remove weakrefs from your event manager and
see if your code starts working.
I'd suggest you're a bit confused about your event manager's API: you
have register/deregister methods and are also using weakrefs to
provide auto-deregistering. I don't know your code, but this looks
like a mistake to me - can you justify (to yourself) that you need
both ways?
--
Paul Hankin
On 20 Okt, 16:21, Paul Hankin <paul.han...@gmail.comwrote:
The next stage in debugging is to think of a test that will prove your
guess right or wrong. I'd remove weakrefs from your event manager and
see if your code starts working.
I'd suggest you're a bit confused about your event manager's API: you
have register/deregister methods and are also using weakrefs to
provide auto-deregistering. I don't know your code, but this looks
like a mistake to me - can you justify (to yourself) that you need
both ways?
--
Paul Hankin
Yes, I did a test with a standard dict and that removed the bug,
should have mentioned that.
And, no, I'm not sure I need both. Currently I'm using the standard
dict.
I'm fairly sure I'll need to manually deregister sometimes, buttons
and whatnot, but automatic deregistration sounds nice for later when
I'll have hundreds of sprites flying around.
Odalrick wrote:
I'm trying to write a simple game and decided I need an eventmanager.
<code>
import weakref
from collections import defaultdict
class _EventManager( object ):
def __init__( self ):
self._handled_events =
defaultdict( weakref.WeakKeyDictionary )
def register( self, handler, event_type, filter=None ):
self._handled_events[event_type][handler] = filter
def deregister( self, handler, event_type ):
self._handled_events[event_type].pop( handler, None )
def handle_event( self, event ):
event_type = event.type
for handler, filter in
self._handled_events[event_type].items():
if filter == None or filter(event):
handler( event )
eventmanager = _EventManager()
__all__ = [ eventmanager ]
</code>
Fairly simple, yet there was some strange bug that prevented my game
from exiting.
I think what happened was that when __init__ ends, self goes out of
scope, and by extension so does self.handle_quit, Now there are no
more refeences to self.handle_quit, because weakrefs don't count, and
the event gets automatically dropped from my eventmanager. I thought
that wouldn't happen because handle_quit is part of the class and
instance MainGame.
No, self is yet another reference to the _EventManager instance which
survives the __init__() call because it is also referenced by the
global variable eventmanager.
On the other hand, self.handle_quit creates a new bound-method object every
time which doesn't even live as long as __init__().
Am I right in my guess? If so, how should I adress this bug? If not,
what is the bug?
The easiest option, to forget about weakrefs, seems to be the best
here. The other option is to keep a reference to the bound method, e. g.:
class MainGame(object):
def __init__(self, ...):
# put a bound method into the MainGame instance
# you can use a different attribute name if you want
hq = self.handle_quit = self.handle_quit
# register it
eventmanager.register(hq, ...)
Peter This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics
by: Ames Andreas (MPA/DF) |
last post by:
Hi all,
I'm using python 2.1 and can't easily upgrade (Zope). I'm using the
Queue module to synchronize/communicate between two threads and
weakref.proxy objects to avoid cycles. Scenario:
...
|
by: ali |
last post by:
i've seen a lot of times in programs but until now i still dont know the use
of the weakref module... any help will be appreciated... thanks...
ali
|
by: Mathias Mamsch |
last post by:
Hi,
I have some confusion concerning the weakref module.
I am trying to save a weak reference to a bound member function of a class
instance for using it as a callback function. But I always...
|
by: Mike C. Fletcher |
last post by:
I'm looking at rewriting parts of Twisted and TwistedSNMP to eliminate
__del__ methods (and the memory leaks they create). Looking at the docs
for 2.3's weakref.ref, there's no mention of whether...
|
by: bearophileHUGS |
last post by:
This is yet another memoize decorator, it's meant to be resilient (and
fast enough):
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/466320
Like most memoize decorators it stores the...
|
by: John Nagle |
last post by:
Is there some way to get a strong ref to the original object back
from a weakref proxy object? I can't find any Python function to do this.
".ref()" doesn't work on proxy objects.
John Nagle
|
by: Kira Yamato |
last post by:
It is erroneous to think that const objects will have constant behaviors too.
Consider the following snip of code:
class Person
{
public:
Person();
string get_name() const
|
by: George Sakkis |
last post by:
I'm baffled with a situation that involves:
1) an instance of some class that defines __del__,
2) a thread which is created, started and referenced by that instance,
and
3) a weakref proxy to the...
|
by: Ripter |
last post by:
I found this script at http://www.pygame.org/wiki/LazyImageLoading?parent=CookBook
And I can't quite figure out how it works. I was wondering if someone
could clarify it for me.
The Code is:
...
|
by: BarryA |
last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
|
by: nemocccc |
last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
|
by: Sonnysonu |
last post by:
This is the data of csv file
1 2 3
1 2 3
1 2 3
1 2 3
2 3
2 3
3
the lengths should be different i have to store the data by column-wise with in the specific length.
suppose the i have to...
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
|
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers,...
|
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
|
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new...
| |