More results...

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

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: , ,

Using text files in Python

file-handling

Learning Objectives


In this post you will learn how to code the main file handling operations to manipulate text files as follows:

  • Opening a file
  • Reading from a text file
  • Reading writing to a text file
  • Appending to a text file
  • Closing a file
Open a fileClose a fileReadWriteAppend to
To open a file use the following code:

file = open("myTextFile.txt","r")

Folder name/File name


When opening a text file you need to specify the filename you want to open. If the file is not stored in the same folder as your Python file, you will also need to specify the location (e.g. subfolder) where the text file is saved. E.g.

file = open("myFolder/myTextFile.txt","r")

Access Mode


When opening the file you have to specify the access mode using one of the following codes:

Mode Description
r Opens a file in read only mode. This is the default mode.
r+ Opens a file for both reading and writing.
w Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist yet, it will create the new file for writing.
w+ Opens a file for both writing and reading. Overwrites the file if the file exists. If the file does not exist yet, it will create the new file for writing.
a Opens a file for appending. The file pointer is at the end of the file. So new data will be added at the end of the file. If the file does not exist, it creates a new file for writing.
a+ Opens a file for both appending and reading. The file pointer is at the end of the file. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.
Once you have finished using your file, make sure that you close this file! It will free up resources and allow other users/processes to access this file if they need to.
Closing a file is extremely easy using the close method.

file.close()
To read a text file, line by line, you will need to:

  1. Open the text file in read mode (either “r” or “r+”),
  2. Loop through the text file, line by line, using a for loop,
  3. Close the text file.

Reading line by line

file = open("myTextFile.txt","r")

for line in file:
  print(line)
  
file.close()

What’s About CSV files?


CSV files (Comma Separated Values) are text files that store data where each record is stored on a line and each field is separated using a comma “,”. Sometimes we use other symbols instead of the comma such as a semi-colon “;” or a pipe “|”.
In this case when reading a line of the text file you can use the split() method to then access each field one by one.

file = open("myTextFile.txt","r")

for line in file:
  data = line.split(";")
  print(data[0] + " - " + data[1] + " - " + data[2])
  
file.close()
To write to a text file you will need to:

  1. Open the text file in read mode: “w”,
  2. Write to the file using the write() method,
  3. Close the text file.

Be careful, when using the write command, you are overwriting the content of your file. If instead of overwriting the content of your file you want to append (write at the end of the file) check the next tab: “Append to a text file”.

Note that when opening the text file, if the file specified does not exist, Python will create a new file automatically.

Writing to a text file

file = open("myTextFile.txt","w")

file.write("Hello World\n");
  
file.close()

The “\n” at the end of the text means “new line”. Only use it if you want the next call to the write() method to start on a new line.

The write method will overwrite the content of your file. If instead you want to write at the end of a text file you can use the “Append access mode”:

To append to a text file you will need to:

  1. Open the text file in append mode: “a”,
  2. Write to the file using the write() method,
  3. Close the text file.

Appending to a text file

file = open("myTextFile.txt","a")

file.write("Hello World\n");
  
file.close()

The “\n” at the end of the text means “new line”. Only use it if you want the next call to the write() method to start on a new line.

Practice makes perfect


Try one of these challenges to put into practice what you have learnt about file handling operations.
Class Register(Handling Text Files) My Mp3 Playlist(Handling Text Files)

London 2012

london-2012

Learning Objectives


In this challenge we are going to investigate methods that can be used to:

  • Read and extract data from a text file,
  • Sort this data in ascending or descending order,
  • Display this sorted data on screen.

Context


We have a text file with the list of the 10 top countries at the London 2012 Olympic Games. (Countries which won the most gold medals). This data is not sorted and is organised as follows:

Name of Country;Number of Gold Medals;Number of Silver Medals;Number of Bronze Medals

You can download this text file:

TextFilecountries.txt

Step by Step


To achieve our goal of reading the text file, sorting its data and displaying it on the screen we will proceed in 5 steps:
5steps

Python Code


Your Challenge


Tweak this code to:

  • Sort this list in ascending order of gold medals
  • Sort this list in alphabetical (ascending) order of name of country
  • Sort this list in descending order of silver medals
  • Sort this list in descending order of bronze medals
  • Sort this list in descending order of total number of medals (Bronze + Silver + Gold medals)

unlock-access

Solution...

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

Batman vs. Python Turtle

For this challenge we are focusing on a set of equations used to draw different sections of the Batman logo:

  • f(x) = 1.5*sqrt((‑abs(abs(x) – 1)) * abs(3 – abs(x))/((abs(x) – 1)*(3 – abs(x)))) * (1+abs(abs(x) – 3)/(abs(x)- 3)) * sqrt(1 – (x/7)^2)+(4.5+0.75 * (abs(x – 0.5)+abs(x+0.5)) – 2.75 * (abs(x-0.75)+abs(x+0.75))) * (1+abs(1 – abs(x))/(1 – abs(x)))
  • g(x) = (‑3)*sqrt(1 -(x/7)^2) * sqrt(abs(abs(x) – 4)/(abs(x)-4))
  • h(x) = abs(x/2) – 0.0913722 * x^2-3+sqrt(1 – (abs(abs(x) – 2) – 1)^2)
  • i(x) = (2.71052+1.5 – 0.5 * abs(x) – 1.35526 * sqrt(4 – (abs(x) – 1)^2)) * sqrt(abs(abs(x) – 1)/(abs(x) – 1))

We will import two Python libraries:

  • math library to use functions such as sqrt() and fabs(),
  • turtle library to draw/plot on the screen using x and y coordinates.

Batman Logo:


Your Challenge


Check the following page for additional maths equations to draw heart shapes. See how you could tweak the code given above to reuse these equations and draw a heart shape on screen.

Tagged with: ,