Please enable JavaScript to use CodeHS

Pygame with Karel - Part 2

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.

Create Tennis Balls

Now that you have the player, Karel, added to the game, it’s time to add some falling tennis balls for Karel to catch.

You’ll create just one tennis ball game object, but the program will reposition that game object after it’s either been caught by Karel or falls past Karel.

If you recall, you created init, update, and draw functions within your player class or Karel game object. You’ll do the same for the tennis ball game object, but add one more function to tell the computer what to do with the tennis ball if Karel catches it.

class tennis_ball(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__() 
        self.image = pygame.image.load("tennis_ball.png")
        self.rect = self.image.get_rect()
        self.rect.center = (random.randint(40, WIDTH - 40), 0)

    def update(self):
        self.rect.move_ip(0, 10)
        if (self.rect.bottom > HEIGHT):
            self.rect.top = 0
            self.rect.center = (random.randint(40, WIDTH - 40), 0)

    def caught(self):
        self.rect.center = (random.randint(40, WIDTH - 40), 0)

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

ball = tennis_ball()
Python

Let’s break down each of the functions in the tennis_ball class.

  • Lines 2-6: This initializes the tennis ball game object by loading the tennis ball sprite image. Similar to your Karel game object, the code on lines 5-6 creates an invisible rectangle around the tennis ball game object. This rectangle positions the tennis ball at a random x-axis location at the top of the game world. The rectangle will also be used in Part 3 of this tutorial to handle collisions.

    (You can download the tennis ball sprite to use in your program if you haven’t already.)

  • Lines 8-12: This is the update function for the tennis ball. Line 9 continuously increases the ball’s y-axis position by 10 pixels. This creates the illusion that the tennis ball is falling. Lines 10-12 state that if the tennis ball goes beyond the height of the game world, then the rectangle should be repositioned at a random x-axis location at the top of the game world. This makes it look like a new tennis ball is falling from a different location each time the tennis ball reaches the bottom of the game world.

  • Lines 14-15: The caught function is unique to the tennis ball game object. This also repositions the tennis ball at the top of the game world, but only occurs when the function is called. This will be used later in Part 3 when you create the collision system for your game.

  • Lines 17-18: Similar to your Karel game object, the draw function will draw the image or tennis ball sprite at the invisible rectangle’s position on the screen or display surface.

  • Line 20: This statement assigns the ball variable to the tennis_ball class. It can be added at the end of the class or at the end of both classes in the code - along with the karel variable.

Add a HUD and Update Game Loop

A heads-up display (HUD) gives information during the game to the player. For our Karel Pygame, you’ll create a basic HUD that shows the number of tennis balls the player has caught with Karel and the time remaining to catch tennis balls.

Karel Pygame HUD


You’ll use the variable font that you defined earlier in the program.

font = pygame.font.SysFont("Roboto", 30)
Python


Let’s take a look at the new code you’ll add to the game loop to manage the tennis ball game object and HUD text elements.

    ball.update()

    ball.draw(screen)
    shown_time = math.floor(timer / 100)
    clock_timer = font.render('Timer = ' + str(shown_time), True, black)
    screen.blit(clock_timer, (WIDTH - 140, 10))
    scores = font.render('Tennis Balls = ' + str(score), True, black)
    screen.blit(scores, (10, 10))

    timer -= 1
Python
  • Lines 1 & 3: The ball.update() statement is added to the game loop near the karel.update() statement. Like Karel, you also have to draw the ball to the game surface after the object is updated. So you add the ball.draw(screen) statement. This draws the tennis ball onto screen or the display surface.

  • Line 4: The variable shown_time is assigned the value of the earlier defined timer variable divided by 100. The result of this division is rounded down to the nearest integer using math.floor() from the math module you imported at the start of the program.

  • Lines 5 & 7: These statements define new variables for the two text elements in the HUD. The first is a clock_timer assigned the result of Pygame’s font.render() function. It passes an argument for the text to be displayed (along with the values of our shown_time and score variables), a Boolean value for whether or not the text should have anti-aliasing, and the color of the text. Because you defined some color variables early on in your program, you can just type the name of the color here.

  • Lines 6 & 8: After each variable for the two text elements, a screen.blit() Pygame function allows you to place the defined text on the game screen. The two arguments passed are the text variable and the x- and y-positions of the top-left corner of that text.

  • Line 10: The game loop updates everything with every frame. This statement decrements or subtracts 1 from the timer variable defined at the start of the program.

Let’s give all this new game loop code a try with our new tennis ball game object.

Awesome! Now you have Karel moving side-to-side with the mouse cursor, a falling tennis ball, and a heads-up display (HUD) in your game world. Next you’ll want to add a collision system to update the HUD and award points when Karel catches each falling tennis ball. For that, proceed to Part 3 of the tutorial series.