More results...

Generic selectors
Exact matches only
Search in title
Search in content
Post Type Selectors
post
page
Python IDE Dashboard

Le Tour de France

cyclist

Learning Objectives


By completing this challenge we are learning how to open and extract data from a text file, reading the file line by line. We will then use our program to make some calculations such as calculating the total distance of the race over 21 stages.

The Race


Le Tour de France is a cycling race that takes place over 21 stages (23 days in total, including two rest days). The text file below contains a list of the 21 stages as follows (based on the 2015 route):

Stage Number;Distance in km;Starting from;Arriving at
TextFileletour.txt

The Code


Your Challenge


Adapt this code to answer the following questions:

  • What stage is the longest stage (in distance)?
  • What stage is the shortest stage (in distance)?
  • What is the average distance per stage?
  • What is the total distance of the race in miles?
  • Between stage 16 and stage 17, once in Gap, cyclists have a rest day. How many kilometres have they been cycling for? How many kilometres are left till the end of the race?
unlock-access

Solution...

The solution for this challenge is available to full members!
Find out how to become a member:
➤ Members' Area
Tagged with: ,

Rainbow Challenge

rainbowIn this challenge we are going to use our coding skills to create some nice colour patterns. We will first look at the code given to create a rainbow effect to understand how it works. We will then adapt this script to create three other colour patterns.

Rainbow Effect


Try the code above. This code is using a few computing concetps such as:

  • A list to store the different colour codes,
  • Iteration using a for loop to loop through each colour in the list,
  • (x,y) coordinates to position the turtle on the screen.

List?


In Python, a list is used to save a collection of values. For instance, to save all the different days of the week we could declare a variable called “daysOfTheWeek” and assign a list as follows:

daysOfTheWeek = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]

Based on this what do you think len(daysOfTheWeek) would return?
What’s about daysOfTheWeek[0]?
Or daysOfTheWeek[3] ?

Looping through a list


It is possible to access each value of a list one at a time using a for loop. Look at the following code to print the seven days of the week.

daysOfTheWeek = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]

for day in daysOfTheWeek:
    print(day)

In our rainbow code we use a list to store all the different colours of the rainbow as follows:

rainbowColors = ["#FF0000","#FFA600","#FFFF00", "#62FF00", "#1E56FC","#4800FF","#CC00FF","#69C5FF"]

(x,y) coordinates using turtle


quadrant-coordinates
On this trinket widget the turtle screen is 400 pixels wide. So:

  • the top left corner coordinates are (-200,200)
  • the top right corner coordinates are (200,200)
  • the bottom left corner coordinates are (-200,-200)
  • the bottom right corner coordinates are (200,-200)
  • the centre of the screen coordinates are (0,0)

Look at the canvas below to understand how (x,y) coordinates work:

Colour Pattern #1


Use and adapt the script above to recreate this colour pattern. The colour codes are given to you in the colour palette below.
color-pattern-1

Colour Hex RGB
#0099e6 (0,153,230)
#43e0ef (67,224,239)
#c3e970 (195,233,112)
#ffa9c2 (255,169,194)
#d297d9 (210,151,217)

Colour Pattern #2


Use and adapt your script to recreate this colour pattern. The colour codes are given to you in the colour palette below.
color-pattern-2

Colour Hex RGB
#ff0000 (255,0,0)
#d61a1a (214,26,26)
#a50000 (165,0,0)
#ddb200 (221,178,0)
#e7e497 (231,228,151)

Colour Pattern #3: Using a Random pattern


Use and adapt your script to recreate this colour pattern. The colour codes are given to you in the colour palette below.

However there is no colour pattern here. Each circle uses a random colour from the colour palette.

Check the code below used to randomly pick a colour from:

import random #Only use this statement once, at the top of your Python program.

rainbowColors = ["#FF0000","#FFA600","#FFFF00", "#62FF00", "#1E56FC","#4800FF","#CC00FF","#69C5FF"]
randomColor = random.choice(rainbowColors)

color-pattern-3

Colour Hex RGB
#ECECEC (236,236,236)
#2198d5 (33,152,213)
#0f8975 (15,137,117)
#0f6089 (15,96,137)
#000000 (0,0,0)

Tagged with: , , ,

Turtle Maze Challenge

maze
Your challenge is to guide the turtle through the maze. To do so you will need to use the following instructions:

  • myPen.forward(100) to move forward by 100 pixels,
  • myPen.right(90) to turn right by 90 degrees,
  • myPen.left(90) to turn left by 90 degrees.

Complete the code


Using a for loop


Note that, as you progress through the maze you may also decide to use a for loop to repeat a set of instructions several times.
For instance:

for i in range(0,3):
   myPen.forward(100)
   myPen.left(90)

Video Tutorial:



unlock-access

Solution...

The solution for this challenge is available to full members!
Find out how to become a member:
➤ Members' Area
Tagged with: , ,

Pygame: How to control your sprite?

arrowKeysThis tutorial is the third tutorial in a series of five Pygame tutorials:

For this third tutorial we will complete the code from the previous tutorial:

Remember the aim is to create a car racing game. In the first tutorial we looked at how to create the background for our game (The road). In the second tutorial we added our first sprite called playerCar which is an instance of the Car class.

In this third tutorial we will add methods to our Car class to move the car to the left, right, forward, and backward.

We will then add event handlers to the main program loop to respond to keystroke events. When the player uses the arrow keys on the keyboard we will call our methods to move the playerCar on the screen.

Step 1: Adding Methods to the Car class.


Open the file car.py and add the lines 26 to 30 as follows:

import pygame
WHITE = (255, 255, 255)

class Car(pygame.sprite.Sprite):
    #This class represents a car. It derives from the "Sprite" class in Pygame.
    
    def __init__(self, color, width, height):
        # Call the parent class (Sprite) constructor
        super().__init__()
        
        # Pass in the color of the car, and its x and y position, width and height.
        # Set the background color and set it to be transparent
        self.image = pygame.Surface([width, height])
        self.image.fill(WHITE)
        self.image.set_colorkey(WHITE)
 
        # Draw the car (a rectangle!)
        pygame.draw.rect(self.image, color, [0, 0, width, height])
        
        # Instead we could load a proper pciture of a car...
        # self.image = pygame.image.load("car.png").convert_alpha()
 
        # Fetch the rectangle object that has the dimensions of the image.
        self.rect = self.image.get_rect()

    def moveRight(self, pixels):
        self.rect.x += pixels

    def moveLeft(self, pixels):
        self.rect.x -= pixels

As you can see we have added two procedures to our class. In OOP (Object Orientated Programming) we call these procedures: methods. A method is a procedure or function associated to a class. Let’s look at the moveRight() method.

def moveRight(self, pixels):
   self.rect.x += pixels

The moveRight() method takes two arguments. The first one is implicit and is called self. It refers to the current object. The second one is called pixels and refers to the number of pixels we will use to move the car.

The body of our method only contains one line: self.rect.x += pixels
It is basically adding pixels to the current x coordinate of the object.

Step 2: Responding to keystroke events


arrowKeysLet’s look at the code for our main program. You may remember that in the first tutorial we talked about the main program loop. The first section of this loop is to respond to events such as user interactions when the user uses the mouse or the keyboard.

So let’s add two event handlers, one moving left and one for moving right using the left and right arrow keys of the keyboard. Each event handler will call the relevant method from the Car class. Check the code below with the new event handlers from line 37 to 45.

import pygame, random
#Let's import the Car Class
from car import Car
pygame.init()

GREEN = (20, 255, 140)
GREY = (210, 210 ,210)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
PURPLE = (255, 0, 255)
        
SCREENWIDTH=400
SCREENHEIGHT=500

size = (SCREENWIDTH, SCREENHEIGHT)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Car Racing")

#This will be a list that will contain all the sprites we intend to use in our game.
all_sprites_list = pygame.sprite.Group()

playerCar = Car(RED, 20, 30)
playerCar.rect.x = 200
playerCar.rect.y = 300

# Add the car to the list of objects
all_sprites_list.add(playerCar)

#Allowing the user to close the window...
carryOn = True
clock=pygame.time.Clock()

while carryOn:
        for event in pygame.event.get():
            if event.type==pygame.QUIT:
                carryOn=False
            elif event.type==pygame.KEYDOWN:
                if event.key==pygame.K_x: #Pressing the x Key will quit the game
                     carryOn=False

        keys = pygame.key.get_pressed()
        if keys[pygame.K_LEFT]:
            playerCar.moveLeft(5)
        if keys[pygame.K_RIGHT]:
            playerCar.moveRight(5)
        
        #Game Logic
        all_sprites_list.update()

        #Drawing on Screen
        screen.fill(GREEN)
        #Draw The Road
        pygame.draw.rect(screen, GREY, [40,0, 200,300])
        #Draw Line painting on the road
        pygame.draw.line(screen, WHITE, [140,0],[140,300],5)
        
        #Now let's draw all the sprites in one go. (For now we only have 1 sprite!)
        all_sprites_list.draw(screen)

        #Refresh Screen
        pygame.display.flip()

        #Number of frames per secong e.g. 60
        clock.tick(60)

pygame.quit() 

All done… Save your files and try your code. You should now be able to control your car using the arrow keys!

Tagged with: , , ,

Captain Redbeard’s Treasure

pirateWe need your coding skills to locate the treasure of Captain Redbeard. The legend holds that Redbeard was a great pirate who sailed the Caribbean Sea, fiercely attacking any vessels from the British Navy he would encounter.

Redbeard was killed in battle with the British Navy in 1743. Legend holds that he received 20 stab wounds and five gunshot wounds before finally succumbing.

But the legend also tells us that he buried his treasure before his final battle on Paradise Island, in the Caribbean waters. On his ship the British Navy found a treasure map with a set of instructions that they have not been able to decode yet.

Will you be able to help them locate Captain Redbeard treasure?

Map of Paradise Island:


treasure-map

Captain Redbeard’s Instructions:

START
GOTO E7
POINT North

FOR step FROM 1 to 4
    MOVE FORWARD BY 1
END FOR

POINT West

REPEAT
    MOVE FORWARD BY 1
UNTIL FoundKey == True

TURN 180 Degrees

WHILE StillOnMap == True
    MOVE FORWARD BY 1
    IF FoundSpider == TRUE THEN
           CRUSH spider
           EXIT WHILE LOOP
    END IF
END WHILE 	

POINT South
MOVE FORWARD BY 2
DIG FOR TREASURE

Can you tell where Captain Redbeard’s treasure has been buried for all these years?

Tagged with:

3D Printing Programming

3DPrinting-101Computing
Using a “scratch like” programming language you can create your own 3D models and export them in a format recognised by 3D Printers.

Click on the picture above to access the BeetleBlocks project:

3DPrinting-Programming

Tagged with: , ,

Murder Mystery

Murder-MysteryDoctor Black has just been found dead in his bedroom. He has been knocked down by a heavy metallic object, most likely the candlestick that was found on the floor next to Doctor Black. When falling down, Doctor Black broke his watch which stopped at 8:14 PM. We can assume that this is the time of death.

Doctor Black’s bedroom is the master bedroom and is located on the first floor.

Our crime scene investigator took some notes to recap the key facts:

cluedo-clipboard

At this time of the day there were only four guests in Doctor Black’s mansion. They are the prime suspects:

  • Miss Scarlett
  • Reverend Green
  • Colonel Mustard
  • Professor Plum

do-not-cross

Our crime scene investigator interviewed all four suspects and gathered some facts about their whereabouts around the time of death.

He has decided to create an algorithm based on these facts to help him solve this murder mystery. To do so he has translated each fact into pseudo code as follows:

Fact:

Miss Scarlett and Professor Plum were playing tennis between 6 and 8PM, so if the murder took place between 6 and 8PM they would both be innocent.

Pseudocode:

IF TimeOfMurder >= 6:00PM AND TimeOfMurder <= 8:00PM THEN
    MissScarlett = "Innocent"
    ProfessorPlum = "Innocent"
END IF

do-not-cross

Below is our crime scene investigator’s full algorithm:

Will it help you solve this crime?

IF TimeOfMurder >= 6:00PM AND TimeOfMurder <= 8:00PM THEN
    MissScarlett = "Innocent"
    ProfessorPlum = "Innocent"
END IF

SELECT CASE LocationOfMurder:
    CASE "1st Floor":
        ReverendGreen = "Innocent"
    CASE "Ground Level":
        MissScarlett = "Innocent"
        ColonelMustard = "Innocent"
    CASE "Garden"
        ProfessorPlum = "Innocent"

IF (MurderRoom == "Kitchen" OR MuderRoom == "Master Bedroom")  AND timeOfMurder >= 8:00PM THEN
    ProfessorPlum = "Innocent"
ELIF MurderRoom == "Bathroom" AND (timeOfMurder >= 8:00PM AND timeOfMurder <= 8:30PM) THEN
    MissScarlett = "Guilty"
END IF

IF MurderWeapon == "Candlestick" OR MurderWeapon == "Rope" THEN
    MurdererGender = "Male"
END IF

And the murderer is …

do-not-cross

Tagged with: ,

Creating Sprites using Pygame

This tutorial is the second tutorial in a series of five Pygame tutorials:

Learning Objectives


In this second tutorial on how to create a retro arcade game using PyGame we are looking at creating our first sprite.
definition-sprite

Consider a sprite as an object. An object can have different properties (e.g. width, height, colour, etc.) and methods (e.g. jump(), hide(), moveForward(), etc.). Like in the industry an object is built from a mould. In computing the mould is called a Class.

So by creating our first sprite we will implement OOP (Object Orientated Programming). We will create our first Class and derive our first object from this class.

Context: Car Racing Game


For this tutorial we are looking at creating a car racing game. The user will be able to control the car and move on the road between lanes by using the left and right arrow keys, accelerate or slow down using the up and down arrow keys.

The main car will be an object called playerCar. It will derive from a Class called Car.

Our first Class


So let’s look at the code for our Car Class:
To start with the first method we will need in our class is the __init__() method. It’s called a constructor. It is used when the object is first created to initalise the main properties of the object (e.g. its x and y position, dimensions, colour, etc.)

import pygame
WHITE = (255, 255, 255)

class Car(pygame.sprite.Sprite):
    #This class represents a car. It derives from the "Sprite" class in Pygame.
    
    def __init__(self, color, width, height):
        # Call the parent class (Sprite) constructor
        super().__init__()
        
        # Pass in the color of the car, and its x and y position, width and height.
        # Set the background color and set it to be transparent
        self.image = pygame.Surface([width, height])
        self.image.fill(WHITE)
        self.image.set_colorkey(WHITE)
 
        # Draw the car (a rectangle!)
        pygame.draw.rect(self.image, color, [0, 0, width, height])
        
        # Instead we could load a proper pciture of a car...
        # self.image = pygame.image.load("car.png").convert_alpha()
 
        # Fetch the rectangle object that has the dimensions of the image.
        self.rect = self.image.get_rect()

Later on we will add more properties and methods to this class. But before doing so we will look at how we can use it to create our first object: the car of the player (playerCar)

So let’s save our class as a python file called car.py.

Our first Object


Now that we have a Class we can create objects from this Class. (Remember a Class is like a mould. It enables you to create as many objects as you need using the same mould.)

Let’s go back to our main.py file (from previous tutorial) to edit its content.

First let’s add at the top of the code an import statement to import our Car class.

#Let's import the Car Class
from car import Car

Then we need to create our sprite in our main program using the following line of code:

playerCar = Car(RED, 20, 30)

Per dafult your car will be on position (0,0) (top left og the screen). You can change the x and y properties of your car as follows:

playerCar.rect.x = 200
playerCar.rect.y = 300

You can see how easy it would be to create another car:

player1Car = Car(RED, 20, 30)
player1Car.rect.x = 200
player1Car.rect.y = 300
player2Car = Car(PURPLE, 20, 30)
player2Car.rect.x = 400
player2Car.rect.y = 400

However, because we are creating a fully working game we are going to do a few more things with this object.

Let’s reuse the code from the first tutorial. We have made a few amendments since to draw the backdrop of our game: A green screen with a grey straight road!

On line 3 notice how we are using the import command to link to our Car Class python file (car.py).

On line 20 we are declaring a list called all_sprites_list that will store all the sprites we will create in our game. (For now just one sprite, the player car.)

On line 22 we are creating our first sprite/object using the Car Class. Notice how when declaring our first object we use the parameters from its constructor (__init__()), in this case, the colour, x, y, width and height of the car we want to create.

Now that we have created our first sprite we need to add it to our list of spites: all_sprites_list. This is what happens on line 27.

Finally, within the main program loop, on line 49 we are refreshing the screen and drawing all the sprites from our list: all_sprites_list.

Here is the full code:

import pygame, random
#Let's import the Car Class
from car import Car
pygame.init()

GREEN = (20, 255, 140)
GREY = (210, 210 ,210)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
PURPLE = (255, 0, 255)
        
SCREENWIDTH=400
SCREENHEIGHT=500

size = (SCREENWIDTH, SCREENHEIGHT)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Car Racing")

#This will be a list that will contain all the sprites we intend to use in our game.
all_sprites_list = pygame.sprite.Group()

playerCar = Car(RED, 20, 30)
playerCar.rect.x = 200
playerCar.rect.y = 300

# Add the car to the list of objects
all_sprites_list.add(playerCar)

#Allowing the user to close the window...
carryOn = True
clock=pygame.time.Clock()

while carryOn:
        for event in pygame.event.get():
            if event.type==pygame.QUIT:
                carryOn=False
                
        #Game Logic
        all_sprites_list.update()

        #Drawing on Screen
        screen.fill(GREEN)
        #Draw The Road
        pygame.draw.rect(screen, GREY, [40,0, 200,300])
        #Draw Line painting on the road
        pygame.draw.line(screen, WHITE, [140,0],[140,300],5)
        
        #Now let's draw all the sprites in one go. (For now we only have 1 sprite!)
        all_sprites_list.draw(screen)

        #Refresh Screen
        pygame.display.flip()

        #Number of frames per secong e.g. 60
        clock.tick(60)

pygame.quit()

That’s it… You are now ready to move to our third tutorial to learn how to control your sprites using the arrow keys.
PyGame Tutorial 3/5Control your sprite using the arrow keys

Tagged with: , ,

Minecraft + Python Challenges

Learning Objectives


Another approach to boost your pogramming skills is to learn how to code for Minecraft. Using Python code you can interact with the Minecraft world to for instance move the player or add blocks to build structures.

For this challenge we are using a Raspberry Pi with Minecraft and Python 2 pre-installed.

Let’s see how this works…

Hello Minecraft World


Let’s start by writting a “Hello World” program that will write a welcome message on the Minecraft chat. This is the simplest program and will be useful to make sure we have the required library and can connect to Minecraft.

Here is the Python code:

from mcpi import minecraft, block

mc = minecraft.Minecraft.create()
msg = "Hello Minecraft World from 101 Computing"
mc.postToChat(msg)

So to test this program on your Raspberry Pi you will need to:

  • Type this program in your Python IDE (e.g. IDLE) for Python 2,
  • Launch Minecraft
  • In your IDE run the program
  • Check the Minecraft screen. If everything goes right, a message will appear on screen.

Teleporting your player


minecraft-xyz-coordinatesFor this Python script we are going to write a function to teleport the player up in the sky. We will call this function “jump”. It will take one parameter: the distance (number of blocks) we want the player to jump (up in the sky).

To understand the code below we need to understand how (X,Y,Z) are used in minecraft to retrieve or change the position of a player (and later on the position of blocks).

from mcpi import minecraft, block
import time

def jump(distance):
    #Let's wait 1 second
    time.sleep(1)
    
    #Retrieve the X,Y,Z coordinates of the player
    pos=mc.player.getPos()
    #Change the Y coordinate of the player to position it up in the sky    
    mc.player.setPos(pos.x, pos.y + distance, pos.z)

#Main Program Starts Here:
jump(100)

Building a Tower


minecraft-postThe purpose of this script is to build a ten-block high tower in front of the player. We will be using 3 different methods for you to compare:
  • Method 1: Building the tower one block at a time using sequencing,

  • Method 2: Building the tower one block at a time using iteration (for loop),

  • Method 3: Building the tower in one go using the setBlocks(), method.

Method 1Method 2Method 3
from mcpi import minecraft, block
import time

def createTower():
    #Let's wait 1 second
    time.sleep(1)
    
    #Retrieve the X,Y,Z coordinates of the player
    pos=mc.player.getPos()

    #Create a 10-block high tower, 5 blocks away from the player
    mc.setBlock(pos.x + 5, pos.y, pos.z, block.STONE)
    mc.setBlock(pos.x + 5, pos.y+1, pos.z, block.STONE)
    mc.setBlock(pos.x + 5, pos.y+2, pos.z, block.STONE)
    mc.setBlock(pos.x + 5, pos.y+3, pos.z, block.STONE)
    mc.setBlock(pos.x + 5, pos.y+4, pos.z, block.STONE)
    mc.setBlock(pos.x + 5, pos.y+5, pos.z, block.STONE)
    mc.setBlock(pos.x + 5, pos.y+6, pos.z, block.STONE)
    mc.setBlock(pos.x + 5, pos.y+7, pos.z, block.STONE)
    mc.setBlock(pos.x + 5, pos.y+8, pos.z, block.STONE)
    mc.setBlock(pos.x + 5, pos.y+9, pos.z, block.STONE)
    mc.setBlock(pos.x + 5, pos.y+10, pos.z, block.STONE)

#Main Program Starts Here:
createTower()
from mcpi import minecraft, block
import time

def createTower(numberOfBlocks):
    #Let's wait 1 second
    time.sleep(1)
    
    #Retrieve the X,Y,Z coordinates of the player
    pos=mc.player.getPos()

    #Create a tower 5 blocks away from the player
    for i in range (0, numberOfBlocks):
        mc.setBlock(pos.x + 5, pos.y + i, pos.z, block.STONE)

#Main Program Starts Here:
createTower(10)
from mcpi import minecraft, block
import time

def createTower(numberOfBlocks):
    #Let's wait 1 second
    time.sleep(1)
    
    #Retrieve the X,Y,Z coordinates of the player
    pos=mc.player.getPos()

    #Create a tower 5 blocks away from the player
    mc.setBlocks(pos.x + 5, pos.y, pos.z, pos.x + 5, pos.y + numberOfBlocks, pos.z, block.STONE)

#Main Program Starts Here:
createTower(10)

Challenge #1: Rugby Post


minecraft-rugby-postUse any of the three methods mentioned above and complete the code to create a full rugby post using Python.

Challenge #2: A complex Structure


Build a complex structure using a Python script. Try to identify patterns in your structure to use for loops and hence reduce the number of instructions in your program.

Try to build a Pyramid first starting from a 10 by 10 square base.

Or why not challenge yourself to build a castle like this one:
minecraft-castle

Tagged with: , , ,

Getting Started with Pygame

This tutorial is the first tutorial in a series of five Pygame tutorials:

Learning Objectives


These instructions will guide you through the first few steps required to set up the foundation for a Pygame project.

Now that you have learned the basics of Python you are most likely willing to start creating your own games. Pygame is one of the best libraries to create mainly 2D retro arcade games such as Tetris, PacMan or Space Invaders.

Let’s see what are the first few steps needed to create your first game in Python.

Installing Pygame


Make sure you have access to the Pygame library. If not you will need to download and install it following the instructions provided on the Pygame website: http://www.pygame.org/.

Step 1: Importing and initialising the Pygame library


Your Python code will need to start with the following two lines of code:

# Import the pygame library and initialise the game engine
import pygame
pygame.init()

Note that you will first need to install the Pygame library on your computer. Alternatively you can complete this challenge online using the following Trinket/Pygame IDE

Step 2: Define the colours you will use in your game


You will have to declare a constant for each of the main colours used within your game. To help you identify colour codes you may use a colour picker.

# Define some colors
BLACK = ( 0, 0, 0)
WHITE = ( 255, 255, 255)
GREEN = ( 0, 255, 0)
RED = ( 255, 0, 0)

Step 3: Open a new window


Your game will run in its own window, for which you can decide of a title, a width and a height.

# Open a new window
size = (700, 500)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("My First Game")

Step 4: The main program loop


The main program loop is the key wrapper for your game.

The main program loop will contain 3 main sections:

  • Capturing Events: Used to constantly “listen” to user inputs and react to these. It could be when the user uses the keyboard or the mouse.
  • Implementing the Game Logic. What happens when the game is running? Are cars moving forward, aliens falling from the sky, ghosts chasing you, etc.
  • Refreshing the screen by redrawing the stage and the sprites.

The main program loop will also use a frame rate to decide how often should the program complete the loop (& refresh the screen) per second. To implement this we will use the clock object from the pygame library.

The main program loop will use a timer to decide how many times it will be executed per second.

# The loop will carry on until the user exits the game (e.g. clicks the close button).
carryOn = True

# The clock will be used to control how fast the screen updates
clock = pygame.time.Clock()

# -------- Main Program Loop -----------
while carryOn:
    # --- Main event loop
    for event in pygame.event.get(): # User did something
        if event.type == pygame.QUIT: # If user clicked close
              carryOn = False # Flag that we are done so we can exit the while loop

     # --- Game logic should go here

     # --- Drawing code should go here
     # First, clear the screen to white. 
     screen.fill(WHITE)
     #The you can draw different shapes and lines or add text to your background stage.
     pygame.draw.rect(screen, RED, [55, 200, 100, 70],0)
     pygame.draw.line(screen, GREEN, [0, 0], [100, 100], 5)
     pygame.draw.ellipse(screen, BLACK, [20,20,250,100], 2)


     # --- Go ahead and update the screen with what we've drawn.
     pygame.display.flip()
     
     # --- Limit to 60 frames per second
     clock.tick(60)

#Once we have exited the main program loop we can stop the game engine:
pygame.quit()

Your Challenge


Use the code above to create your first Pygame project.

Complete the code to draw the following background:
pygame-road-layout

Next Step?


Your background is ready? Let’s add the first sprite to your project by completing the next tutorial:
Adding a Sprite using PyGame(Tutorial 2/5)
Tagged with: , ,