More results...

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

Enigma Encoder

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.

The Enigma machine was used 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).

In this challenge we will create an enigma encoder program to encrypt and decrypt messages using specific Enigma settings. But before doing so we need to gain a better understanding of how the Enigma machine actually works. To do so you can use our online Enigma emulator to start encoding or decoding secret messages.

Inside the Enigma


The enigma machine is a fairly complex encryption machine which consists of four main sections:

The Keyboard

The keyboard is used to retrieve the user input. The Enigma machine is a symmetric encryption machine. Which means that it can be used to both encrypt or decrypt a message using the same settings. The keyboard is hence used to either enter the plaintext that needs to be encrypted or the ciphertext that needs to be decrypted.

They keyboard consists of 26 keys for each letter of the alphabet. This means that encrypted messages will be joined up without any spaces or punctuation signs.

Notice how the keyboard starts with the letters QWERTZ instead of QWERTY. This is due to the fact that in the German language, the letter Z is more often used than the letter.

The plugboard

Once a key is pressed on the keyboard, it goes through the plugboard which provides the first stage of the encryption process. It is based on the principles of a substitution cipher, a form of transposition encryption.

To setup the keyboards, short wires are used to connect pairs of letters that will be permuted. For instance on the picture below the letter W will be replaced with a D and the letter D with a W as a (red) wire is used to connect these two letters/plugs. Similarly, letter V will become letter Z and Z will become V.

In a code book the plugboard settings would be recorded as follows: DW VZ

The Rotors

After the plugboard, the letter goes through the three rotors in order (from right to left), each of them changing it differently using a combination of transposition cipher and Caesar cipher! On the engima M3 there are three rotor slots and five rotors to choose from. Each rotor is identified using a Roman numeral from I to V. This provides a few settings of the Enigma machine: which rotors to use, and in which order to position them. In a code book this seeting would be recorded as IV II III (Left, Middle and Right rotors).

Each of the five rotors encrypt the letter differently using a transposition/permutation cipher and can be connected in the Enigma machine with a different Ring setting. Another setting is the initial position of the rotors: Which letters are you going to set each rotor to begin with (e.g. A/B/C../Z sometimes recorded in a codebook using numbers (01 for A, 02 for B up to 26 for Z). This creates a Caesar Shift (Caesar Cipher). On an Enigma machine, you can change the position of the rotors by turning the three wheels.

Different versions of Enigma (e.g. M4) included four rotors which made the encryption process and the number of possible settings even bigger.

On our Enigma M3 emulator, you can click on the rotors to access the Enigma rotors settings:


What makes the Enigma code particularly difficult to crack is that every time a key is pressed, the rotor on the right turns by 1 letter. Which means that the encryption settings constantly changes for each letter of a message. It also means that a single plaintext letter would be encrypted differently depending on its position in the message.

The rotors are also connected to each other so that when the rotor positioned on the right reach a specific letter, it triggers the rotor in the middle to rotate by one letter. Similarly when the rotor in the middle reaches a specific letter it triggers the rotor on the left to turn by one letter.

You will find more information on how the rotors operate on the following wikipedia page.

The Reflector

The reflector is another type of rotor inside the machine. Once the letter has gone through the three rotors from right to left, the reflector will reflect the electrical current back through the rotors, sending the encrypted letter through the rotors from left to right for another 3 stages of encryption and then through the plugboard again for a final substitution cipher. When going through the reflector, a permutation cipher is also applied to the letter.

Different versions of reflectors were used on different versions of Enigma machines. Each reflector would apply a different permutation cipher. Enigma M3 machines were equipped with either a UKW-B or UKW-C reflector. You can apply these two reflectors in the rotor settings window of our emulator (see screenshot above).

The lampboard


The lampboard is the final stage of the encryption process and is used to show the output (encrypted letter). It consists of 26 light bulbs, one for each letter of the alphabet.

The diagram below shows the journey of a letter through the encryption process of an Enigma M3.

Python Enigma Encoder


The Python program below allows you to encode and decode messages using the Enigma encryption.
You can apply your own Enigma settings by editing lines 3 to 9 of this 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: , ,

Pong Tutorial using Pygame – Adding a Scoring System

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

The final stage of our tutorial focuses on adding a scoring system to our Pong game. Player A will score a point if the ball bounces against the right hand side edge of the screen while player B will score a point if the ball bounces against the left hand side edge of the screen. Both scores will be displayed at the top of the screen.

The final code for the main.py is provided below. We made three changes to the code as follows:

  • On lines 43 to 45 we are initialising both player scores to 0.
  • On lines 72 to 77 the code detects when one the player scores point.
  • On lines 96 to 101 how the scores are displayed on screen.
main.pypaddle.pyball.py
# Import the pygame library and initialise the game engine
import pygame
from paddle import Paddle
from ball import Ball
 
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
 
ball = Ball(WHITE,10,10)
ball.rect.x = 345
ball.rect.y = 195
 
#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 2 paddles and the ball to the list of objects
all_sprites_list.add(paddleA)
all_sprites_list.add(paddleB)
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()
 
#Initialise player scores
scoreA = 0
scoreB = 0
 
# -------- 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
 
    #Moving the paddles when the use uses the arrow keys (player A) or "W/S" keys (player B) 
    keys = pygame.key.get_pressed()
    if keys[pygame.K_w]:
        paddleA.moveUp(5)
    if keys[pygame.K_s]:
        paddleA.moveDown(5)
    if keys[pygame.K_UP]:
        paddleB.moveUp(5)
    if keys[pygame.K_DOWN]:
        paddleB.moveDown(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>=690:
        scoreA+=1
        ball.velocity[0] = -ball.velocity[0]
    if ball.rect.x<=0:
        scoreB+=1
        ball.velocity[0] = -ball.velocity[0]
    if ball.rect.y>490:
        ball.velocity[1] = -ball.velocity[1]
    if ball.rect.y<0:
        ball.velocity[1] = -ball.velocity[1]     
 
    #Detect collisions between the ball and the paddles
    if pygame.sprite.collide_mask(ball, paddleA) or pygame.sprite.collide_mask(ball, paddleB):
      ball.bounce()
    
    # --- 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) 
 
    #Display scores:
    font = pygame.font.Font(None, 74)
    text = font.render(str(scoreA), 1, WHITE)
    screen.blit(text, (250,10))
    text = font.render(str(scoreB), 1, WHITE)
    screen.blit(text, (420,10))
 
    # --- 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()
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 moveUp(self, pixels):
        self.rect.y -= pixels
        #Check that you are not going too far (off the screen)
        if self.rect.y < 0:
          self.rect.y = 0
          
    def moveDown(self, pixels):
        self.rect.y += pixels
        #Check that you are not going too far (off the screen)
        if self.rect.y > 400:
          self.rect.y = 400

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)
Tagged with:

Pong Tutorial using Pygame – Adding a Bouncing Ball

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

Our aim is to add the bouncing ball to our Pong 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 4) We will then create an object called ball using the Ball class. (See lines 25 to 27) We will add this object to the all_sprites_list group of sprites. (See line 35)

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

# Import the pygame library and initialise the game engine
import pygame
from paddle import Paddle
from ball import Ball

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

ball = Ball(WHITE,10,10)
ball.rect.x = 345
ball.rect.y = 195

#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 and the ball to the list of objects
all_sprites_list.add(paddleA)
all_sprites_list.add(paddleB)
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
        elif event.type==pygame.KEYDOWN:
                if event.key==pygame.K_x: #Pressing the x Key will quit the game
                     carryOn=False
 
    #Moving the paddles when the use uses the arrow keys (player A) or "W/S" keys (player B) 
    keys = pygame.key.get_pressed()
    if keys[pygame.K_w]:
        paddleA.moveUp(5)
    if keys[pygame.K_s]:
        paddleA.moveDown(5)
    if keys[pygame.K_UP]:
        paddleB.moveUp(5)
    if keys[pygame.K_DOWN]:
        paddleB.moveDown(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>=690:
        ball.velocity[0] = -ball.velocity[0]
    if ball.rect.x<=0:
        ball.velocity[0] = -ball.velocity[0]
    if ball.rect.y>490:
        ball.velocity[1] = -ball.velocity[1]
    if ball.rect.y<0:
        ball.velocity[1] = -ball.velocity[1] 

    # --- 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()

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 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, 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 77 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
from paddle import Paddle
from ball import Ball

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

ball = Ball(WHITE,10,10)
ball.rect.x = 345
ball.rect.y = 195

#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 and the ball to the list of sprites
all_sprites_list.add(paddleA)
all_sprites_list.add(paddleB)
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
        elif event.type==pygame.KEYDOWN:
                if event.key==pygame.K_x: #Pressing the x Key will quit the game
                     carryOn=False
 
    #Moving the paddles when the use uses the arrow keys (player A) or "W/S" keys (player B) 
    keys = pygame.key.get_pressed()
    if keys[pygame.K_w]:
        paddleA.moveUp(5)
    if keys[pygame.K_s]:
        paddleA.moveDown(5)
    if keys[pygame.K_UP]:
        paddleB.moveUp(5)
    if keys[pygame.K_DOWN]:
        paddleB.moveDown(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>=690:
        ball.velocity[0] = -ball.velocity[0]
    if ball.rect.x<=0:
        ball.velocity[0] = -ball.velocity[0]
    if ball.rect.y>490:
        ball.velocity[1] = -ball.velocity[1]
    if ball.rect.y<0:
        ball.velocity[1] = -ball.velocity[1] 
 
    #Detect collisions between the ball and the paddles
    if pygame.sprite.collide_mask(ball, paddleA) or pygame.sprite.collide_mask(ball, paddleB):
      ball.bounce()
 
    # --- 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()

Next Step?


The final touch consists of adding a scoring system:
Pong Tutorial using Pygame:Adding a Scoring System
Tagged with:

Pong Tutorial using Pygame – Controlling the Paddles

pong-gameThis 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 two-player game of Pong. In the first tutorial we looked at how to create the background for our game. In the second tutorial we added our first sprites called paddleA and paddleB which are instances of the Paddle class.

In this third tutorial we will add methods to our Paddle class to move the paddles up and down when player A uses the W (up) and S (down) keys and player B uses the up and down arrow keys.

We will then add event handlers to the main program loop to respond to keystroke events. When the players use the relevant keys on the keyboard we will call our methods to move their paddle on the screen.

Step 1: Adding Methods to the Paddle class.


Open the file paddle.py and add the lines 23 to 33 as follows:

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 moveUp(self, pixels):
        self.rect.y -= pixels
		#Check that you are not going too far (off the screen)
        if self.rect.y < 0:
          self.rect.y = 0
          
    def moveDown(self, pixels):
        self.rect.y += pixels
	#Check that you are not going too far (off the screen)
        if self.rect.y > 400:
          self.rect.y = 400

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

def moveUp(self, pixels):
    self.rect.y -= pixels
    #Check that you are not going too far (off the screen)
    if self.rect.y < 0:
       self.rect.y = 0

The moveUp() 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 paddle.

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 four event handlers, to move the paddle up or down when the players press the W or S keys (Paddle A) or the up and down arrow keys (paddle B). Each event handler will call the relevant method from the Paddle class. Check the code below with the new event handlers from line 47 to 56.

# 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
 
    #Moving the paddles when the user uses the arrow keys (player A) or "W/S" keys (player B) 
    keys = pygame.key.get_pressed()
    if keys[pygame.K_w]:
        paddleA.moveUp(5)
    if keys[pygame.K_s]:
        paddleA.moveDown(5)
    if keys[pygame.K_UP]:
        paddleB.moveUp(5)
    if keys[pygame.K_DOWN]:
        paddleB.moveDown(5)    
 
    # --- 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()

All done… Save your files and try your code. You should now be able to control each paddle using the W, S, Up arrow and Down arrow keys!

Next Step?


It’s now time to add a bouncing ball to our game:
Pong Tutorial using Pygame:Adding a Bouncing Ball
Tagged with:

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