Rectangle collision in pygame? (Bumping rectangles into each other)
<p>I decided to move that Squarey game to pygame, and now I have 2 rectangles that can move around and bump into the walls. However, the rectangles can move right through each other. How would I make them bump into each other and stop?
My code:</p>

<pre><code>import pygame

pygame.init()
screen = pygame.display.set_mode((1000, 800))
pygame.display.set_caption("Squarey")
done = False
is_red = True
x = 30
y = 30
x2 = 100
y2 = 30
clock = pygame.time.Clock()

while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True
        if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
            is_red = not is_red

    pressed = pygame.key.get_pressed()
    if pressed[pygame.K_UP]: y -= 3
    if pressed[pygame.K_DOWN]: y += 3
    if pressed[pygame.K_LEFT]: x -= 3
    if pressed[pygame.K_RIGHT]: x += 3
    if pressed[pygame.K_w]: y2 -= 3
    if pressed[pygame.K_s]: y2 += 3
    if pressed[pygame.K_a]: x2 -= 3
    if pressed[pygame.K_d]: x2 += 3

    if y &lt; 0:
        y += 3
    if x &gt; 943:
        x -= 3
    if y &gt; 743:
        y -= 3
    if x &lt; 0:
        x += 3

    if y2 &lt; 0:
        y2 += 3
    if x2 &gt; 943:
        x2 -= 3
    if y2 &gt; 743:
        y2 -= 3
    if x2 &lt; 0:
        x2 += 3

    screen.fill((0, 0, 0))
    if is_red: color = (252, 117, 80)
    else: color = (168, 3, 253)
    if is_red: color2 = (0, 175, 0)
    else: color2 = (255, 255, 0)
    rect1 = pygame.draw.rect(screen, color, pygame.Rect(x, y, 60, 60))
    rect2 = pygame.draw.rect(screen, color2, pygame.Rect(x2, y2, 60, 60))
    pygame.display.flip()
    clock.tick(60)

pygame.quit()
</code></pre>

<p>To check for collisions, try something like this:</p>

<pre><code>def doRectsOverlap(rect1, rect2):
      for a, b in [(rect1, rect2), (rect2, rect1)]:
          # Check if a's corners are inside b
          if ((isPointInsideRect(a.left, a.top, b)) or
              (isPointInsideRect(a.left, a.bottom, b)) or
              (isPointInsideRect(a.right, a.top, b)) or
              (isPointInsideRect(a.right, a.bottom, b))):
               return True

      return False

  def isPointInsideRect(x, y, rect):
      if (x &gt; rect.left) and (x &lt; rect.right) and (y &gt; rect.top) and (y &lt; rect.bottom):
          return True
      else:
          return False
</code></pre>

<p>Then, while moving them, you can call</p>

<pre><code>if doRectsOverlap(rect1, rect2):
    x -= 3
    y -= 3
    rect1 = pygame.draw.rect(screen, color, pygame.Rect(x, y, 60, 60))
</code></pre>

<p>Or something like that.</p>

python pygame collision rectangles