Monday, August 19, 2013

A moment of dirty programming

It could have more to do with the fact that when I was formally schooled in the ways of programming that the teaching language at my college was Java, and Java can be a nit-picky little bastard at times that comes with object oriented practices and static casting drilled into would-be programmers that has me feeling a little... well, off.

At the moment it revolves around the concept of dynamic type-casting.  While in Java you had to tell the complier specifically what type of value a variable was going to store (static typing), the Python interpreter simply assumes what a variable's type is based on how it is being used on a given line (dynamic typing).  Not the first language to be this way, but for the most part, as par instruction from school, its usually a good idea to, even in a dynamically typed language, to not have a variable be reassigned from being a number to a string for example.  The fear being of using the variable in a point of the program as string when the algorithm requires an integer or a float.

Course, today, its using an integer as a boolean.  Here's the naughtiness:

    def parseEvent (self,event):
        if event.type == KEYDOWN:
            if event.key == K_UP:
                self.direction = "back"
                self.moveDown(-1)
                self.motion ++
            elif event.key == K_DOWN:
                self.direction = 'front'
                self.moveDown(1)
                self.motion ++
            elif event.key == K_LEFT:
                self.direction = 'left'
                self.moveAcross(-1)
                self.motion ++
            elif event.key == K_RIGHT:
                self.direction = 'right'
                self.moveAcross(1)
                self.motion ++
        elif event.type == KEYUP:
            self.motion = 0

    def update (self):
        if self.motion:
            self.image = self.sprite_images[direction+"_"+"walk"+self.motion%2]
        else:
            self.image = self.sprite_images[direction+"_standing"]


So, to explain.  The variable motion is a counter that is measuring state, which, when redrawing the sprite, is used to determine which arch in the walking motions are to be drawn.  If motion equals zero then it is assumed that the character isn't moving at all, and therefore the sprite frame for standing still is drawn.

So, as you see, the motion variable is being used as a boolean.  Maybe not as bad as other examples floating around, though a piece of me can see that this was a bizarre solution to the problem involving redraw.

No comments:

Post a Comment