title: Optimizing Keyboard Input in Pygame
body: <p>I am creating a very simple game using the pygame library in which the player moves a square around the screen with the arrow keys. Unfortunately, the response of the controls are proving to be a problem.</p>
  
  <p>The controls work fine until you switch direction e.g. left to right. When the player switches direction, the square the player is controlling jars to a halt.</p>
  
  <p>The code for the controls looks like this in my game:</p>
  
  <pre><code>def move(self, event):
      speed = 6
      if event.type == pygame.KEYDOWN:
          if event.key == pygame.K_LEFT:
              self.rect.x -= speed
          if event.key == pygame.K_RIGHT:
              self.rect.x += speed
          if event.key == pygame.K_DOWN:
              self.rect.y += speed
          if event.key == pygame.K_UP:
              self.rect.y -= speed
  </code></pre>
  
  <p>This method is located in a class called Block (I stole Block from the pygame docs) that just makes a sprite for the player alongside providing movement.</p>
  
  <p>The function move() is actually called inside the main.py file like this:</p>
  
  <pre><code>while going:
      clock.tick(60)
  
      # event handling
      for event in pygame.event.get():
          if event.type == QUIT:
              going = False
  
      # controller input
      player.move(event)
  </code></pre>
  
  <p>Where player is an instance of the Block class and event is just an item from the event queue of my game.</p>
  
  <p>I tried using the pygame.key.get_pressed function (which did work better) but I would rather use the pygame.KEYDOWN locals alternatively because it returns the key presses as events in the event queue rather than booleans returned from a list.</p>
  
  <p>If you are more investigative than your average joe you can take a look at the "full" game here: <a href="https://github.com/catmes/Project_React" rel="nofollow">https://github.com/catmes/Project_React</a></p>
  
  <p>You will need pygame 1.9.2 and python 2.7. Keep in my mind that the game itself is more a learning exercise so don't surprised when you see bad code (that will be fixed later of course ;) ).</p>
  
  <p>Thanks for stopping by and giving this question a peek, I do appreciate your time.</p>