How to detect boundary in Pygame

When we design a game first thing we need to do is to make sure our game character stays within the game boundary. In order to make sure our game character will move within the game boundary we will create a set of rule such as if the top-left corner of that game character moves pass the x or the y boundary of the screen then we will need to reset the coordinate for the top-left corner of that game character accordingly. Below script will create a bouncing ball which will change color randomly and moves within the boundary of the screen.

import pygame
from pygame.locals import *
from sys import exit

from random import *

screen = pygame.display.set_mode((640, 480), 0, 32)

clock = pygame.time.Clock()

x, y = 10., 10.
speed_x, speed_y = 100., 90.

circle_radius = 7
circle_pos = (int(x), int(y))

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
    random_color = (randint(100,255), randint(30,255), randint(155,255))
    screen.fill((255, 255, 255)), random_color, circle_pos, circle_radius)
    time_has_passed = clock.tick(30) #return the time delta after each frame
    time_has_passed_in_second = time_has_passed / 1000.0
    x += speed_x * time_has_passed_in_second
    y += speed_y * time_has_passed_in_second
    # If the ball goes off the edge of the screen,
    # reset it's position and then move it in the opposite direction
    if x > 640 - (circle_radius * 2):
        speed_x = -speed_x
        x = 640 - (circle_radius * 2)
    elif x < 0:
        speed_x = -speed_x
        x = 0.
    if y > 480 - (circle_radius * 2):
        speed_y = -speed_y
        y = 480 - (circle_radius * 2)
    elif y < 0:
        speed_y = -speed_y
        y = 0
    circle_pos = (int(x), int(y))

The script above also shows us that we can actually use the pygame.draw module to draw out our gaming character instead of loading graphic into the computer memory.

If you run the above script then you will see the below outcome!

Leave a Reply

Your email address will not be published. Required fields are marked *