Please enable JavaScript to use CodeHS

Pygame with Karel - Part 1

Learn about the Pygame Python module and how it can be used to create games in Python. In this tutorial series you'll use some basic Pygame functions to build a mouse-input game where Karel the dog catches falling tennis balls. Prerequisite: Knowledge of basic Python programming constructs including module imports.

By Matt Arnold

Curriculum Developer

Pygame Tutorials

  • Part One - Import Pygame and Add Karel
  • Part Two - Add Tennis Balls and HUD
  • Part Three - Collisions


Prerequisite: It’s recommended that you complete the CodeHS Introduction to Computer Science in Python 3 course prior to starting this tutorial series.

Pygame


Introduction

The Python programming language allows coders to import modules. These modules contain a set of definitions and statements. They can define functions, declare variables, and run snippets of code to make writing programs in Python easier. The Python standard library contains over 200 modules!

Pygame contains multiple Python modules that make it easier to program games. Pygame can even be combined with other imported modules - like math or random. Pygame is a free and open source Python module you can use to create platformers, puzzle games, role-playing games (RPG), and various other 2D and 3D games. Most games are distributed on the web, but they can also be played on handhelds and consoles.

Refer to the Pygame Documentation throughout this tutorial series to get more information on Pygame functions and usage.

Catch Game

You’re going to create a basic game using the Pygame module along with a few other modules. In this game, tennis balls will fall from random locations across the top of the screen. Players will use a mouse to move a Karel sprite (character image) side-to-side to catch as many falling tennis balls as possible before the time runs out.

Try out the game before you start writing your program!

Import Modules

Create a new Python 3 project in your CodeHS Sandbox. Before programming the game, you’ll import some modules you’ll use in the program. All modules are imported at the beginning of your program.

# Import pygame module and local modules
import pygame
from pygame.locals import *

# Need to import os module to avoid audio driver issues
import os
os.environ['SDL_AUDIODRIVER'] = 'dsp'

# Import random and math standard Python modules
import random
import math

# Initialize the Pygame modules
# this must be done to activate the Pygame modules
pygame.init()
Python

Define Colors and Fonts

Next you’ll define some colors using RGB values and couple of font variations - a regular and large font. The only difference between these two fonts will be the size.

# Define some colors using RGB values
green = (211, 237, 218)
black = (0, 0, 0)
white = (255, 255, 255)

# Set up regular and large fonts
font = pygame.font.SysFont("Roboto", 30)
font_large = pygame.font.SysFont("Roboto", 50)
Python

Screen Size and Additional Variables

The screen, or display surface, needs to be established. Pygame can get the display’s information, including width and height, and assign those to the width and height of the game world.

In this next code snippet, you’ll set the game world’s width and height based on the screen size, add some variables to keep score, track the state of the game, and run a timer. Lastly, you’ll set the frames per second (FPS) variable to the clock frame rate.

# Initialize the screen size and set to fullscreen
# The screen is sometimes referred to as the display surface
screen_info = pygame.display.Info()
WIDTH = screen_info.current_w
HEIGHT = 350   # You can set this to 'screen_info.current_h' for the full height
screen = pygame.display.set_mode((WIDTH, HEIGHT), pygame.FULLSCREEN)

# Some additional variables for keeping score, states, and a timer
timer = 2000
score = 0
running = True

# Set a frame-rate limitation
FPS = pygame.time.Clock()
Python

Create the Karel Game Object

For this game, you’ll use two sprites, an image or animation of a game character or object. You’ll create a player character using a Karel sprite. In Part 2 of this tutorial series, you’ll add the tennis ball sprite. Download each sprite file below and upload them to your project. You’ll link to these image files in your code.


Karel Sprite    Download Karel Sprite

  Tennis Ball Sprite     Download Tennis Ball Sprite


Each game object will be created as a Python class and include three crucial video game programming elements - the initialization, update, and render or draw information for that game object. These will be used later in the program’s game loop to tell the computer how to handle each game object every time the frame or screen refreshes.

Let’s start by adding Karel as a game object to your game!

class player(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__() 
        self.image = pygame.image.load("karel.png")
        self.rect = self.image.get_rect()
        self.rect.center = (WIDTH / 2, HEIGHT - 70)

    def update(self):
        mouse_position = pygame.mouse.get_pos()[0]
        self.rect.center = (mouse_position, HEIGHT - 70)

    def draw(self, screen):
        screen.blit(self.image, self.rect)

karel = player()
Python

There’s a lot going on for the Karel game object. Let’s break it down.

  • Line 1: The class player is established and uses the Pygame sprite function to set it up.

  • Lines 2-6: These lines initialize the sprite as an image loaded from your program files. It also constructs an invisible rectangle around the image. This rectangle will be used to reposition Karel whenever the sprite is updated on the screen and check for collisions with falling tennis balls. The invisible rectangle also needs centered with the Karel image. That happens on line 6.

    You’ll notice that self is used to call on the player object. They’re followed by a method and sometimes a Pygame function.

  • LInes 8-10: This is the update function for the player game object. Again, self refers to the player object. The update function uses a Pygame function to grab the x-axis position of the player’s mouse cursor on the screen. The x-axis is stored in a Pygame array as index [0]. Then the invisible rectangle is repositioned to match the x-axis position of the mouse cursor. The y-axis is a constant at 70 pixels above the height of the playing field or screen. This update function lets the player move Karel from side-to-side during gameplay.

  • Lines 12-13: Finally you need to draw or render the Karel character on the game screen. The draw function passes data from the self (or the game object) and screen objects to render the image in the game world. This is done with each iteration of the game loop or each frame. You use Pygame’s blit function in order to draw the image onto the screen or display surface. It passes the arguments for the image that should be used and the position of the invisible rectangle as the image’s destination.

  • Line 15: To call the Karel game object in the game loop later, let’s make things a little easier by assigning the player object to the variable karel.

Game Loop

Every video game has at least one game loop. This loop checks the program for any updates to game objects and renders the game to the screen each frame.

For this game, you’ll use a while loop that only ends in the event the player quits the game. This will be coded in a for loop at the start of the game loop.

# Game loop
while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()

    karel.update()

    screen.fill(green)
    karel.draw(screen)

    pygame.display.update()
    FPS.tick(60)
Python

Let’s take a deeper look at what’s going on within the game loop.

  • Lines 3-5: This is the for loop that checks to see if the player has quit the game. If they do, then Pygame quits the program.

  • Line 7: Calls on the update function within the karel game object. Remember this is the same as the player class.

  • Lines 9-10: Fills the gameplay screen with the color green and draws or renders the karel game object to the screen.

  • Lines 12-13: This calls the Pygame update function in the display object. Lastly the FPS (frames per second) is set to 60fps using the Pygame tick function.


Now that you’ve established the game world, set up the game loop, and added your first game object, let’s test out the program so far!

Great! Now you have Karel moving side-to-side with the mouse cursor in your game world. To add the tennis ball game object, proceed to Part 2 of the tutorial series.