Input/Output engine

Well I’m releasing some of my code so I can reuse bits for the next pyweek. Today’s bit of code is rather simple but I find it quite useful. It’s basically a simple processor and holder for pygame even information. The nice thing is it has lists for certain events that you can pass to a function whole or check anytime without preventing another piece of code from doing that.

The codes been strongly documented but I can annotate or update as needed.


Unfortunately I can’t wordpress to make everything look pretty yet but here’s the source file

from pygame.locals import *

class ioe:
    def __init__(self):
        #Creates local variables
        self.reset()

    def update(self,events):
        """Dump the event list from pygame and it will sort them
        into lists for up, pressed, down, quit and user.When an
        up event is processed that key is removed from the
        pressed list and vice versa for down events."""

        #for every key released add the key to the up list
        self.up=[k.key for k in events if k.type==KEYUP]

        #for each key in the up list, filter those keys from the pressed list
        for i in self.up:
            self.pressed=[x for x in self.pressed if x != i]

        #fill the down list the same way as the up list
        self.down=[k.key for k in events if k.type==KEYDOWN]

        #If a key is pushed down then it is being pressed until it is let up
        self.pressed+=self.down

        #quit and user actions don't have key values so
        #they are just added directly to respective lists
        self.quit=[k for k in events if k.type==QUIT]
        self.user=[e for e in events if e.type==USEREVENT]

    def reset(self):
        """Empties all the lists. Use this when going back to a
        menu otherwise keys could be stuck in the pressed list."""

        #clears all the lists by setting them equal to an empty list.
        self.up=[]
        self.down=[]
        self.pressed=[]
        self.quit=[]
        self.user=[]

And that’s it.