title: Add collision detection to a plattformer in pygame
body: <p>I'm working on a small platformer game in which you place blocks to make a level, then play it.</p>
  
  <p>I got gravity, jumping, and left and right movement.. but I am not sure how to make the player collide with walls when moving left or right.</p>
  
  <p>The way I want it to work is like this-</p>
  
  <p><code>if key[K_LEFT]:</code></p>
  
  <p><code>if not block to the left:</code></p>
  
  <p><code>move to the left</code></p>
  
  <p>How would I go about doing this (relative to this source):</p>
  
  <pre><code>import pygame,random
  from pygame.locals import *
  import itertools
  pygame.init()
  screen=pygame.display.set_mode((640,480))
  class Block(object):
      sprite = pygame.image.load("texture\\dirt.png").convert_alpha()
      def __init__(self, x, y):
          self.rect = self.sprite.get_rect(centery=y, centerx=x)
  
  class Player(object):
      sprite = pygame.image.load("texture\\playr.png").convert()
      sprite.set_colorkey((0,255,0))
      def __init__(self, x, y):
          self.rect = self.sprite.get_rect(centery=y, centerx=x)
  
  blocklist = []
  player = []
  colliding = False
  
  while True:
      screen.fill((25,30,90))
      mse = pygame.mouse.get_pos()
      key=pygame.key.get_pressed()
  
      if key[K_LEFT]:
          p.rect.left-=1
      if key[K_RIGHT]:
          p.rect.left+=1
      if key[K_UP]:
          p.rect.top-=10
  
      for event in pygame.event.get():
          if event.type == QUIT: exit()
  
          if key[K_LSHIFT]:
              if event.type==MOUSEMOTION:
                  if not any(block.rect.collidepoint(mse) for block in blocklist):
                      x=(int(mse[0]) / 32)*32
                      y=(int(mse[1]) / 32)*32
                      blocklist.append(Block(x+16,y+16))
          else:
              if event.type == pygame.MOUSEBUTTONUP:
                  if event.button == 1:
                      to_remove = [b for b in blocklist if b.rect.collidepoint(mse)]
                      for b in to_remove:
                          blocklist.remove(b)
  
                      if not to_remove:
                          x=(int(mse[0]) / 32)*32
                          y=(int(mse[1]) / 32)*32
                          blocklist.append(Block(x+16,y+16))
  
                  elif event.button == 3:
                      x=(int(mse[0]) / 32)*32
                      y=(int(mse[1]) / 32)*32
                      player=[]
                      player.append(Player(x+16,y+16))
  
      for b in blocklist:
          screen.blit(b.sprite, b.rect)
      for p in player:
          if any(p.rect.colliderect(block) for block in blocklist):
              #collide
              pass
          else:
              p.rect.top += 1
          screen.blit(p.sprite, p.rect)
      pygame.display.flip()
  </code></pre>