More results...

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

Elastic Collision in a Pool Game

A range of video games use elastic collision formulas to predict the change of velocity of two objects when a collision occurs.

Elastic collision occurs when two objects are colliding and the total kinetic energy of the two objects remains the same. In reality, most collisions between two objects would result in some loss of energy (inelastic collision). However in some contexts, such as when two rigid billiard balls are colliding, this loss of energy is negligeable. In a video game of pool we would therefore implement an algorithm based on an elastic collision.

Let’s investigate how we can implement an elastic collision in a computer animation or a video game.

Velocity Vector

In a frame based game, most moving sprites would have a set of coordinates (x,y) to inidicate their position on the screen as well as a vaolcity vector (vx,vy) to indicate used to increment the (x,y) coordinates between two frames of the game and hence implement the movement of the sprite.

1 Dimensional Elastic Collision

Let’s consider two perfectly elastic balls of masses m1 and m2 moving along the same straight line with velocities u1 and u2.

Our aim is to calculate the velocity v1 and v2 of these two balls after the collision.

Conisidering that both momentum and kinetic energy are conserved quantities in an elastic collision, we can deduct the following two formulas:

Conservation of momentum

Conservation of kinetic energy

We can use both these formulas to calculate the velocity vectors v1 and v2 of the two colliding objects after the collision:

Note that these equations can be simplified when both colliding objects have the same mass: m1=m2. In this case we can use the following simplified formulas:

2 Dimensional Elastic Collision

In a 2-dimension environment, the velocity vectors may not be aligned on the same straight line.

We can however decompose the velocity vectors to identify the component of the velocity that is going along the straight line joining the centre of both moving balls (Purple vectors on the above diagram) and the component that is perpendicular to this straight line (Grey vectors on the above diagram). The first component will be affected by the elastic collision using the 1-Dimensional model/formulas whereas the second component will not be affected by the collision.

In order to calculate the 2 components of our velocity vectors (purple and grey vectors) we will first need to perform a rotation by θ, the angle that can be calculated using the (x,y) cartesian coordinates of the centre of both moving objects as follows:

We will then rotate our velocity vectors by θ as shown on the diagram below. Note however, that we would apply the same rotation for both velocity vectors (red and blue balls).

The formulas to perform a 2D rotation are as follows: (You can find out more about these formulas on this page)
where (Vx,Vy) represents the velocity vector (vx,vy) after the rotation.

We can now apply the 1-dimensional elastic collision formulas to the Vx (purple component) of the velocity for each moving object, whereas the Vy components will not be affected by the elastic collision.

And then we will need to rotate our new velocity vectors by to cancel out the previous rotation.

2-Dimensional Elastic Collision Demonstration

To see how the above formulas can be implemented, we have created a demo using JavaScript. You can investigate this code further to identify how the steps described above have been implemented.

In our demo, all the moving objects have a different mass, pro-rata of their size (radius).

Note that this code could be simplified further using objects of the same mass as this would be the case in a game of pool!

Finally, you will notice that this code also applies some formulas to the velocity vectors of each ball to let the balls bounce against the edge of the canvas. These formulas are explained on this page.

Your Task

Your task consists of tweaking the above code (Click on “Edit On Codepen” button in the top right corner of the above codepen frame) in order to create a pool table with:

  • 7 yellow balls
  • 7 red balls
  • 1 black ball
  • 1 white ball

Note that, in a game of pool, all balls have the same mass and size. You can hence simplify the code to use the simplified 1-dimensional elastic collision formulas.

About this task: The aim of this challenge is not to create a full game of pool but just to tweak the above code to make sure that the canvas contains 16 balls of the right colour and of the same weight/size. In a full game of pool, other features would need to be considered such as, implementing the correct size of the pool table, adding pockets and detecting when balls fall into these pockets, adding friction to slow down the rolling balls and adding a mechanism for the player to aim/shoot. All of these features are not part of this task.

unlock-access

Solution...

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

The Monty Hall Problem

The Monty Hall problem is a counter-intuitive brain teaser based on probabilities.

This puzzle is named after Monty Hall, the TV presenter of “Let’s Make a Deal”, an American TV show (known as “Deal or No Deal” in the UK) where contenders swap boxes of different values in order to win a prize.

In a similar approach, the aim of the Monty Hall puzzle is to try to win a car by knocking on the right door. The player is presented with three closed doors. Behind one of these doors is a luxurious car. Behind each of the other two doors is a goat!

Here is how the game proceeds:

  • You first pick a door. It could be that you picked the door with the car but you do not know that yet!
  • The game show host examines the other two doors and opens one with a goat. (Note that when both doors are hiding a goat, the presenter picks one of these doors randomly.)
  • You then need to make a decision: You can either stick with your initial guess and open the door to see if you win the car. Alternatively, you can decide to switch your door with the other closed door!

You can give it a go using our interactive game below:

What are the Odds?

When being asked whether to stick to your first guess or change your mind, there are only two closed doors left: One door hiding a goat and one door hiding the car. You could therefore assume that the odds of winning the car are 50-50! This is however a misconception! And if you play the game several times in a row, you will soon realise that you are twice more likely to win the car if you decide to switch your initial guess with the other door!

Not convinced? Try it… And if you want to fully understand the probabilities of this counter-intuitive puzzle you can check this page.

Frequency Analysis

In order to confirm these odds, we would like you to create a Python program that will simulate 100 games in a row, randomly positioning the two goats and the car behind the three doors every time. The program should then automatically and randomly select a door, reveal one door/goat and decide whether to switch doors or not. It should then determine whether the selected door leads to the car or the goat and keep a tally count of wins and losses.

At the end of the 100 attempts, the program should output the statistics as follows:

Python Code

We have only just started the code and thought about the key steps needed to complete this challenge. Your task is to complete the code below to produce a similar output (See statistics displayed above).

unlock-access

Solution...

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

Denary to Binary Conversion Algorithm

In this challenge, we are going to write al algorithm to convert a decimal (aka Denary) number between 0 and 255 into binary using 1 Byte (=8 bits).

Before attempting this challenge you may practise your denary to binary conversion:

Python Challenge


We are now going to use some Python code to implement al algorithm to convert a denary number into binary. To do so, you will need to complete the following 4 tasks.

Python Challenge - Task #1Task #2: Input ValidationTask #3: Writing a FunctionTask #4: Binary to Denary

Python Challenge: Task #1

We have started an algorithm which we would like you to complete to perform a full denary to binary conversion.

Your first challenge is to investigate the code below to see what it does and how it works. You will then need to complete this code to make sure that it outputs a fully Byte of data for any given number between 0 and 255.

The following trace table may help you investigate this code step by step:

 Line NumberdenarybinaryOUTPUT
3

Python Challenge: Task #2

Add some code to your code from task 1 to validate the input so that your code only accepts a number between 0 and 255. You can find out more about different validation techniques below and select the validation technique that is most relevant to this task:

Validation Techniques:


Input Validation: Presence Check

name = input("Enter your name:").strip() 

if name=="":
    print("Empty name!")
else:
    print("Thank you!")

Input Validation: Type Check – Integer?

number = input("Type a number:")

if number.isdigit():
    print("This is a number")
else:
    print("This is not a whole number")

Input Validation: Range Check

number = int(input("Type a number between 1 and 5:"))

if number>=1 and number<=5:
    print("Valid number")
else:
    print("Invalid number")

Input Validation: Lookup Check

drive = input("Can you drive?").lower()

if drive in ["yes","no"]:
    print("Valid answer")
else:
    print("Invalid answer")

Input Validation: Character Check

email = input("Type your e-mail address:")

if "@" in email:
    print("Valid e-mail address")
else:
    print("Invalid e-mail address")
postcode = input("Type your postocode:").upper()

if postcode[0] in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" and postcode[1] in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" and postcode[2] in "123456789":
    print("Valid postcode")
else:
    print("Invalid postcode")

Input Validation: Length Check

password = input("Type a password:")

if len(password)>=8:
    print("Valid password")
else:
    print("Invalid password")

Try Again! Using a While Loop:

name = input("Enter your name:")

while name=="":
    print("You must enter your name! Please try again!")
    name = input("Enter your name:")

print("Welcome " +  name)

Task #3: Writing a Function

Turn your code into a function called convertToBinary(). Your function will take a denary number as a parameter and return a binary string. You will then need to add some code to test your function.​

Task #4: Writing a Function

Create a new function called convertToDenary(). This new function will take a binary string as a parameter and return the matching denary value.


unlock-access

Solution...

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

Software Crosswords

A computer system consists of both hardware (the physical components of the computer) and software: the programs that run on this hardware.

There are three main categories of software:

  • Operating Systems: software that controls the computer hardware: The operating system can load programs into memory (e.g. RAM), instruct the CPU on which programs to run, interact with input, output and storage devices.
  • Utilities and Drivers: A range of specific software that can be used to help with the maintenance and security of the computer system
  • Application Software: A range of software used by the end-user to perform specific tasks.

Complete the following crossword to demonstrate your understanding of the three main types of computer software.
Computer Software CrosswordOpen Crossword Puzzle in a New Window
Computer Software CrosswordOpen Crossword Puzzle in a New Window

unlock-access

Solution...

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

Short Path Algorithm Practice

Before completing this task, you will need to familiarise yourself with the following 2 algorithms used to find the shortest path between two nodes of a weighted graph:

Dijkstra’s Short Path Algorithm

For each of the weighted graph below, complete the table below to show the steps needed to find the shortest path between node A and node Z using the Dijkstra’s Short Path Algorithm. Note that on these graphs, the weight of each edge represents the distance in miles between two nodes.

Graph #1Graph #2Graph #3Graph #4

Shortest Path?

Length?


Shortest Path?

Length?

Shortest Path?

Length?

Shortest Path?

Length?

Node Status Shortest Distance from A Previous Node
A
B
C
D
E
F
G
H
Z

A* Algorithm

On the graphs below, the heuristic values specified for each node of the graph represent the distance in a straight line (as the crow flies) between the node and the destination node (Z).

Graph #1Graph #2Graph #3Graph #4
Shortest Path?

Length?

Shortest Path?

Length?

Shortest Path?

Length?

Shortest Path?

Length?

Node Status Shortest Distance from A Heurisitic Distance to Z Total Distance Previous Node
A
B
C
D
E
F
G
H
Z

TCP/IP Stack: Network Layers and Protocols

The TCP/IP Stack is a model that governs how data is transmitted from one computer to another via an IP network such as the Internet.

Internet communication includes using a web browser to access a webpage from a websever, sending or downloading an email from a mail server, uploading files to a server using an FTP client, etc.

For all these Internet communications, the TCP/IP Stack is used to show the different protocols used to format data to enable its transmission between computers.

A protocol is a set of rules required for two computers to communicate over a network.

A layer is a group of protocols focusing one one stage of the data transmission.

The TCP/IP Stack consists of 4 Layers:

  • Application Layer
  • Transport Layer
  • Internet/Network Layer
  • Physical/Data/Link Layer

Application Layer

The application layer is used to format the data so that it can be processed by the application(e.g. web browser, email client) being used for the communication. For instance:

  • HTTP and HTTPS protocols are used to access a webpage via a web-browser
  • The SMTP protocol is used to send e-mails between mail servers
  • The IMAP and POP3 protocols are used to retrieve emails from a mail server
  • The FTP protocol is used to transfer files between two computers

Some protocols such as HTTPS are also used to make sure the data is encrypted before being transmitted (passed down to the next layer).

Transport Layer

The transport layer is used to implement packet switching.

The purpose of this layer is to split the data being transmitted in to data packets. Each packet will have its own header with information about the packet being sent, its position in the transfer, the protocol and port used.

This layer is also responsible for checking packets when they are received. This is called Transfer Control (TCP Protocol). If a packet is missing or has been corrupted, the receiving computer will automatically ask the sending computer to resend the missing/corrupted packet.

Internet Layer

This layer is also known as the Network layer. Each packet is assigned the IP address of the source (sending computer) and of its destination (receiving computer) so that the packet can be routed through the network/Internet.

On the Internet, data packets are being redirected by routers till they reach their destination.

Link Layer

This layer is also known as Physical Layer. The aim of this layer is to convert the data packets into an electric current going through a copper cable (Ethernet, Coax, Phone line, etc.), an electromagnetic radio wave (wireless transmission) or a light beam (optic fibre).

The protocols used on this layer depend on the type of connection/link used to transfer the data: e.g.

  • WiFi, 3G/4G/5G, Bluetooth are examples of wireless protocols
  • Ethernet and ADSL are examples of protocols used for wired communication

TCP/IP Stack Drag and Drop

Complete the following drag and drop activity to check your understanding of the TCP/IP Stack!

TCP/IP StackOpen in New Window

Tagged with:

Snow Poem Algorithm

The following algorithm is inspired by a poem by Brian Bilston called “snow poem”. On this poem, each word represents a snowflake gently and randomly falling from the sky. On the last verse of this poem, you can see how the snow is starting to settle on the ground!

The aim of this challenge is to investigate a range of string manipulation techniques using Python including:
Splitting a string into a list, using a special character (e.g. space or “/” character)
String concatenation techniques using the * and + operators
Retrieving the length of a string using the len() function.

Here is the Python code for our Snow Poem algorithm:

Christmas Tree

Using a similar approach, we created an algorithm to reproduce the poem “Needles” by the same author.

Here is the Python code for the poem “Needles”:

There is no coding task attached to this algorithm. If you like this code, you may want to investigate the following challenges:

Programming Terminology – Drag and Drop


To be a good carpenter, you need to be able to identify and select the right tools to complete your project. For instance, the main wood working tools used by carpenters are:

Chisel, Hand Saw, Hammer, Screwdriver, Hand Plane, Caliper, Level, Clamp, Circular Saw, Jigsaw, Orbital Sander, Palm Sander, Tape Measurer, Miter Gauge, Router, Band Saw, Power Drill, Drill Press, Grinder, etc.

It’s the same with programming. To be a good programmer, your need to be able to identify all the tools that are available to build a computer program. If you can name these tools, you will then be able to select the right tool when you need them!

When using procedural programming with a high level programming language like Python, the main tools of the programmer are:

    Sequencing,
    Iteration,
    Selection,
    Variables,
    Constants,
    Data Types (Integer, Float, String, Boolean) & casting values,
    Computing Operators (assignment operator, arithmetic operators, comparison operators, Boolean operators)
    Data Structures (e.g. lists and arrays)
    String manipulation techniques (incl. String concatenation)
    Subroutines (e.g. Procedures and Functions)
    Libraries (e.g. random library, time library, etc.)
    Etc.

Task 1: Drag and Drop

Complete the fill in the gaps activity below to label all the programming terminology used in this Python program:


Programming TerminologyOpen in New Window

Task 2: Python Coding

Code this program online using trinket.io.

Task 3: Returning the change!

Update the above code, so that, when the user overpays, the program returns the change. For instance, if your customer overpays by £14, the output of your code would be:

You overpaid by £14. Here is your change:
£10 banknote
£2 coin
£2 coin

unlock-access

Solution...

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

Laser Maze Game in Python

In this Python programming challenge, we are going to recreate the game “Laser Maze”.

The aim is to redirect a laser beam across a given stage in order to reach the exit gate of the stage.

The laser can only travel in four directions:

  • Up
  • Right
  • Down
  • Left

The stage/maze is a 2D grid consisting of 12×12 tiles (including the outside walls of the room):

The following rules will apply when generating the stage:

  • The source of the laser beam will be randomly positioned on the left wall of the room and the laser will be aiming to the right.
  • The exit gate of stage will be randomly positioned on the right wall of the room.
  • 3 Bombs will be randomly placed on three tiles of the stage.

To solve the level, the user will have to place some reflectors on the stage using the following rules:

  • Reflectors can only be placed on empty tiles. They cannot be placed on existing walls, bombs, laser source or exit gate.
  • There will be two types of reflectors: // and \\ which will redirect the laser beam by 90 degrees either clockwise (\\) or anti-clockwise (//)

Structure Diagram (Decomposition)

Here is the structure diagram for our Laser Maze Game:

From this structure diagram, we can generate the following checklist:
Initialise 12×12 empty maze
Place Laser Source
Place Exit Gate
Place Bombs
Display maze
Player inputs row and column numbers and type of reflector
Place reflectors on the maze
Repeat process (for any additional reflectors)
Shooting: Start Laser Beam at Source
Trace laser in all four directions (right, left, up, down)
Detect collision with bombs
Detect collision with walls
Detect collision with laser source
Detect collision with exit gate
Detect collision with reflectors
Redirect laser beam (when laser collides with a reflector)
Output “Level Complete” message or “Game Over Message”

Python Code

We have started the code for our laser game but our code is incomplete. Your task is to complete this game to allow the user to solve the level by placing reflectors on the 2D grid to redirect the laser beam either clockwise or anti-clockwise.

Extension Task

Your extension task is to implement a scoring system.
At the start of the game, the user has 100 points.
Each reflection wall used costs 20 points.
Once a level is complete, the user should earn 50 points.
Once a level is complete, the user should automatically be presented with a new level.
The game stops when the user hits a wall or a bomb.

unlock-access

Solution...

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

Battle of the Knights

For this Python programming challenge, you are going to create a Battle game where two knights will fight each other till death!

Your game will use a text-based user interface (using ASCII art to represent the knights) and will produce a frame based animation of the battle scene:

Here is a structure diagram of the whole game:

Using this structure diagram we can generate the following to do list for you to complete this game step by step:
Generate random knight names for both players
Initialise both health scores to 100
Randomly pick an action for each knight (attack, defend or rest)
Display the battle scene (as stickmen based on the action of each knight)
Update health scores
Display knights’ names and health scores
Repeat process as long as both health scores are positive
Stop the battle as soon as at least one health score is lower or equal to zero
Identify if there is a winner or a draw (when both players have a health score lower or equal to 0)
Output the last scene of the battle and the name of the knight who won the battle

Python Code

To get started with this project, we will reuse the code from the “Knight Name Generator” challenge.

Note that to create a frame based animation, you can use both the time library (to define the delay between two frames) and the os library (to clear the screen between each frame). For instance, see how this code displays a random number every 1 second.

import random, time, os
while True:
   print(random.randint(0,10))
   
   time.sleep(1)
   os.system("cls")

Your task is to complete the code below to implement all aspects of this game using the above checklist:

Extension Task

Re-organise your code to make use of OOP concepts.

You should do so by creating a Knight class to store the name, health and state of your knight as properties of the Knight class and use a few methods to let your knight randomly pick an action (new state) or to draw your sprite on screen.

unlock-access

Solution...

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