I'm making a Mario clone in pygame and I have just wrote a function proccesses inputs and acts as a state machine for Mario. Everything is working just as I want it, but I was wondering if you can think of any more efficient way to write this code.
A note that these methods are all a part of a class called mario
.
def __init__(self):
#The inputs currently binded to each of marios actions.
self.keybinds = {
'right': K_RIGHT,
'left' : K_LEFT,
'jump' : K_z,
'spd' : K_LSHIFT
}
# The current state mario is in.
# Valid states: 'stand', 'air', 'death'.
self.state = 'stand'
# The current action mario is doing.
# Valid actions: 'none', 'walk', 'run', 'jump'.
self.action = 'none'
# The current direction mario is facing.
# Valid values: 'r', 'l'.
self.faceDir = 'r'
# The direction that the user wants mario to be moving in
self.des_dir = 'n'
# The current speed mario is moving at.
# Valid speeds: 'norm', 'fast'.
self.spd = 'norm'
# A boolean based on whether a character instance can jump.
self.canJump = True
self.crnt_mdx = 2.7 # The current max x velocity mario can move at.
self.slow_dx = 2.7 # The max x velocity mario can move at when he is walking.
self.fast_dx = 4.7 # The max x velocity mario can move at when he is running.
def processInput(self, keys, keyup):
#keys = a list of all keybord keys currently being pressed.
#I have imported a module that has a bunch of variables that represent each key.
#keyup = the current key that was just released, if any.
if keyup == self.keybinds['jump']:
self.canJump = True
if self.state == 'stand' or self.state == 'air':
if keys[self.keybinds['right']]:
self.moveHorz('r')
self.accelerate('r')
self.set_crnt_acc('r')
self.faceDir = 'r'
self.des_dir = 'r'
elif keys[self.keybinds['left']]:
self.moveHorz('l')
self.accelerate('l')
self.set_crnt_acc('l')
self.faceDir = 'l'
self.des_dir = 'l'
else:
if self.state == 'stand' and self.horzDir != 'n':
self.slowDown()
self.des_dir = 'n'
if self.state == 'stand':
if keys[self.keybinds['spd']]:
self.crnt_mdx = self.fast_dx
else:
self.crnt_mdx = self.slow_dx
if keys[K_z] and self.canJump:
self.canJump = False
self.action = 'jump'
else:
pass