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 2006
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: DolphinDB |
last post by:
Tired of spending countless mintues downsampling your data? Look no further!
In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
|
by: Aftab Ahmad |
last post by:
Hello Experts!
I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
|
by: ryjfgjl |
last post by:
ExcelToDatabase: batch import excel into database automatically...
|
by: isladogs |
last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM).
In this month's session, we are pleased to welcome back...
|
by: isladogs |
last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM).
In this month's session, we are pleased to welcome back...
|
by: Vimpel783 |
last post by:
Hello!
Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
|
by: jfyes |
last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
|
by: ArrayDB |
last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
|
by: PapaRatzi |
last post by:
Hello,
I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
| |