leafleafleafDocy banner shape 01Docy banner shape 02Man illustrationFlower illustration

Writing a Pinball Game with Python Pygame

Estimated reading: 4 minutes 98 views

Combining what we have learned before, in this section, we use Pygame to write a small game – a pinball game.

In this game, we control the paddle by moving the mouse to bounce the pinball to score. You can click the left button of the mouse to make the bezel longer to reduce the difficulty of the game; you can also click the right button of the mouse to shorten the bezel to increase the difficulty of the game.

If the paddle doesn’t catch the pinball, the player loses a life, and when the player has zero lives, the paddle can no longer be moved. If you still want to play the game, you can click the F1 button to restart the game. Lives and scores are displayed at the top of the window, and we’ve also added background music to the game.

The complete code is as follows.

import pygame # import the pygame module
pygame.init() # create pygame
screen = pygame.display.set_mode([800,600]) # create a window
# create color constants
WHITE = (255,255,255)
BLACK = (0,0,0)
ball = pygame.image.load("ball.png") # load the image of the pinball
ballx = 0 # X coordinate of the pinball
bally = 0 # Y coordinate of the ball
speedx = 5 # The pinball moves pixels in the X coordinate direction
speedy = 5 # The pinball moves pixels in the Y coordinate direction
paddlew = 100 # width of the paddle
paddleh = 15 # height of the paddle
paddlex = 300 # X coordinate of the paddle
paddley = 570 # Y coordinate of the paddle
font = pygame.font.SysFont("SimHei", 24) # Set the font that supports Chinese
timer = pygame.time.Clock() #Create a Clock object
points = 0 # score
lives = 3 # number of lives
pop=pygame.mixer.Sound("sample.wav") # Load background music
pop.play() # play background music
# game loop
Running = True
while Running:
    # event loop        
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            Running = False
        if event.type==pygame.MOUSEBUTTONDOWN:
            # Press the left button, and when the baffle is less than 400, the baffle length is doubled
            if pygame.mouse.get_pressed()[0] and paddlew<400:
            # Press the right button and when the baffle is greater than 20, the length of the baffle is halved
            elif pygame.mouse.get_pressed()[2] and paddlew>20:
        if event.type==pygame.KEYDOWN:
            # Press F1 on the keyboard to restart the game
            if event.key==pygame.K_F1:
    #The number of lives is zero, stop the game           
    if lives==0:
        text = font.render("Game Over", True, WHITE)
        screen.blit(text, (350,270)) # Copy the text surface to the main surface
        pygame.display.update() # display text
        pop.stop() # stop music playback
        continue # end a single while loop
    ballx += speedx # move the X coordinate of the pinball
    bally += speedy # Y coordinate of moving the ball
    #If the pinball is beyond the left or right side of the window, flip the pinball direction       
    if ballx <= 0 or ballx + ball.get_width() >= 800:
        speedx = -speedx
    #If the pinball is beyond the bottom of the window, the number of health is reduced by 1, and the direction of the pinball is flipped
    if bally+ball.get_height()>=600:
        speedy = -speedy        
    #If the pinball is beyond the top of the window, flip the pinball direction
    if bally <= 0:
        speedy = -speedy
    screen.fill(BLACK) # Fill the Surface object with white
    screen.blit(ball, (ballx, bally)) # Copy the pinball surface to the main surface
    # draw and move the bezel
    paddlex = pygame.mouse.get_pos()[0] # X coordinate changes with mouse movement   
    pygame.draw.rect(screen, WHITE, (paddlex, paddley, paddlew, paddleh))
    # If the bottom of the pinball hits the pinball and the velocity is greater than 0, and half of the pinball's X coordinate falls on the baffle, the pinball can bounce
    if bally + ball.get_height() >= paddley and speedy > 0:
        if ballx + ball.get_width() /2 >= paddlex and ballx + ball.get_width() / 2 <= paddlex + paddlew:      
            points += 1 # add 1 to the score
            speedy = -speedy # Flip the pinball direction
    # draw lives and scores
    draw_string = "Life: " + str(lives) + " Score: " + str(points)
    text = font.render(draw_string, True, WHITE)
    text_rect = text.get_rect()
    text_rect.centerx = screen.get_rect().centerx
    text_rect.y = 10
    screen.blit(text, text_rect)
    pygame.display.update() # refresh
    timer.tick(60) # frame rate is 60fps
pygame.quit() # Quit the program

The knowledge points in this part of the code have been introduced before, and will not be specifically explained here. The result of running the program is shown in the figure below. Readers can experience this game by running this program to further deepen the understanding of what we have learned before.

Leave a Comment