CODE WITH MARTIN

PyGame


Introduction

PyGame is a package used for developing games with Python. You'll need to install the package using 'pip3 install pygame' to get started with the code below.

The example code below shows how we can draw and move a bouncing ball around the screen.

The Code

import sys, pygame

pygame.display.init()

size = width, height = 800, 600
speedX = 1
speedY = 1
background = 0, 0, 0
x = 1
y = 1

screen = pygame.display.set_mode(size)
pygame.display.set_caption("Bouncing Ball")

clock = pygame.time.Clock()

while 1:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    deltaTime = clock.tick(100)
    deltaTime = min(20.0, deltaTime)
    
    # Move the ball position by the speed values.
    x += speedX * deltaTime
    y += speedY * deltaTime

    # Check if the ball is hitting the edges of the screen and change
    # the speed direction if it does hit.
    if x < 0:
        x = 0
        speedX = 1
    if x > width:
        x = width
        speedX = -1

    if y < 0:
        y = 0
        speedY = 1
    if y > height:
        y = height
        speedY = -1

    # Clear the screen, render the ball and display.
    screen.fill(background)
    pygame.draw.circle(screen, (255,0,0), (x,y), 10)
    pygame.display.flip()

Challenges

1. Can you change the code so that we can see 2 bouncing balls on the screen travelling at different speeds?

2. Can you further change the code so that we can see 10 bouncing balls, all at different speeds and different colours?

3. Can you show 100 bouncing balls, all with differing speeds and colours?

You can read more about PyGame at https://www.pygame.org/docs/.