Task 1: Set Up

Goal: Create a file and initialise pygame.

Task 1.1: Make Python File

  1. In VS Code, click on File and then New File

    File

    New File

    You should see something like this pop up after you click 'New File' Pop Up

  2. Enter the name of your file (e.g. 'my_game.py') my_game.py

    Note: It’s super important to include .py at the end of the file name so VS Code knows it's Python code!
  3. Press 'ENTER' and something looks like this should pop up my_game.py

  4. Press 'Desktop' and then 'Create File' to save your file to the Desktop

  1. Congratulations! You have created you python file! You can now start coding :)

my_game.py

Task 1.2: Import Pygame

Now that you have created your Python file, it's time to start setting it up for Pygame!

  1. At the very top of your Python file, you need to import the Pygame library.

  2. Initialising Pygame

You should now see something like this:

Pygame Init

Task 2: Creating a game screen

Goal: Create a visible game screen with a background, title, icon and a game loop.

Task 2.1: Create Game Screen

Before we make our game we need to set up the screen to display it!

  1. Create some variables that will hold the width and the height. 800 pixels wide and 600 pixels tall

    E.g. A screen that is 100 pixels wide and 200 pixels could have these variables:

        WIDTH = 100
        HEIGHT = 200
    
  2. Create a window of that size and assign it to screen like so:

pygame.display.set_mode((WIDTH, HEIGHT))

πŸ“ Note

Running your game will cause your program to crash. You must complete Task 1.2 before you can see a screen when you run your pygame.


🚩 Checkpoint

  • Two variables for width and height
  • A screen object created using Pygame and your variables

Task 2.2: Create Game Loop

  1. Use a variable called running and set it to True
  2. Make a while loop underneath this variable which will keep looping while the game is running
  3. Inside your while running: loop, loop through each event type and if the event type is quit, close the game.
  4. At the end of your while loop, refresh the screen with pygame.display.update()

πŸ’‘ Hints

  • Looping through each event type: for event in pygame.event.get()
  • If the player closes the game event.type == pygame.QUIT, you need to set a certain variable to False

🚩 Checkpoint

  • No crashing! Your window should stay open until you click the X!
  • You should see something like this:

Task 2.3: Add Background Image

  1. Save the image path as a variable: e.g.background_image = "images/background/wooden_floor.jpeg"
  2. Then load it using background = pygame.image.load(background_image)
  3. Make sure the background fits the window use background = pygame.transform.scale(background, (size_x, size_y))
  4. Draw the background onto the screen use screen.blit(background, (0,0))

πŸ’‘ Note

Make sure you add your background image before the game loop!

Try adding your own image! JPEGs are preferable since they don't get as blurry when you zoom in on them.


🚩 Checkpoint

  • A background_image variable (path to the image)
  • A background variable (the scaled loaded image)
  • A screen.blit(variable, coordinate) line outside your while running: loop
  • A background showing up instead of a black screen!

Task 2.4: Add a Game Title and App Icon

  1. Change the text that appears at the very top of your game window use a Pygame function pygame.display.set_caption("My game").
  2. Load an image using icon = pygame.image.load("images/game_icon.png")
  3. Use the Pygame function pygame.display.set_icon(icon) to set the image.

🚩 Checkpoint

  • Have your customised game title
  • Have your customised icon

Task 3: Making a player

Goal: Make a player that can move and be seen on the screen.

Task 3.1: Create a Player Class

Classes, also known as objects, work like a blueprint. Every class can have properties and methods. For example, a car class can have the properties colour = red and the methods drive(). Typically we name our class with capital letters, e.g. class Car or class Bird.

  1. Create a Player class to store the player’s position, size and image (sprite)
  2. Inside your Player class, create an __init__() method.

πŸ’‘ Hint

  • Generally, you can make a class in Python like so:
  • 
    class Car:
        def __init__(self, colour, speed):
            colour = colour
            speed = speed
            

🚩 Checkpoint

  • A Player class
  • An __init__() method inside the class
  • Player properties:
    • position_x
    • position_y
    • size
    • image
    • sprite

Task 3.2: Create an instance of player

If a class is a blueprint, then creating an instance is using that blueprint to make something!

  1. Outside of your class definition (in your main code), create a new player object!

πŸ’‘ Hint

  • Generally, you can create a class instance like so:
  • 
    car_instance = Car("Red", 60)
            
  • This creates an instance of a car with the colour "Red" and a speed of 60.
  • Note: this assumes you have made a class called Car with the properties colour and speed. You can look at 3.1 to see an example of this.
  • Your Player class has the properties position_x, position_y, size, image, sprite.
  • You should add values inside the bracket, e.g. Player(...) that lines up with those properties.
  1. After you create the player instance, print out the player’s important properties to check they were created correctly.

πŸ’‘ Hint

  • You can access a class property by using a dot, like this: car_instance.colour. This should be"Red".
  • Print the player's sprite.
  • Print the player's position_x.
  • Print the player's position_y.
  • Print the player's size.

🚩 Checkpoint

  • A player object stored in a variable called Player.
  • Printouts in the terminal showing the player's properties.

Task 3.3: Create the draw method

  1. Create a new method called draw.

πŸ’‘ Hint

  • Use the def keyword.
  • It should be written inside your Food class (at the same indentation level as __init__()).
  • This method won’t take any arguments (only self).
  • This method will draw the food onto the screen.
  • In general, a method looks like:
  • 
    class Car:
        # These are our properties
        def __init__(self, colour, speed):
            colour = colour
            speed = speed
        β€Ž 
        # These are our methods
        def drive(self):
            # Do something here
    
  1. Draw the Sprite onto the Screen

πŸ’‘ Hint

  • Use screen.blit(...) to draw. Refer to your previous lines of code to see how to use this function!
  • The first thing you want to draw is the sprite.
  • The position to draw at is (position_x, position_y).

🚩 Checkpoint

  • A draw() method inside your Player class which knows how to:
    • Draw the sprite.
    • Place it at the correct position.

Task 3.4: Create the move method

  1. Inside your Player class, define a new method called move().

πŸ’‘ Hint

  • Use the def keyword.
  • Remember to give it just one parameter: self.
  1. Use pygame.key.get_pressed() to check which keys are currently being held down and save the result into a variable. This function will return a dictionary which can be accessed with the variables in the table below.

  2. Check if the player is pressing:

KeyActionPygame dictionary key
W keyMove uppygame.K_w
A keyMove leftpygame.K_a
S keyMove downpygame.K_s
D keyMove rightpygame.K_d

πŸ’‘ Hint

  • If the W key is pressed, decrease the y position.
  • If the S key is pressed, increase the y position.
  • If the A key is pressed, decrease the x position.
  • If the D key is pressed, increase the x position.
  • You can access a dictionary like so: dictionary[dictionary_key]
  1. Change the player's image depending on the direction they are moving

πŸ’‘ Hint

  • When moving up, change the image to poco_up.png.
  • When moving down, change the image to poco_down.png.
  • When moving left, change the image to poco_left.png.
  • When moving right, change the image to poco_right.png.

🚩 Checkpoint

  • A move() method inside your Player class.
  • The method checks which keys are pressed.
  • The method updates the player’s position_x and position_y.
  • The player image changes when moving!

Task 3.5: Fix duplicating Poco

Oh no! There's way too many Pocos! Let's fix that.

  1. Inside your while running: game loop, at the very start of the loop (before drawing the player or foods), draw the background again over the whole screen.

πŸ’‘ Hint

  • Use screen.blit(...) to redraw the background in the while loop

🚩 Checkpoint

  • Now Poco will move smoothly without leaving any clones behind.

Task 4: Adding other entities

Goal: Add multiple entities that are related to each other. In this example we have added food, but you are free to add what you wish, as long as it is appropriate.

Task 4.1: Create a Food Class

  1. Start by creating a new class called Food. This will be quite similar to the Player class. E.g.:
class Food:
  1. Inside your Food class, create a special function called __init__.

πŸ’‘ Hint

  • Use the def keyword to define the method.
  • The __init__ method should accept 4 inputs:
    • name
    • image
    • position_x
    • position_y
  • Your Food class should have more than 4 properties though, being name, image, size, position_x, position_y and sprite
  • Save each of these inputs into the object using self.
  • Note that you can set default values for a class like so:
  • 
    class Car:
        # Notice how we don't have a weight parameter in the 
        # brackets below.
        def __init__(self, colour, speed):
            # We can set this when creating an instance
            colour = colour
            speed = speed
            # Default property values
            weight = 20
            
  1. Inside your __init__() method, set a default size for your food.
  2. Still inside the __init__() method, load the image file using Pygame's image.load function.
  3. Scale the loaded image to the correct size using Pygame's transform scale function.
  4. Save the final scaled image into the object (e.g., self.sprite).

🚩 Checkpoint

  • A Food class (or a class of things you want to have).
  • Code in the __init__() method that:
    • Saves the name, image, and position.
    • Sets a default size.
    • Loads and scales the sprite.
  • A ready-to-use object for your game!

Task 4.2: Create a Food Dictionary

  1. Create a dictionary called foods, this dictionary will hold all the food items you want to appear in your game.

πŸ’‘ Hint

  • Use curly braces {} to create a dictionary.
  • Save it in your main code before your game loop starts.

2. Inside your dictionary, add entries for each food you want

πŸ’‘ Hint

  • Each key should be the name of the food (like "banana", "grapes", etc.).
  • Each value should be a list that contains:
    • The path to the image file.
    • The x position.
    • The y position.

Example structure:

"food name": ["path/to/image.png", x_position, y_position]

Task 4.3: Initialise Active Foods List

  1. Create a new empty list called active_foods, and this list will store all the Food objects you create.
  2. Write a for loop that goes through every item in your foods dictionary. In each loop, you will create a new Food object.

πŸ’‘ Hint

  • Use .items() to loop through both the key and value.
  • The key will be the name of the food.
  • The value will be a list containing:
    • [image path, x position, y position]

3. Create a New Food Object for Each Item

πŸ’‘ Hint

  • key -> name
  • value[0] -> image path
  • value[1] -> x position
  • value[2] -> y position

🚩 Checkpoint

  • An empty active_foods list is created.
  • A loop that:
    • Goes through every food in your dictionary.
    • Creates a Food object.
    • Adds it into the active_foods list.

Task 4.4: Create Food Draw Method

  1. Create a new method called draw.

πŸ’‘ Hint

  • Use the def keyword.
  • It should be written inside your Food class (at the same indentation level as __init__()).
  • This method won’t take any arguments (only self).
  • This method will draw the food onto the screen.

  1. Draw the Sprite Onto the Screen

πŸ’‘ Hint

  • Use screen.blit(...) to draw.
  • The first thing you want to draw is the sprite (image).
  • The position to draw at is (position_x, position_y).


🚩 Checkpoint

  • A draw() method inside your Food class which knows how to:
    • Draw the sprite.
    • Place it at the correct position.

Task 4.5: Draw Active Foods in Game Loop

Now that each Food knows how to draw itself, it's time to actually draw all the food onto your game window during the game!

  1. Draw each active food item onto the screen by looping through all active foods inside your while running: game loop.

πŸ’‘ Hint

  • Create a loop inside your while running: loop to iterate over the active_foods list.
  • Call the food’s draw() method.
  1. Check whether the player has interacted with the food.

πŸ’‘ Hint

  • Inside the for loop:
    • Use the player's method to check for interaction with the food.

🚩 Checkpoint

  • A for loop inside the main game loop.
  • You can interact with the food.
  • All food is drawn onto the screen.
  • All your food is visible.

Task 5: Collision

Goal: Detect whether the player is colliding with any of the food.

Task 5.1: Create a hitbox for both the players and the foods

  1. Create an extra property in the player and food class. Use the .get_rect().move() function to create a rectangle that moves with the class' sprite.
  2. Create a method called update(self) in the player class. Copy the property you just wrote into this method.
  3. Call the player update method in the main game loop, just underneath player.draw()

πŸ’‘ Hint

  • sprite.get_rect() creates a rectangle the size of the image
  • .move() moves whatever it's attached to to an x and y coordinate
  • To combine these into a hitbox you can have:
    self.hitbox = self.sprite.get_rect().move(self.position_x, self.position_y)

Task 5.2: Check whether two hitboxes are colliding

  1. Create a property called interact_foods(self, food) in the food class
  2. Use the colliderect to check whether the rectangular hitboxes are colliding
  3. If they are colliding, remove food from the active_foods list

πŸ’‘ Hint

  • Check if the player hitbox is colliding with the food hitbox:
    collision = self.hitbox.colliderect(food.hitbox)
  • The collision variable is True if the hitboxes are colliding and False if not

Task 6: Finishing the game.

Goal: Add a score, a win condition. Finishing this task finishes the basic features of your game.

Task 6.1: Create a player score

  1. Create a player property called score
  2. Everytime that a user picks up a new item, update this variable.

Task 6.2: Game Win condition

  1. If the the player picks up all the items or the score is equal to the number of items, then end the game and quit.

πŸ’‘ Hint

  • Perhaps setting running = False will do something.

Task 6.3: Show the score on the screen

  1. Render the score on the screen. We can use font.render().
  2. blit the text onto the screen. Experiment with where you would put the score!

πŸ’‘ Hint

  • Setting fonts and colours in pygame:
  • 
    colour = (256, 256, 256) # (R,G,B)
    font = pygame.font.SysFont('Palatino', 50)
        
  • Rendering text. We concatenate "Score: " and the score variable to make it nice!
  • Link to documentation for font.render
  • 
    score_render = font.render("Score: " + score, True, colour)
        

Task 6: Finishing the game.

Goal: Add a score, a win condition. Finishing this task finishes the basic features of your game.

Feature 1: Using random numbers

  1. We can generate a random number with random.randint(start, end)

πŸ’‘ Hint


- if we want to generate a number between 0 and 10:
    ```python
    random_number = random.randint(0, 10)
    ```

  1. You can use random nunmber to make your food randomly appear

Task 6.2: Game Win condition

  1. If the the player picks up all the items or the score is equal to the number of items, then end the game and quit.

πŸ’‘ Hint

  • Perhaps setting running = False will do something.

Task 6.3: Show the score on the screen

  1. Render the score on the screen. We can use font.render().
  2. blit the text onto the screen. Experiment with where you would put the score!

πŸ’‘ Hint

# Setting fonts in pygame
    colour = (256, 256, 256) # (R,G,B)
# Creating text - concatenate "Score: " and the score variable
# https://www.pygame.org/docs/ref/font.html#pygame.font.Font.render
font.render("Score: " + score, True, colour)

# Drawing on the screen
screen.blit(image, (x_position, y_position))