pygame: The Bouncing Blocks Algorithm

doRectsOverlap and isPointInsideRect:
Collision detection is figuring when two things on the screen have touched (that is, collided with) each other. For example, if the player touches an enemy they may lose health. Or the program needs to know when the player touches a coin so that they automatically pick it up. Collision detection can help determine if the game character is standing on solid ground or if there’s nothing but empty air underneath them.

In our games, collision detection will determine if two rectangles are overlapping each other or not. Our next example program will cover this basic technique.

overlapping-rectangles

Later in this chapter, we’ll look at how our Pygame programs can accept input from the user through the keyboard and the mouse. It’s a bit more complicated than calling the input() function like we did for our text programs. But using the keyboard is much more interactive in GUI programs. And using the mouse isn’t even possible in our text games. These two concepts will make your games more exciting!

Source Code of the Collision Detection Program
Much of this code is similar to the animation program, so the explanation of the moving and bouncing code is skipped. (See the animation program in the Animating Graphics Chapter for that.) A block will bounce around the window and bounce off each other.

On each iteration through the game loop, the program will read each Rect object in the list and the blocks will have a reaction.

The block is represented by a dictionary. The dictionary has a key named ‘rect’ (whose value is a pygame.Rect object) and a key named ‘dir’ (whose value is one of the constant direction variables like we had in last chapter’s Animation program).

overlapping-rectanglesVert

Use the functions below to make the block react differently when they are close to each other.

## BouncingBlocks.py

## copy the animation.py 

import pygame, sys, random
from pygame.locals import *

## add these two functions 

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 > rect.left) and (x < rect.right) and (y > rect.top) and (y < rect.bottom):
        return True
    else:
        return False

How to use the functions:

      if b['rect'].right > WINDOWWIDTH+15:
            # block has moved past the right side
            
            if b['dir'] == DOWNRIGHT:
                b['dir'] = DOWNLEFT
            if b['dir'] == UPRIGHT:
                b['dir'] = UPLEFT


        ##### add the call to the doRectsOverlap by pairs of blocks
        ##### Make sure the indentations make sense!!!
       if doRectsOverlap(b3['rect'], b2['rect']):
          if b3['dir'] == UPLEFT:
                b3['dir'] = DOWNLEFT
           if b3['dir'] == UPRIGHT:
                b3['dir'] = DOWNRIGHT

       #### what other pairs do you want to check for overlaps??? 

        # draw the block onto the surface
        pygame.draw.rect(windowSurface, b['color'], b['rect'])

  # draw the window onto the screen
    pygame.display.update()
    time.sleep(0.02)