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_e vents =
defaultdict( weakref.WeakKey Dictionary )
def register( self, handler, event_type, filter=None ):
self._handled_e vents[event_type][handler] = filter
def deregister( self, handler, event_type ):
self._handled_e vents[event_type].pop( handler, None )
def handle_event( self, event ):
event_type = event.type
for handler, filter in
self._handled_e vents[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_qui t, Now there are no
more refeences to self.handle_qui t, 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.re gister( self.handle_qui t, pygame.QUIT )
eventmanager.re gister( self.handle_qui t, pygame.KEYDOWN,
key_filter( pygame.K_ESCAPE ) )
def mainloop( self ):
handle_event = eventmanager.ha ndle_event
self.quit_game = False
while not self.quit_game:
for event in pygame.event.ge t():
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_ev ent( event ):
print str( event )
if __name__ == "__main__":
game = MainGame()
game.mainloop()
</code> 3 2025
On Oct 20, 2:47 pm, Odalrick <odalr...@hotma il.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_e vents =
defaultdict( weakref.WeakKey Dictionary )
def register( self, handler, event_type, filter=None ):
self._handled_e vents[event_type][handler] = filter
def deregister( self, handler, event_type ):
self._handled_e vents[event_type].pop( handler, None )
def handle_event( self, event ):
event_type = event.type
for handler, filter in
self._handled_e vents[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_qui t, Now there are no
more refeences to self.handle_qui t, 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...@gm ail.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_e vents =
defaultdict( weakref.WeakKey Dictionary )
def register( self, handler, event_type, filter=None ):
self._handled_e vents[event_type][handler] = filter
def deregister( self, handler, event_type ):
self._handled_e vents[event_type].pop( handler, None )
def handle_event( self, event ):
event_type = event.type
for handler, filter in
self._handled_e vents[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_qui t, Now there are no
more refeences to self.handle_qui t, 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_qui t 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_qui t = self.handle_qui t
# register it
eventmanager.re gister(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:
thread1:
- is the sole consumer (non-blocking get)
- holds the reference to the queue
|
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 get dead
references, when I try to create a reference to a bound member function. It
seems as if an instance of a class owns no reference to its memberfunctions,
so the the reference count is always zero. How can I come behind that?
|
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 the callbacks are
held with a strong reference. My experiments suggest they are not...
i.e. I'm trying to use this pattern:
class Closer( object ):
"""Close the OIDStore (without a __del__)"""
def __init__( self, btree ):
"""Initialise the...
|
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 pairs of data-result in
cache dictionary, but Garrett Rooney says:
it could be better if it used the new weak references from python 2.1.
The way it works now, the cached values will be stored forever, and
will never be garbage collected. This is...
| |
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 instance that is passed to the thread
instead of 'self', to prevent a cyclic reference.
This probably sounds like gibberish so here's a simplified example:
==========================================
|
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:
import pygame
import weakref
class ResourceController(object):
def __init__(self, loader):
|
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
|
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
| |
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
|
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
| |
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |