More results...

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

Pong Tutorial using Pygame – Adding the Paddles

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

Learning Objectives


In this second tutorial on how to create the retro arcade game Pong using PyGame we are looking at creating our first sprites.
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 called Paddle and derive our first objects (paddleA and paddleB) from this class.

Pong is a two player game so playerA will be able to control the first paddle (paddleA) using the W and S keys (w for moving the paddle upwards, S for moving it downwards) while playerB will use the up and down arrow keys.

Our first Class


So let’s look at the code for our Paddle 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
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()

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 objects: the pladdles of both players (paddleA and paddleB)

So let’s save our class as a python file called paddle.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 Paddle class.

#Let's import the Paddle Class
from paddle import Paddle

Then we need to create and position our sprites in our main program using the following lines of code:

paddleA = Paddle(WHITE, 10, 100)
paddleA.rect.x = 20
paddleA.rect.y = 200

paddleB = Paddle(WHITE, 10, 100)
paddleB.rect.x = 670
paddleB.rect.y = 200

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

Let’s reuse the code from the first tutorial.

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

On line 25 we are declaring a list called all_sprites_list that will store all the sprites we will create in our game. (For now just two sprites, paddleA and paddleB.)

From line 22 we are creating our first sprites/objects using the Paddle Class. Notice how when declaring our first object we use the parameters from its constructor (__init__()), in this case, the colour, width and height of the paddle we want to create.

Now that we have created our first sprites we need to add them to our list of spites: all_sprites_list. This is what happens on line 28 and 29.

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 the pygame library and initialise the game engine
import pygame
from paddle import Paddle

pygame.init()

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

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

paddleA = Paddle(WHITE, 10, 100)
paddleA.rect.x = 20
paddleA.rect.y = 200

paddleB = Paddle(WHITE, 10, 100)
paddleB.rect.x = 670
paddleB.rect.y = 200

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

# Add the paddles to the list of sprites
all_sprites_list.add(paddleA)
all_sprites_list.add(paddleB)

# 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
        elif event.type==pygame.KEYDOWN:
                if event.key==pygame.K_x: #Pressing the x Key will quit the game
                     carryOn=False  
 
    # --- Game logic should go here
    all_sprites_list.update()
 
 
    # --- Drawing code should go here
    # First, clear the screen to black. 
    screen.fill(BLACK)
    #Draw the net
    pygame.draw.line(screen, WHITE, [349, 0], [349, 500], 5)
    
    #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()

That’s it… You are now ready to move to our third tutorial to learn how to control your sprites using the arrow keys.
Pong Tutorial using PygameControlling the paddles

Tagged with:

Pong Tutorial using Pygame – Getting Started

pong-gameThis tutorial is the first tutorial in a series of five Pygame tutorials:

Pong is one of the earliest arcade video games, first released in 1972 by Atari. It is a two-player game based on table tennis. The game features simple 2D graphics. It consists of two paddles used to return a bouncing ball back and forth across the screen. The score is kept by the numbers at the top of the screen.

In this tutorial we are going to recreate a game of Pong using Python and the Pygame library. The Pygame library is the perfect library to build basic 2D arcade games and to start developing your OOP skills. (Object-Oriented Programming)

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: Defining 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. Pong is a very basic game and only uses two colours: black and white.

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

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("Pong")

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.

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

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

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

# 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
 
    # --- Game logic should go here
 

 
    # --- Drawing code should go here
    # First, clear the screen to black. 
    screen.fill(BLACK)
    #Draw the net
    pygame.draw.line(screen, WHITE, [349, 0], [349, 500], 5)
 
    # --- 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?


Your background is ready? Let’s add the first sprite to your project by completing the next tutorial:
Pong Tutorial using Pygame:Adding the Paddles
Tagged with:

Pomodoro Timer

pomodoro-timerThe Pomodoro Technique is a time management method that can be used for a wide range of tasks. Many students use this technique to organise their revision time before an exam.

This Pomodoro Technique was developed by Francesco Cirillo in the late 1980s. It uses a timer to break down work into short intervals, typically 25 minutes in length, separated by short breaks (3 to 5 minutes). Each interval is known as a pomodoro, from the Italian word for “tomato” because Francesco Cirillo used a tomato-shaped kitchen timer when he was a university student.

The technique is an iterative process based on the following steps:

  1. Decide on a task to complete,
  2. Work on this task for 25 minutes (using a timer),
  3. When the timer stops/rings, put a check mark on a post-it note,
  4. If you have fewer than 4 check marks:
    • Take a short break (3 to 5 minutes),
    • Repeat this process from step 2,
  5. After 4 check marks (pomodoros):
    • Take a long break (15 to 30 minutes),
    • Reset your check mark counter to zero,
    • Repeat this process from step 2.

Pomodoro Timer – Algorithm/Flowchart


pomodoro-timer-flowchart

Your Task: (Python Code)


Use the above flowchart to implement a pomodoro timer using Python.

For testing purpose you can reduce the pomodoro intervals from 25 minutes to 10 seconds, the short breaks to 3 seconds and the long breaks to 5 seconds. Once your code will have been fully tested, you will reset it using more meaningful timings. (e.g. 25 minutes, 5 minutes, 30 minutes)

Extension Task #1:


To make your program more robust, you should make sure that the program only accepts a valid “Yes” or “No” answer to the question “Would you like to carry on?”.

To do so you will implement a validation routine to validate the user input. You can find more about Yes/No validation routines on this post.

Extension Task #2:


Add a few inputs at the start of the code for the user to change the settings of their pomodoro timer. The three settings that the user should be able to change are:

  • How long (in minutes) should a pomodoro interval last for (e.g. 25 minutes)?
  • How long (in minutes) should a short break last for (e.g. 5 minutes)?
  • How long (in minutes) should a long break last for (e.g. 30 minutes)?

Your program should then use the settings provided by the end-user.

unlock-access

Solution...

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

Enigma Crib Analysis

The Enigma machine was used in World War II to encrypt secret messages.

The enigma machine was used in World War II to encrypt secret messages.

During World War II, Enigma machines were used by the Germans to encrypt and decrypt military radio communications. An Enigma machine consists of a complex sets of interconnected rotors used to performs substitution and transposition ciphers to encrypt data. The Germans would change the enigma settings every day making it extremely difficult for the allies to break the Enigma code.

In order to crack the Enigma code, the allies decided to set up a team of code breakers (cryptanalysts) at Bletchley Park, UK. Amongst these, Alan Turing and Dillwyn Knox rapidly identified that the best approach to crack the Enigma code was to find a method to identify the Engima settings used by the German on that day. This is due to the fact that the same settings can be used to both encrypt a plaintext to cypher text and to decrypt a cipher text back to its original plaintext. In other words the Enigma machine is used to implement a symmetric encryption: knowing the key (Enigma settings) enables you to both encrypt and decrypt messages.

The method they identified to work out the Enigma settings relied on the use of cribs. The term crib was used at Bletchley Park to denote any known plaintext or suspected plaintext at some point in an enciphered message. Effectively code breakers realised that the Germans were regularly sending Weather reports (in German Wetter Vorhersage) and could identify the ciphertext containing these words (based on the time of the day these reports were sent). Another message that Germans often used was the message “Nothing to report” (in German Keine besonderen Ereignisse) which was also used to identify useful cribs.

So let’s consider the following encrypted message:
enigma-crib-ciphertext

Now let’s assume that we know (or strongly suspect) that this message contains the expression “SECRET MESSAGE”, but we are not sure at which position in the text this might be.

It could be that the plain text message starts with “SECRETMESSAGE” in this case the crib would be:
enigma-crib-ciphertext-pos1

However it could be that the expression “SECRETMESSAGE” is within the ciphertext at a different position. (not necessary at the very start of the message). E.g. If it was at position 5 the crib would then be:
enigma-crib-ciphertext-pos5

So when an encrypted message was intercepted and the code breakers suspected it may contain a crib, one of their first task was to identify the possible starting position of the crib to get a full crib (plaintext with matching ciphertext). To do so cryptanalysts exploited the property of the Enigma machine which ensured that it never encoded a letter as itself. So any crib that contained at least one letter encoded as itself could be automatically discarded. This hugely reduced the number of potential cribs that could then be exploited to try to work out the Enigma settings.

Using our intial ciphertext, you can see how most crib positions can be discarded, resulting in only two possible cribs:
enigma-crib-analysis

Python Challenge


In this challenge we will write a computer program to help cryptanalyst identify potential cribs from a ciphertext. Our program will use to inputs: a plaintext crib (e.g. SECRETMESSAGE) and a full cypher text. The program will then work out and return all potential cribs by investigating all possible positions of the crib in the cipher text and discarding invalid cribs (cribs containing a letter that would be encoded as itself).

Online Crib Analysis


You can use our online Crib Analysis page to test/compare the output of your code against our online solution.

Find out more


Find out more about Enigma and the Turing-Welchman Bombe which was used to break the Enigma code:

unlock-access

Solution...

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

Turing-Welchman Bombe Simulator

turing-welchman-bombe-4-drumsIn our Enigma – mission X challenge, we looked at how the Enigma machine was used by the Germans during WWII to encrypt radio communications and how code breakers were assigned the job to crack the code of the Enigma machine.

Considering that an Enigma M3 machine consists of three rotors (chosen from a set of five), the addition of the rotor settings with 26 positions, and the plugboard with ten pairs of letters connected means that an Enigma M3 has 158,962,555,217,826,360,000 (nearly 159 quintillion) different settings!

The break through that enabled code breakers to work out the Enigma settings came from the work of Alan Turing, Gordon Welchman and their associates at Bletchley Park who created a complex electro-mechanical device called the Bombe used to work out possible enigma settings (rotor settings & positions and plugboard connections) from a “crib”. The term crib originated at Bletchley Park and refers to a piece of plaintext with its matching ciphertext. Codebreakers noticed that the Germans were regularly sending Weather reports (in German Wetter Vorhersage) and could identify the ciphertext containing these words (based on the time of the day these reports were sent).

Another message that Germans often used was the message “Nothing to report” (in German Keine besonderen Ereignisse) which was also used to identify useful cribs.

During the war more than 200 Bombes were built to help decrypt hundreds of messages every day. All these machines were fully destroyed when the war ended. An actual reproduction of the Turing-Welchman Bombe can be found at the National Museum of Computing and additional explanations of how the Bombe worked is available at Bletchley Park.

Turing-Welchman Bombe Simulator


To gain a better understanding of how the Bombe worked, we decided to recreate an online simulator that you can use to workout Enigma settings from valid cribs.

Click on the picture below to access our online Turing-Welchman Bombe simulator and try to find the Enigma settings to decrypt the following cipher text:

SNMKG GSTZZ UGARL VYQGM YWMLU

turing-welchman-bombe

Tagged with: , ,

Enigma Daily Settings Generator

enigma-m3-ukw-bBefore attempting this challenge, you should familiarise yourself with the Enigma machine by completing the Enigma Mission X challenge.

Code Books were used by the Germans to list all the settings needed to set up the Enigma machines before starting to encrypt or decrypt messages. The Germans used to change the Enigma settings very regularly (e.g. once a day) so that if the Allies managed to break their code (find out the Enigma settings) they would only be able to use them for that day and would have to find the new settings every day. Code books were highly confidential documents as if a codebook was captured or reconstructed, messages could easily be decrypted.

An Enigma code book would have one page per month. The page would include all the settings for each day of the month with the first day of the month at the bottom of the page so that once used, a setting could be torn off the page.

The settings would indicate which rotors to use and in which order to connect them. Initially the Enigma machine came with a box of five rotors to choose from. On an Enigma M3, three out of the five rotors were connected. The M4 Enigma used four rotors chosen from a box of up to eight rotors.

The settings would also include the wheel settings (how to connect the rotors) and their initial position. Finally the settings would indicate which letters to connect by plugging cables on the plugboard.

The aim of this challenge is to write a piece of Python code to generate a full Code Book of Enigma Daily Settings for the Enigma M3 series. (which consists of 3 rotors to choose from a collection of 5 unique rotors).

The code book should include 30 or 31 set of randomly generated daily settings (one for each day of the month) displayed in a table as follows:

enigma-code-book

Each daily settings should include:

  • The date (number between 1 and 30/31, listed in reverse order)
  • The choice of three rotors (e.g. IV I III)
  • The ring settings (e.g. ABC)
  • The initial rotor positions (e.g. DEF)
  • The plugboard permutations (e.g. AF CK EW MT SV XY)

Python Code / Solution

unlock-access

Solution...

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

Enigma – Mission X Challenge

top-secret-stamp

Dear code breaker,

I am contacting you from Bletchley Park as we are intercepting an increased volume of encrypted radio signals. We are working day and night to break the enigma codes that the German Navy are updating every day. The German U-Boats are operating in the Atlantic Ocean and are causing major casualties by sinking not only military ships from the Royal Navy but also merchant ships bringing supplies from the United States and Canada to the United Kingdom.

Luckily, we have gained access to a code book which, we believe, gives us all the settings for the Enigma M3 machine, for each day of this month.

Could you help us decode the following secret messages by applying the required settings to the Enigma M3 machine. I am not sure about your understanding of the German language, so I have enclosed a German translation book including key German expressions.

We believe that the Germans are preparing a major attack on the south coast of England. We hope that the messages will help us find more information on the exact location and day of the attack.

Let us know if you can find out more useful information from these messages.

Yours sincerely,

Your friend, Alan T.

Video Tutorial

Mission Files


Click on the following folder to access Mission X top secret files.
misison-folder

unlock-access

Solution...

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

Enigma Machine Emulator

The enigma machine was used in World War II to encrypt secret messages.

The enigma machine was used in World War II to encrypt secret messages.

The Enigma machines are a series of electro-mechanical rotor cipher machines. The first machines were invented at the end of World War I by German engineer Arthur Scherbius and were mainly used to protect commercial, diplomatic and military communication. Enigma machines became more and more complex and were heavily used by the German army during World War II to encrypt radio signals.

One of the key objectives for the Allies during WWII was to find a way to break the code to be able to decrypt German communications. A team of Polish cryptanalysts was the first to break Enigma codes as early as 1932, however the German used more advanced Enigma machines making it virtually impossible to break the Enigma code using traditional methods. In 1939 with the prospect of war, the Poles decided to share their findings with the British. Dilly Knox, one of the former British World War I Codebreakers, set up an Enigma Research Section at Bletchley Park, England. He worked alongside Tony Kendrick, Peter Twinn, Alan Turing and Gordon Welchman. Together they developed a complex machine called the Bomb used to workout Enigma settings from intercepted German communications. The first wartime Enigma messages were broken in January 1940. Being able to decrypt German messages gave the Allies valuable information which has had a major impact on the outcomes of WWII.

To gain a better understanding of the encryption techniques used by the enigma machine we have decided to recreate a virtual Enigma machine/emulator.

You will be able to use this machine to both encrypt or decrypt enigma messages (Enigma encryption is symmetric, which means that the same settings can be used to both encrypt or decrypt a message).

Our Enigma machine emulator is replicating the encryption process of the Enigma M3 series that was used by the German Navy (Kriegsmarine). It is fitted with a UKW-B reflector. Later on through the war, it was replaced by the M4 series which included a 4throtor.

Before pressing any keys on the keyboard section of the machine you will need to apply the required settings. To do so you will need to click on the rotors to adjust the wheels initial settings and then make the required connections by clicking on the different plugs (bottom section of the machine) to connect letters from the plugboard.

Enigma Machine Emulator

Tagged with: , ,

Stopping Distance Calculator

road-sign-deerIn this challenge, we will write a Python program to estimate the total stopping distance of a vehicle based on its speed. The stopping distance consists of two components. The first component is the reaction distance covered by the vehicle due to the reaction time/delay of the driver between the moment an obstacle is spotted on the road and the moment the brakes are applied. The second component is the braking distance which is the distance a vehicle will travel from the point when its brakes are fully applied to when it comes to a complete stop. The braking distance is primarily affected by the original speed of the vehicle and the coefficient of friction between the tires and the road surface.

Based on the law of physics, we can write the stopping distance formula as follows:
stopping-distance-formula

For this challenge we will use a response time (tr) of 1.5 seconds, the average response time of a driver. In reality this response time varies depending on the age of the driver, their experience and their condition: e.g. A tired driver will have a slower response time than an alert driver.

The common baseline value for the friction coefficient µ (pronounced mu) is 0.7. In reality this coefficient varies depending on the condition of the road (e.g. dry/wet/icy) as well as the types, condition and pressure of the tyres.

Our aim is to write a Python program based on the INPUT / PROCESS / OUTPUT model that will:

  1. INPUT: Ask the user to enter the speed of a car in mph (Miles per hour)
  2. PROCESS: Convert this speed in mps (meters per second)
  3. PROCESS: Apply the stopping distance formula (using µ = 0.7 and tr = 1.5s)
  4. OUTPUT: Display the estimated stopping distance of the car in meters.

Speed Conversion Formula


To convert the speed of the vehicle from mph (miles per hour) to mps (meter per second) you will need to apply the following formula:
speed-conversion-formula

Complete the Python Code


Testing


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

Test # Input Values Expected Output Actual Output
#1 50 mph 70 meters
#2 70 mph 118 meters
#3 30 mph 33 meters

Extension Task:


The value of the friction coefficient µ depends on the condition of the road.

Adapt your script to ask the user if the road is dry, wet, or icy.
Based on the user input, you will use the following friction coefficients:

Road Condition Friction Coefficient
Dry µ = 0.7
Wet µ = 0.5
Icy µ = 0.3

Testing


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

Test # Input Values Expected Output Actual Output
#1 30 mph, Dry Road 33 meters
#2 30 mph, Wet Road 38 meters
#3 30 mph, Icy Road 51 meters
#4 70 mph, Dry Road 118 meters
#5 70 mph, Wet Road 146 meters
#6 70 mph. Icy Road 213 meters
unlock-access

Solution...

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

Binary Permutations Challenge

binary-permutations

Did You Know?

Everything that is stored on a computer is stored as binary code. Binary code is made of bits (0 or 1). We often use Bytes to store data. A Byte is made of eight bits and can be used to store any whole number between 0 to 255. This is because with 8 bits you can generate 256 different permutations.

Check it yourself, click on the binary digits to create your own binary number:


1286432168421
11111111

128 + 64 + 32 + 16 + 8 + 4 + 2 + 1 = 255


Python Challenge


The aim of this challenge is to write a procedure called listAllBinaryPermutations() that will take one parameter called numberOfBits and outputs all possible binary permutations depending on the number of bits.

For instance listAllBinaryPermutations(4) would output the following 16 binary permutations:

  • 0000
  • 0001
  • 0010
  • 0011
  • 0100
  • 0101
  • 0110
  • 0111
  • 1000
  • 1001
  • 1010
  • 1011
  • 1100
  • 1101
  • 1110
  • 1111

unlock-access

Solution...

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