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.
Prerequisite: It’s recommended that you complete the CodeHS Introduction to Computer Science in Python 3 course prior to starting this tutorial series.
Some game engines and libraries contain a built-in collision system. The Pygame module includes a collider system that can check for a number of different overlaps between game objects. In your Karel catching game, you’ll use the rectangle collider for sprites pygame.sprite.collide_rect
to detect whether or not the invisible rectangle around the Karel sprite is overlapping any portion of the invisible rectangle around the tennis ball sprite. This is sometimes referred to as a 2D box collision and often lies within the game loop.
Line 1: Using the sprite.collide_rect
function, the program checks for overlapping rectangles of your karel
and ball
game objects, passed to the function. It also checks to see if the game is running or if the Game Over screen is showing.
Line 2: If both of the conditionals in Line 1 are true, then increment or add 1 to the score
variable. This variable controls the number of tennis balls caught in the game’s HUD.
Line 3: Then run the ball.caught()
function you established earlier when constructing the tennis ball sprite.
Finally, you’ll need a Game Over screen that’ll appear when the timer reaches zero. This screen is fairly basic, but you can modify it with different colors and fonts if you prefer.
Within the game loop, this if statement checks the value of timer
. If it’s less than zero, then the succeeding commands run.
Lines 2-3: This sets running
to false, meaning that the game is no longer in play. The screen is filled in with the color black.
Lines 4-5: These lines assign the variables game_over
and scores
to fonts and text that will render on the screen. font_large.render
uses the font established earlier as the font_large
font and establishes the text and color that should be shown.
Lines 6-7: Using screen.blit
, the text assigned to the variables in Lines 4-5 are rendered to the screen. The parameters establish the variable to use for the text and position of the text, using x- and y-axes, in pixels.
Once this Game Over screen if statement is added to the end of the game loop, your tennis ball catching game is ready to play! Try it out and make any adjustments necessary.
Terrific! You’ve created your first game using the Pygame module. Learn how to create other types of games in Python by reviewing the Pygame Documentation.