More results...

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

Data Validation Quiz

When programming a computer system, it is good practice to include a range of validation checks in the code to check if the data being inputted by the end-user follows some basic rules.

The aim of validation checks is to ensure that data used or stored by computer systems is valid. Invalid data may indeed make the system crash or may provide inaccurate information back to the user.

Validation checks cannot confirm if the data is correct or not but they can filter out a lot of invalid data.

There are different types of checks that can be implemented in your code such as:

  • Presence Check: When a field has to be filled in (mandatory field) and cannot be left blank/empty. (e.g username field when you sign in to a new system)
  • Length Check: When a field has to contain a set number of characters (e.g. a password is at least 8 characters long, a credit card number contains 16 digits).
  • Type Check: When a field has be of a certain data type (integer, float/real, etc.).
  • Range Check: When a field has be within a range, or greater or lower than given value. (e.g. A percentage value has to be between 0 and 100)
  • Lookup Check: When a field can only accept a certain set of values from a list (e.g. A title field can be either Mr, Mrs, Ms or Dr)
  • Character Check: When a field has to contain a specific character or type of characters. (e.g. An e-mail address should contain an “@” sign)

Take the Quiz! (open full screen)


Check that you understand the different types of validation checks by completing this quiz:

Tagged with:

Vera Molnár’s Artwork revisited using Python

vera-molnar-artworkVera Molnár (born 1924) is a French media artist of Hungarian origin. She is considered to be a pioneer of computer art. Trained as a traditional artist, she began working with computers in 1968, where she began to create algorithmic paintings based on simple geometric shapes and geometrical themes.

In this blog post we are looking at using Python Turtle to recreate some of her artwork. To create you own op art/computer art, you will need to be confident in using iterative algorithms and have a good understanding of Cartesian coordinates.

To find review some of Vera Molnár’s artwork you can use the following pages:

Artwork #1


This is our first attempt at recreating some of Vera Molnár’s artwork using Python Turtle.

Artwork #2


This is our second attempt at recreating some of Vera Molnár’s artwork using Python Turtle.

Your Task


Your task is to select on other piece of artwork from Vera Molnár and write a computer algorithm using Python Turtle to recreate it. You can do so by adapting the scripts provided above.

vera-molnar-computer-art

Find more work from Vera Molnár on Google Images

Tagged with: , , ,

Triangle Geometry Functions

In this challenge we will create a library of functions to apply the different formulas based on the geometry of triangles.

For each function, you will need to design the algorithm using either Pseudo-code or a flowchart, implement the function using the Python trinket provided below and use another algorithm to test your function.

PerimeterAreaAnglesEquilateralIsoscelesPythagoras' TheoremHeron's Formula
triangle-perimeter-formulaWrite a function called getPerimeter() that takes three parameters/arguments a, b, c (the length of each side of a triangle).

Your function should calculate and return the perimeter of this triangle.


Write an algorithm to test your function.
Your algorithm should:

  • Ask the user to enter the length of the 3 sides of a triangle,
  • Use the getPerimeter() function to retrieve the perimeter of the triangle,
  • Display the perimeter of the triangle
triangle-area-formulaWrite a function called getArea() that takes two parameters/arguments corresponding to the length of the base and of the height of a triangle.

Your function should calculate and return the area of this triangle.


Write an algorithm to test your function.
Your algorithm should:

  • Ask the user to enter the length of the base and height of a triangle,
  • Use the getArea() function to retrieve the area of the triangle,
  • Display the area of the triangle
triangle-angles-formulaWrite a function called getAngle() that takes two parameters/arguments called angle1 and angle2 (the value of two angles in degrees)

Your function should calculate and return the value of the third angle: (180 – angle1 – angle2)


Write an algorithm to test your function.
Your algorithm should:

  • Ask the user to enter the value of two angles in degrees,
  • Use the getAngle() function to retrieve the value of the third angle,
  • Display this value on screen.
triangle-equilateralWrite a function called isEquilateral() that takes three parameters a, b, c (the length of each side of a triangle).

Your function should workout if the triangle is equilateral (if all sides have the same length) and return a Boolean value (True or False) based on its finding.


Write an algorithm to test your function.
Your algorithm should:

  • Ask the user to enter the length of the 3 sides of a triangle,
  • Use the isEquilateral() function to find out if the triangle is an equilateral triangle,
  • Display a relevant message to the end user.
triangle-isoscelesWrite a function called isIsoscles() that takes three parameters a, b, c (the length of each side of a triangle).

Your function should workout if the triangle is an isosceles triangle (if any two sides have the same length) and return a Boolean value (True or False) based on its finding.


Write an algorithm to test your function.
Your algorithm should:

  • Ask the user to enter the length of the 3 sides of a triangle,
  • Use the isIsoscles() function to find out if the triangle is an isosceles triangle,
  • Display a relevant message to the end user.
triangle-pythagorasWrite a function called getHypotenuse() that takes two parameters/arguments called a and b (the length of two sides of a right-angled triangle).

Your function should calculate and return the length of the third side (the hypotenuse) of the triangle knowing that:
triangle-pythagoras-formula


Write an algorithm to test your function. Your algorithm should:

  • Ask the user to enter the length of the 2 sides of a right-angled triangle,
  • Use the getyHypotenuse() function to retrieve the value of the hypotenuse of the right–angled triangle,
  • Display the value of the Hypotenuse.

Write a function called isRightAngledTriangle(), that takes three parameters a, b and c and works out if the triangle is a right-angled triangle or not. Your function should return a Boolean value (True or False) based on its finding.


Write an algorithm to test your function. Your algorithm should:

  • Ask the user to enter the length of the 3 sides of a triangle,
  • Use the isRightAngledTriangle() function to find out if the triangle is a right-angled trinagle,
  • Display a relevant message to the end-user.
heron-formula
Write a function called getTriangleArea() that takes three parameters/arguments a, b, c (the length of each side of a triangle).

Your function will apply Heron’s formula to calculate and return the area of the triangle.


Write an algorithm to test your function.
Your algorithm should:

  • Ask the user to enter the length of the 3 sides of a triangle,
  • Use the getTriangleArea() function to retrieve the area of the triangle,
  • Display the area of the triangle

Python Code


We have already started the code for you and have completed the function getPerimeter() followed by a short algorithm to test this function.

Your task is to complete this Python script to create and test all the functions mentioned above.

unlock-access

Solution...

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

Heron’s Formula

The Heron’s formula is a famous formula used to calculate the area of a triangle based on the length of its three sides. It is called “Heron’s Formula” (sometimes called Hero’s formula) after Hero of Alexandria who was a Greek Engineer and Mathematician in 10 – 70 AD.

heron-formula

Python Task


Your task is to write a function called calculateTriangleArea(). Your function will:

  • Take three parameters corresponding to the length of the 3 sides of a triangle: a, b and c,
  • Apply Heron’s formula to calculate the area of the triangle,
  • Return the area of the triangle.

You will also then need to create a small program that will:

  • Ask the user to enter the length of the three sides of a triangle,
  • Calculate the area of the triangle using the calculateTriangleArea() function,
  • Output the area of the triangle.

Video Tutorial


Python Code


Test Plan:


Once your code is done, complete the following tests to check it is working as expected:

Test # Input Values (in cm) Expected Output (in cm2) Pass/Fail?
#1 First side: 3
Second side: 4
Third side: 5
Area: 6
#2 First side: 8
Second side: 10
Third side: 12
Area: 39.686
#3 First side: 4
Second side: 8
Third side: 10
Area: 15.199

Extension Task #1


Create some extra functions to calculate the area of a square, of a rectangle and of a disc. Each function will need to accept the relevant parameters needed to calculate the area of the desired shape.

Extension Task #2


Create a menu system, where the user is asked what shapes they would like to calculate the area of before being asked to enter the relevant dimensions.

Did you know?


Illustration of Hero's Aeolipile (Steam Engine)

Illustration of Hero’s Aeolipile (Steam Engine)

Hero published a well-recognized description of a steam-powered device called an aeolipile (sometimes called a “Hero engine”). Among his most famous inventions was a windwheel, constituting the earliest instance of wind harnessing on land.

Tagged with:

Linear Search Functions

liear-search-algorithmFor this programming challenge we will investigate different functions which will all be based on a linear search algorithm.

Let’s consider a teacher who has decided to keep track of rewards issued to their students throughout the term by adding their name at the end of a text file each time they win a reward for their positive attitude and effort in lessons.

The teacher would like to write a few Python functions to:

  • scan the content of the text file and check if a particular students has received a reward or not,
  • count the number rewards a student has received throughout the term.
  • locate a student in the text file (identify the position/line number where the student’s name appear in the text file)

The teacher has started the code by creating a function called readTextFile() that takes a parameter called filename/ This function scan the context of the text file and return a list of all the names listed in the text file.

Using flowcharts, the teacher then worked out the algorithms for the extra functions they would like you to implement and test to complete the code. You can access these flowcharts below.

Is Listed?Rewards CountFind Position
The first function that you will need to implement is called isListed(), takes two parameters value and list and returns True if the value can be found in the list, false otherwise. To test this function you will need to implement the following algorithms:
flowchart-function-is-listed
Click on the above flowcharts to open in a new window

The third function is called count(), takes two parameters value and list and returns number of times the searched value appears in the list. To test this function you will need to implement the following algorithms used to count the number of rewards a student has received throughout the term.
flowchart-function-count
Click on the above flowcharts to open in a new window

The second function to implement is called findPosition() takes two parameters value and list and returns the position (starting at position 1) of the value in the list or -1 if the item is not found. To test this function you will need to implement the following algorithms used to locate a name in the text file by identifying the line number where such name appears in the file.
flowchart-function-find-position
Click on the above flowcharts to open in a new window

Python Code


You can now complete and test all three functions using the flowcharts provided above. The trinket below contains two tabs. In the second tab called “rewards.txt” you can access the content of the text file.

Alternative Approach


The Python syntax allows you to use loop through a list of values as follows:

for value in list:
   print(value)

Not all programming languages will let you use this syntax. An alternative approach is to use indices:

for i in range(0,len(list)):
   print(list[i])

In this case the flowchart for our count() function would become:
flowchart-count-function-length

unlock-access

Solution...

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

Leap Year Subroutine

calendar-iconA leap year is a calendar year that contains an additional day (29th of February) added to keep the calendar year synchronised with the astronomical year or seasonal year (which contains roughly 365¼ days or 365.242375 days to be more accurate).

An easy way to work out if a year is a leap year or not is to check if the year (e.g. 2020) is a multiple of 4. If it is, then it is most likely a leap year. Indeed, the rule is slightly more complex than this and can be summarised in three statements:

  • Leap years are any year that can be exactly divided by 4 (such as 2004, 2008, 2012, 2016, 2020, 2024, etc)
  • except if it can be exactly divided by 100, then it isn’t a leap year (such as 2100, 2200, etc)
  • except if it can be exactly divided by 400, then it is a leap year (such as 2000, 2400, 2800, etc)

In Python to work out if a number is a multiple of 4, we can calculate the remainder (MOD) of dividing this number by 4. If this remainder is equal to zero, then the number is a multiple of 4.

Based on this we can create a small function that will take a number (year) as a parameter and return whether the given year is a leap year or not. Here is the flowchart for this function called isLeapYear():
flowchart-leap-year

We can then this function in any program where we need to work out if a year is a leap year or not. For instance, we can create a program that:

  • Asks the user to enter a year (e.g. 2020)
  • Check if the year entered is a leap year or not (using our isLeapYear() function!)
  • Outputs a message to inform the user if the year is a leap year or not.

Here is the flowchart for this program:
isleapyear-flowchart

Video Tutorial


Your Task:


Use Python code to implement both the isLeapYear() function and the main program based on the above flowcharts.

Test Plan:


Once your code is done, complete the following tests to check it is working as expected:

Test # Input Values Expected Output Pass/Fail?
#1 Year: 2020 2020 is a leap year.
It contains 366 days.
#2 Year: 2021 2021 is not a leap year.
It contains 365 days.
#3 Year: 2056 2056 is a leap year.
It contains 366 days.
#4 Year: 2100 2100 is a not a leap year.
It contains 365 days.
#5 Year: 2400 2400 is a leap year.
It contains 366 days.
unlock-access

Solution...

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

SQL Investigation: The Stolen Gemstones


On July the 12th, a hundred prestigious guests were invited to the Precious Gemstones Exposition at the famous Royal Castle, England.
Precious-Gemstones-Exposition
This exposition provides a unique opportunity to admire the most precious and valuable gemstones in the world.
gemstones
The gemstones were exposed in the different rooms of the castle and were protected with a state-of-the-art security system.

At 10:12pm, a power cut left all the guests in the dark for a duration of just under five minutes. At the same time, the security system was deactivated.

When the power returned, the visitors were aghast to see that the twelve most precious gemstones of the exposition had simply vanished. The twelve gemstones were located in twelve different rooms. It would have been impossible for a single individual to steal more than one gemstone in such a short time. This means that this carefully planned robbery has been performed by a team of at least twelve robbers.

The guests have collected evidence left behind by the robbers and have asked you to use it to identify the potential robbers.

You have also been given access to a database of all staff members and guests who were present on that night.

TextFilesuspects.csv

You can download this database as a CSV file and use it on your own computer (e.g. import the data using MS Access or Apache Open Office).

You can also access and query this database online using our online SQL Editor:
Open in new windowAccess Online Database / SQL Editor

Will you be able to identify the twelve robbers and confront them to retrieve the precious gemstones? To do so you will need to write and execute twelve different SQL queries using the set of clues listed below.. Here are some examples of SQL queries based on the suspects table:

SELECT * FROM suspects WHERE gender="MALE" AND Nationality="Australia";
SELECT * FROM suspects WHERE firstname like "A%";
SELECT * FROM suspects WHERE gender="Male" AND (nationality="USA" OR nationality="Canada");
SELECT * FROM suspects WHERE height>=1.80 AND staff=TRUE;

RubySapphireOnyxTopazDiamondTanzanitePink SapphireQuartzEmeraldAmberPeridotAmethyst
gemstone-rubyThe first gemstone is an intense red ruby which was exposed in the main lounge.

It would appear that the robber broke the glass case to grab the precious stone. They then broke the window and jumped outside.

Footprints have been found outside just below the broken window. The shoes are male shoes, size 10.5. They are not the type of shoes worn by the staff as part of their uniform. So the first robber must be one of the guests.

Can you use these clues to identify a potential culprit from the guests and staff list?

gemstone-sapphireThe second stone is the world largest blue sapphire. It was stolen from the dining room.

The robber seems to have hurt themselves when breaking the glass case protecting the gemstone. Some blood stains have been found on the carpet. A handkerchief has also been found with blood stains. It has most likely been inadvertently dropped by the robber who used it to clean their wound. On the handkerchief we can see two embroidered initials A.H.

Can you find anyone on the guests list with the initials A.H.?

gemstone-onyxThis rare semi-translucent Onyx was exposed in the billiard room. A long blond hair has been found just next to the stand where the Onyx was displayed. The length of the hair suggests a female robber.

The back door of the billiard room was open. This door is equipped with a magnetic card/badge reader and can therefore only be opened by staff members from the security team.

gemstone-topazThis clear topaz was exposed in the centre of the ballroom. A candle from the main chandelier was found on the floor. This would suggest that, while leaving the room in the dark, the robber inadvertently hit the chandelier. This means that the robber must be at least 1.85m tall.

A wine glass was found next to the stand where the topaz was exposed. Red lipstick marks can be seen on the glass which would indicate a female robber.

gemstone-diamondThe diamond was exposed in the library. A post-it note was found on the floor and one can assume it fell off the robber’s pocket or handbag. Some handwritten symbols appear on the post-it note but these are written using the Mandarin alphabet.

We can deduct that the robber may come from China, Taiwan or Singapore.

gemstone-tanzaniteThe tanzanite was exposed in the small lounge/tearoom.

On their way out of the room, the robber must have caught their jacket on the door hatch, ripping off a piece of the jacket and inside pocket. Inside this pocket, the guests found a torn piece of a business card where part of a name can be seen: “Mr Oli…” We can assume that the robber is a man and his first name or his last name starts with the letters “OLI”..

The jacket is not part of the staff uniform, so the robber must be a one of the guests.

gemstone-pink-sapphireThe pink sapphire was exposed on the upstairs landing area. On their way out, the robber must have fallen down the stairs, as the guests reported hearing a loud noise. They also heard someone swear in English. The robber dropped their “Exposition information pack” which was given to all guests. In this pack an extra vegan menu page was found. This page is only given to guests with a vegan diet.

We can assume that the robber is either American (USA), Canadian, English or Australian and is also vegan.

gemstone-quartzThe quartz was exposed in the kitchen.

A tray of Spanish tapas was presented on the kitchen table. The robber picked a few tapas with superior quality chorizo. This suggests that the robber is neither vegetarian nor vegan.

In the dustbin, an empty pack of disposable tissues was found. It had a price tag on it with a price of 8.5 kr (Danish Krones). This would indicate that the robber is most likely Danish.

gemstone-emeraldThe emerald was exposed in the study room. It would seem that the burglar had to force the window open to escape the room. An earring in the shape of the Eiffel Tower was found at the scene. It is believed to belong to a French female guest.

It is an expensive piece of jewellery and is unlikely that the staff members would wear such jewellery at work.

gemstone-amberThe amber was exposed in the main hall. A flower pot was knocked over during the robbery and the soil from the pot spread over the carpet. The robber walked over it and left a footprint on their way out. It appeared to be woman’s shoe with a size between 6 and 7.

The brand was also identified and is only sold in the following South American countries: Peru, Chile, Argentina, Brazil and Venezuela.

gemstone-peridotThe peridot was exposed in the master bedroom. When the guests arrived at the scene, they could smell a subtle scent of jasmine, an essence used in women’s perfumes.

In the fireplace, some warm ashes of paper were found. However, the paper did not burn fully. It appears to be a plane ticket, indicating a flight leaving from Dublin Airport (Ireland). We would therefore assume that the robber might be a guest from Ireland.

gemstone-amethystThe amethyst was exposed in the royal suite.

The royal suite has a slanted roof with wooden beams. It would appear that the robber bumped their head on one of these beams as blood was found. It would suggest the robber was between 1.70m and 1.80m tall. When this happened, the robber dropped their cap. It is a men’s cap worn by the gardening staff at the Royal Castle.

unlock-access

Solution...

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

BBC micro:bit – Pong (1 Player)

BBC-microbit-PongIn this tutorial, we will create a simplified version of Pong for 1 player to play using a micro:bit.

The challenge is to create the game considering that the micro:bit screen consists of a 2D grid of 25 LEDs (5 by 5 grid).

As opposed to the real game of Pong, we will only use one paddle, located at the bottom of the screen. The player will control the paddle using the A button (to move the paddle to the left) and the B button (to move the paddle to the right).

A sprite will be used to represent the ball which will be bouncing against the top, left and right edges of the screen and against the paddle. If the use fails to catch the ball, the ball will reach the bottom edge of the screen which will trigger a game over message.

To implement this game you will need to use the micro:bit website to create the code using the JavaScript Block Editor.

micro-bit-logo

Step 1: Initialising the game


First we will initialise the main sprites:
BBC-microbit-pong-onstart
The main sprites are:

  • The ball sprite will start on the top row (y = 0) at a random x position (between 0 and 4). The ball will also be given a direction using two variables: directionX and directionY. The following diagram represents the 6 different directions of the ball sprite on the 2D grid.
    bbc-microbit-pong-directions
    When we first initialise the ball and position it at the top of the screen, we also set a direction where the ball is aiming downwards (direction 4, 5 or 6 from the diagram above).
  • The paddle consists of 2 sprites, paddleA and paddleB, as a sprite only consists of 1 LED, we used two sprites next to each other to create a wider paddle (as wide as 2 LEDs). The paddle is located on the bottom row (y = 4) and can be moved horizontally by pressing the left and right buttons of the micro:bit using the following code:
  • BBC-microbit-pong-onbutton-pressed

    Step 2: Bouncing ball algorithm


    The most complex part of the game is to control the movement of the ball sprite. Every 500ms, the ball moves in the direction set by the (directionX,directionY) vector. Based on its new position the code provided below detects different possible scenarios:

    • The ball should bounce against the left, top, and right edges of the screen. Each bounce will affect its direction.
    • The ball should bounce against the paddle. Once again, a bounce will affect the direction of the ball.
    • If the ball reaches the bottom edge of the screen, a game over message should be displayed.

    BBC-microbit-pong-forever

    The code is now complete. You can recreate the game and then customise it further by adding a scoring system, or by making the ball move faster (using a shorter delay/pause) every time the ball hits the paddle.

Tagged with:

Breakout Tutorial using Pygame: Adding a Brick Wall

break-out-gameThis tutorial is the second tutorial in a series of five Pygame tutorials:

The final stage of our tutorial focuses on adding a brick wall and a scoring system to our Breakout game:

  • The player will score a point if the ball bounces against a brick.
  • The player will lose a life if the ball bounces against the bottom edge of the screen.
  • Both the score and number of lives will be displayed at the top of the screen.
  • A “Level Complete” message will be displayed if all bricks have been removed.
  • A “Game Over” message will be displayed if the number of lives reaches zero.
  • The final code for the main.py is provided below. We made several changes to the code as follows:

    • On line 6 we import the Brick class. (Code provided in the brick.py tab)
    • On lines 39 to 57 we create three rows of bricks and add them to a group called all_bricks.
    • On lines 93 to 103 we take a life away when the ball hit the bottom edge of the screen. If the number of lives reaches zero, we display a “Game Over” message..
    • On lines 114 to 129 we detect if the ball hits a brick. If so we remove the brick (using the kill() method) and increment the score by one.
    main.pypaddle.pyball.pybrick.py
    #Import the pygame library and initialise the game engine
    import pygame
    #Let's import the Paddle Class & the Ball Class
    from paddle import Paddle
    from ball import Ball
    from brick import Brick
    
    pygame.init()
    
    # Define some colors
    WHITE = (255,255,255)
    DARKBLUE = (36,90,190)
    LIGHTBLUE = (0,176,240)
    RED = (255,0,0)
    ORANGE = (255,100,0)
    YELLOW = (255,255,0)
    
    score = 0
    lives = 3
    
    # Open a new window
    size = (800, 600)
    screen = pygame.display.set_mode(size)
    pygame.display.set_caption("Breakout Game")
    
    #This will be a list that will contain all the sprites we intend to use in our game.
    all_sprites_list = pygame.sprite.Group()
    
    #Create the Paddle
    paddle = Paddle(LIGHTBLUE, 100, 10)
    paddle.rect.x = 350
    paddle.rect.y = 560
    
    #Create the ball sprite
    ball = Ball(WHITE,10,10)
    ball.rect.x = 345
    ball.rect.y = 195
    
    all_bricks = pygame.sprite.Group()
    for i in range(7):
        brick = Brick(RED,80,30)
        brick.rect.x = 60 + i* 100
        brick.rect.y = 60
        all_sprites_list.add(brick)
        all_bricks.add(brick)
    for i in range(7):
        brick = Brick(ORANGE,80,30)
        brick.rect.x = 60 + i* 100
        brick.rect.y = 100
        all_sprites_list.add(brick)
        all_bricks.add(brick)
    for i in range(7):
        brick = Brick(YELLOW,80,30)
        brick.rect.x = 60 + i* 100
        brick.rect.y = 140
        all_sprites_list.add(brick)
        all_bricks.add(brick)
    
    # Add the paddle and the ball to the list of sprites
    all_sprites_list.add(paddle)
    all_sprites_list.add(ball)
    
    # 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 exit this loop
    
        #Moving the paddle when the use uses the arrow keys
        keys = pygame.key.get_pressed()
        if keys[pygame.K_LEFT]:
            paddle.moveLeft(5)
        if keys[pygame.K_RIGHT]:
            paddle.moveRight(5)
    
        # --- Game logic should go here
        all_sprites_list.update()
    
        #Check if the ball is bouncing against any of the 4 walls:
        if ball.rect.x>=790:
            ball.velocity[0] = -ball.velocity[0]
        if ball.rect.x<=0:
            ball.velocity[0] = -ball.velocity[0]
        if ball.rect.y>590:
            ball.velocity[1] = -ball.velocity[1]
            lives -= 1
            if lives == 0:
                #Display Game Over Message for 3 seconds
                font = pygame.font.Font(None, 74)
                text = font.render("GAME OVER", 1, WHITE)
                screen.blit(text, (250,300))
                pygame.display.flip()
                pygame.time.wait(3000)
    
                #Stop the Game
                carryOn=False
    
        if ball.rect.y<40:
            ball.velocity[1] = -ball.velocity[1]
    
        #Detect collisions between the ball and the paddles
        if pygame.sprite.collide_mask(ball, paddle):
          ball.rect.x -= ball.velocity[0]
          ball.rect.y -= ball.velocity[1]
          ball.bounce()
    
        #Check if there is the ball collides with any of bricks
        brick_collision_list = pygame.sprite.spritecollide(ball,all_bricks,False)
        for brick in brick_collision_list:
          ball.bounce()
          score += 1
          brick.kill()
          if len(all_bricks)==0:
               #Display Level Complete Message for 3 seconds
                font = pygame.font.Font(None, 74)
                text = font.render("LEVEL COMPLETE", 1, WHITE)
                screen.blit(text, (200,300))
                pygame.display.flip()
                pygame.time.wait(3000)
    
                #Stop the Game
                carryOn=False
    
        # --- Drawing code should go here
        # First, clear the screen to dark blue.
        screen.fill(DARKBLUE)
        pygame.draw.line(screen, WHITE, [0, 38], [800, 38], 2)
    
        #Display the score and the number of lives at the top of the screen
        font = pygame.font.Font(None, 34)
        text = font.render("Score: " + str(score), 1, WHITE)
        screen.blit(text, (20,10))
        text = font.render("Lives: " + str(lives), 1, WHITE)
        screen.blit(text, (650,10))
    
        #Now let's draw all the sprites in one go. (For now we only have 2 sprites!)
        all_sprites_list.draw(screen)
    
        # --- 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()
    The code for the Paddle class remains unchanged.

    import pygame
    BLACK = (0,0,0)
    
    class Paddle(pygame.sprite.Sprite):
        #This class represents a paddle. 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 paddle, its width and height.
            # Set the background color and set it to be transparent
            self.image = pygame.Surface([width, height])
            self.image.fill(BLACK)
            self.image.set_colorkey(BLACK)
    
            # Draw the paddle (a rectangle!)
            pygame.draw.rect(self.image, color, [0, 0, width, height])
    
            # Fetch the rectangle object that has the dimensions of the image.
            self.rect = self.image.get_rect()
    
    
        def moveLeft(self, pixels):
            self.rect.x -= pixels
    	    #Check that you are not going too far (off the screen)
            if self.rect.x < 0:
              self.rect.x = 0
    
        def moveRight(self, pixels):
            self.rect.x += pixels
            #Check that you are not going too far (off the screen)
            if self.rect.x > 700:
              self.rect.x = 700
    
    The code for the Ball class remains unchanged.

    import pygame
    from random import randint
    
    BLACK = (0, 0, 0)
     
    class Ball(pygame.sprite.Sprite):
        #This class represents a ball. 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 ball, its width and height.
            # Set the background color and set it to be transparent
            self.image = pygame.Surface([width, height])
            self.image.fill(BLACK)
            self.image.set_colorkey(BLACK)
     
            # Draw the ball (a rectangle!)
            pygame.draw.rect(self.image, color, [0, 0, width, height])
            
            self.velocity = [randint(4,8),randint(-8,8)]
            
            # Fetch the rectangle object that has the dimensions of the image.
            self.rect = self.image.get_rect()
            
        def update(self):
            self.rect.x += self.velocity[0]
            self.rect.y += self.velocity[1]
              
        def bounce(self):
            self.velocity[0] = -self.velocity[0]
            self.velocity[1] = randint(-8,8)
    
    This is the code for the new Brick class, to be saved in a new file called brick.py.

    import pygame
    BLACK = (0,0,0)
    
    class Brick(pygame.sprite.Sprite):
        #This class represents a brick. 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 brick, 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(BLACK)
            self.image.set_colorkey(BLACK)
    
            # Draw the brick (a rectangle!)
            pygame.draw.rect(self.image, color, [0, 0, width, height])
    
            # Fetch the rectangle object that has the dimensions of the image.
            self.rect = self.image.get_rect()
    
    Tagged with:

    Breakout Tutorial using Pygame: Adding a Bouncing Ball

    break-out-gameThis tutorial is the second tutorial in a series of five Pygame tutorials:

    Our aim is to add the bouncing ball to our Breakout game. To do so we will create a new class called Ball.

    Bouncing Algorithm


    To understand how to implement a bouncing algorithm, it is essential to understand how the computer controls the trajectory of a sprite (e.g. ball) on the screen. Arcade games are based on a frame based animation where the screen is refreshed every x milliseconds. Moving sprites are positionned using (x,y) coordinates and have a velocity vector (Vx,Vy) which specifies the delta in pixels to apply to the (x,y) coordinates of a sprite between two frames:

    • frame n: Sprite Coordinates: (x,y)
    • frame n+1: Sprite Coordinates: (x+Vx,y+Vy)

    velocity-vector

    As the sprite moves across the screen, it may need to bounce against another sprite or against the edge of the screen.

    Let’s investigate how the velocity vector is affected when the sprite bounces against vertical and horizontal walls/edges.

    Right Wall/EdgeLeft Wall/EdgeTop Wall/EdgeBottom Wall/Edge
    bouncing-algorithm-right
    bouncing-algorithm-left
    bouncing-algorithm-top
    bouncing-algorithm-bottom

    Ball Class


    Below is the code for the Ball class. You will need to copy this code in a new Python file called ball.py. The update() method of this class will be called for each frame of the main program loop. It moves (changes the (x,y) coordinates of) the ball using its velocity vector.

    import pygame
    from random import randint
    BLACK = (0,0,0)
    
    class Ball(pygame.sprite.Sprite):
        #This class represents a ball. 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 ball, its width and height.
            # Set the background color and set it to be transparent
            self.image = pygame.Surface([width, height])
            self.image.fill(BLACK)
            self.image.set_colorkey(BLACK)
     
            # Draw the ball (a rectangle!)
            pygame.draw.rect(self.image, color, [0, 0, width, height])
            
            self.velocity = [randint(4,8),randint(-8,8)]
            
            # Fetch the rectangle object that has the dimensions of the image.
            self.rect = self.image.get_rect()
            
        def update(self):
            self.rect.x += self.velocity[0]
            self.rect.y += self.velocity[1]
    

    Adding the ball to the game


    In the main.py file, we will first import the Ball class. (See line 5) We will then create an object called ball using the Ball class. (See lines 33 to 36) We will add this object to the all_sprites_list group of sprites. (See line 40)

    We will also apply the bouncing algorithm to check if it needs to bounce against any of the four walls. (See lines 65 to 73)

    #Import the pygame library and initialise the game engine
    import pygame
    #Let's import the Paddle Class & the Ball Class
    from paddle import Paddle
    from ball import Ball
    
    pygame.init()
    
    # Define some colors
    WHITE = (255,255,255)
    DARKBLUE = (36,90,190)
    LIGHTBLUE = (0,176,240)
    RED = (255,0,0)
    ORANGE = (255,100,0)
    YELLOW = (255,255,0)
    
    score = 0
    lives = 3
    
    # Open a new window
    size = (800, 600)
    screen = pygame.display.set_mode(size)
    pygame.display.set_caption("Breakout Game")
    
    #This will be a list that will contain all the sprites we intend to use in our game.
    all_sprites_list = pygame.sprite.Group()
    
    #Create the Paddle
    paddle = Paddle(LIGHTBLUE, 100, 10)
    paddle.rect.x = 350
    paddle.rect.y = 560
    
    #Create the ball sprite
    ball = Ball(WHITE,10,10)
    ball.rect.x = 345
    ball.rect.y = 195
    
    # Add the paddle to the list of sprites
    all_sprites_list.add(paddle)
    all_sprites_list.add(ball)
    
    # 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 exit this loop
    
        #Moving the paddle when the use uses the arrow keys
        keys = pygame.key.get_pressed()
        if keys[pygame.K_LEFT]:
            paddle.moveLeft(5)
        if keys[pygame.K_RIGHT]:
            paddle.moveRight(5)
    
        # --- Game logic should go here
        all_sprites_list.update()
    
        #Check if the ball is bouncing against any of the 4 walls:
        if ball.rect.x>=790:
            ball.velocity[0] = -ball.velocity[0]
        if ball.rect.x<=0:
            ball.velocity[0] = -ball.velocity[0]
        if ball.rect.y>590:
            ball.velocity[1] = -ball.velocity[1]
        if ball.rect.y<40:
            ball.velocity[1] = -ball.velocity[1]
    
        # --- Drawing code should go here
        # First, clear the screen to dark blue.
        screen.fill(DARKBLUE)
        pygame.draw.line(screen, WHITE, [0, 38], [800, 38], 2)
    
        #Display the score and the number of lives at the top of the screen
        font = pygame.font.Font(None, 34)
        text = font.render("Score: " + str(score), 1, WHITE)
        screen.blit(text, (20,10))
        text = font.render("Lives: " + str(lives), 1, WHITE)
        screen.blit(text, (650,10))
    
        #Now let's draw all the sprites in one go. (For now we only have 2 sprites!)
        all_sprites_list.draw(screen)
    
        # --- 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()
    

    Collision Detection


    The next addition to our game is to detect when the ball hits/collides with one the two paddles. If it does, we will make it bounce using a random new direction.

    So first, let’s add a new method called bounce() to our Ball class.

    Then, in the main program loop, let’s add some code to detect if the ball sprite collides with the paddleA or paddleB sprites. If it does we will call the bounce() method of the Ball class.

    ball.pymain.py
    We have added the bounce() method on lines 30 to 32.

    import pygame
    from random import randint
    BLACK = (0, 0, 0)
    
    class Ball(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(BLACK)
            self.image.set_colorkey(BLACK)
     
            # Draw the ball (a rectangle!)
            pygame.draw.rect(self.image, color, [0, 0, width, height])
            
            self.velocity = [randint(4,8),randint(-8,8)]
            
            # Fetch the rectangle object that has the dimensions of the image.
            self.rect = self.image.get_rect()
            
        def update(self):
            self.rect.x += self.velocity[0]
            self.rect.y += self.velocity[1]
            
        def bounce(self):
            self.velocity[0] = -self.velocity[0]
            self.velocity[1] = randint(-8,8)
    
    We have added on lines 75 to 79 the code to detect a collision between the ball and the paddles.

    # Import the pygame library and initialise the game engine
    import pygame
    #Let's import the Paddle Class & the Ball Class
    from paddle import Paddle
    from ball import Ball
    
    pygame.init()
    
    # Define some colors
    WHITE = (255,255,255)
    DARKBLUE = (36,90,190)
    LIGHTBLUE = (0,176,240)
    RED = (255,0,0)
    ORANGE = (255,100,0)
    YELLOW = (255,255,0)
    
    score = 0
    lives = 3
    
    # Open a new window
    size = (800, 600)
    screen = pygame.display.set_mode(size)
    pygame.display.set_caption("Breakout Game")
    
    #This will be a list that will contain all the sprites we intend to use in our game.
    all_sprites_list = pygame.sprite.Group()
    
    #Create the Paddle
    paddle = Paddle(LIGHTBLUE, 100, 10)
    paddle.rect.x = 350
    paddle.rect.y = 560
    
    #Create the ball sprite
    ball = Ball(WHITE,10,10)
    ball.rect.x = 345
    ball.rect.y = 195
    
    # Add the paddle and the ball to the list of sprites
    all_sprites_list.add(paddle)
    all_sprites_list.add(ball)
    
    # The loop will carry on until the user exit 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 exit this loop
    
        #Moving the paddle when the use uses the arrow keys
        keys = pygame.key.get_pressed()
        if keys[pygame.K_LEFT]:
            paddle.moveLeft(5)
        if keys[pygame.K_RIGHT]:
            paddle.moveRight(5)
    
        # --- Game logic should go here
        all_sprites_list.update()
    
        #Check if the ball is bouncing against any of the 4 walls:
        if ball.rect.x>=790:
            ball.velocity[0] = -ball.velocity[0]
        if ball.rect.x<=0:
            ball.velocity[0] = -ball.velocity[0]
        if ball.rect.y>590:
            ball.velocity[1] = -ball.velocity[1]
        if ball.rect.y<40:
            ball.velocity[1] = -ball.velocity[1]
    
        #Detect collisions between the ball and the paddles
        if pygame.sprite.collide_mask(ball, paddle):
          ball.rect.x -= ball.velocity[0]
          ball.rect.y -= ball.velocity[1]
          ball.bounce()
    
        # --- Drawing code should go here
        # First, clear the screen to dark blue.
        screen.fill(DARKBLUE)
        pygame.draw.line(screen, WHITE, [0, 38], [800, 38], 2)
    
        #Display the score and the number of lives at the top of the screen
        font = pygame.font.Font(None, 34)
        text = font.render("Score: " + str(score), 1, WHITE)
        screen.blit(text, (20,10))
        text = font.render("Lives: " + str(lives), 1, WHITE)
        screen.blit(text, (650,10))
    
        #Now let's draw all the sprites in one go. (For now we only have 2 sprites!)
        all_sprites_list.draw(screen)
    
        # --- 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()
    

    Next Step?


    The final touch consists of adding a scoring system:
    Breakout Tutorial using Pygame:Adding a Brick Wall
    Tagged with: