More results...

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

Breakout Tutorial using Pygame – Getting Started

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

Breakout is one of the earliest arcade video games, first released in 1976 by Atari. It was derived from the game Pong (released by Atari in 1972). This one-player game features simple 2D graphics. It consists of one paddle (in more recent version the paddle was replaced by a spaceship) used to return a bouncing ball back and forth across the screen. The aim of the game is to break the bricks of a brick wall by getting the ball to hit/bounce on the bricks. The score correspond to the number of bricks being hit.

In this tutorial we are going to recreate a game of Breakout 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. We will also initialise two global variables, score and lives that we will use later on in the game.

# Define some colors
WHITE = (255,255,255)
DARKBLUE = (36,90,190)
LIGHTBLUE = (0,176,240)
RED = (255,0,0)
ORANGE = (255,100,0)
YELLOW = (255,255,0)

score = 0
lives = 3

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 = (800, 600)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Breakout Game")

Step 4: The main program loop


The main program loop is the key wrapper for your game.

The main program loop will contain 3 main sections:

  • Capturing Events: Used to constantly “listen” to user inputs and react to these. It could be when the user uses the keyboard or the mouse.
  • Implementing the Game Logic. What happens when the game is running? Are cars moving forward, aliens falling from the sky, ghosts chasing you, etc.
  • Refreshing the screen by redrawing the stage and the sprites.

The main program loop will also use a frame rate to decide how often should the program complete the loop (& refresh the screen) per second. To implement this we will use the clock object from the pygame library.

The main program loop will use a timer to decide how many times it will be executed per second.

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

# Define some colors
WHITE = (255,255,255)
DARKBLUE = (36,90,190)
LIGHTBLUE = (0,176,240)
RED = (255,0,0)
ORANGE = (255,100,0)
YELLOW = (255,255,0)

score = 0
lives = 3

# Open a new window
size = (800, 600)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Breakout Game")

# 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 dark blue. 
    screen.fill(DARKBLUE)
    pygame.draw.line(screen, WHITE, [0, 38], [800, 38], 2)

    #Display the score and the number of lives at the top of the screen
    font = pygame.font.Font(None, 34)
    text = font.render("Score: " + str(score), 1, WHITE)
    screen.blit(text, (20,10))
    text = font.render("Lives: " + str(lives), 1, WHITE)
    screen.blit(text, (650,10))
 
    # --- 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:
Breakout Tutorial using Pygame:Adding the Paddle
Tagged with:

How many lines of output?

Take the Quiz! (open full screen)


RGB Colour Guessing Game


Play the RGB Colour GameOpen in new window

RGB Colour Code?


rgb-coloursEvery colour on the screen can be represented using an RGB code (Red, Green, Blue) code. This code consists of three numbers between 0 and 255, indicating how much red, green and blue are used to recreate the colour. For instance the RGB code for:

  • Red is (255,0,0)
  • Green is (0,255,0)
  • Blue is (0,0,255)
  • Yellow is (255,255,0)
  • Orange is (255,165,0)

Using the RGB colour code we can identify 224 colours: that’s 16,777,216 unique colours!

Graphic designer and software programmer sometimes prefer to use another notation based on hexadecimal RGB code where each of the three decimal values are converted into a two-digit hexadecimal code, resulting in a 6-digit hexadecimal code. For instance:

  • Red is #FF000
  • Green is #00FF00
  • Blue is #0000FF
  • Yellow is #FFFF00
  • Orange is #FFA500

Check the following RGB Color picker to see how RGB codes work:

CMYK to RGB Conversion Algorithm

CMYK-ColoursCMYK and RGB are two different colour models. The CMYK model is used in the publishing/printing industry as it is based on the four basic colours used for printing colour images on white paper. The four colours of the CMYK model are Cyan, Magenta, Yellow and Black. The CMYK colours are subtractive. This means the colours get darker as you blend them together. This is what happens when you print a colour image on paper as the more ink/pigments you add, the darker the colour gets.

The RGB model on the other hand is base don the opposite effect. Using the RGB model, the colours get brighter as you increase their Red, Green or Blue values. RGB colours are used to represent colours on a computer screen and are hence used for light emission, not pigments. The colours grow brighter as you blend them or increase their intensity.

CMYK values are given either as percentages or values between 0 and 1 (e.g. 50% = 0.5), whereas RGB values are given using an integer value between 0 and 255.

Colour Colour Name (R,G,B) (C,M,Y,K)
Cyan (0,255,255) (100%,0%,0%,0%)
Magenta (255,0,255) (0%,100%,0%,0%)
Yellow (255,255,0) (0%,0%,100%,0%)
Black (0,0,0) (0%,0%,0%,100%)
Red (255,0,0) (0%,100%,100%,0%)
Green (0,255,0) (100%,0%,100%,0%)
Blue (0,0,255) (100%,100%,0%,0%)
White (255,255,255) (0%,0%,0%,0%)
Turquoise (48,213,200) (77%,0%,6%,16%)
Metallic Gold (212,175,55) (0%,17.45%,74.06%,16.86%)

It his possible to convert RGB code into CMYK code and vice versa using the formulas provided below.
rgb-to-cmyk

CMYK to RGB Conversion Formulas


CMYK-to-RGB-Conversion-Formulas

RGB to CMYK Conversion Formulas


RGB-to-CMYK-Conversion-Formulas

Programming Task


Using a programming language of your choice, create a computer program that:

  1. Asks the user to choose between two options:
    • RGB to CMYK conversion
    • CMYK to RGB conversion
  2. Retrieve the RGB or CMYK values based on the option selected
  3. Apply the conversion formulas to calculate the matching CMYK or RGB values
  4. Output the resulting CMYK or RGB values

Python Code


We have started the code for you, though you still need to complete the main two functions: RGB_to_CMYK() and CMYK_to_RGB()

unlock-access

Solution...

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

Four Corners Javascript Challenge

four-corners-compassFour corners is a children’s game, often played in primary/elementary schools. The game can be played in a classroom. One player stand in the middle of the room with a blindfold. All the other participants choose one of the four corners of the room. For the purpose of this game we will call the four corners of the room North, East, South and West. The central player, “it”, designates one corner of the room. All the participants standing in this corner are out of the game. The remaining participants then move to a different corner of their choice and the game carries on until all participants have been caught.

The aim of this challenge is to recreate the game of four corners using HTML, CSS and JavaScript. The names of all participants will be stored in a JavaScript array called names as follows:

var names = ["Kacy", "Lucas", "Ali", "Cheung", "Leila"];

You can then access a value within an array using the appropriate index. i.e.

var player = names[0];

You can find out the number of items in an array using the length property:

var numberOfPlayers = names.length;

You can sort the values of an array using the sort() method:

names.sort();

You can use the push() method to append a new value in the array.

names.push("Jeff");

You can use the pop() method to remove the last value in the array.

var player = names.pop();

You can reset/empty an array:

names = [];

You can join two or more arrays together using the concat() method:
For instance you can join two arrays together:

var team1 = ["Kacy", "Lucas", "Ali", "Cheung", "Leila"];
var team2 = ["Jeff", "Fran", "Noah", "Eldece", "Marwan"];
var allPlayers = team1.concat(team2);

You can join three arrays together (an so on):

var team1 = ["Kacy", "Lucas", "Ali", "Cheung", "Leila"];
var team2 = ["Jeff", "Fran", "Noah", "Eldece", "Marwan"];
var team3 = ["Laura", "Harry", "Tim", "Jess", "Keziah"];
var allPlayers = team1.concat(team2, team3);

Four Corners Game


Using some of the techniques mentioned above, review the code for the four corners game. The JavaScript code is incomplete. Add some code in the clickCorner() to complete the game.

Press the “Edit on Codepen” button to access the code in full screen mode.

See the Pen
Four Corners
by 101 Computing (@101Computing)
on CodePen.

unlock-access

Solution...

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

Jack and the Beanstalk

jack-and-the-beanstalkIn the English fairy tale, Jack and the beanstalk, Jack is a young, poor boy living with his mother and a dairy cow on a farm cottage. The cow’s milk is their only source of income. When the cow stops giving milk, Jack’s mother tells him to take her to the market to be sold. On the way, Jack meets a curious man who offers magic beans in exchange for the cow, and surprisingly Jack makes the trade. When he arrives home without any money, his mother becomes angry, throws the beans out of the window, and sends Jack to bed without dinner.

During the night, the magic beans cause a gigantic beanstalk to grow outside Jack’s window. Let’s stop the fairy tale story here and focus on the magic beanstalk.

By studying its growth we found out the beanstalk was 100cm high just one hour after Jack’s mother sent the bean out of the window. After that the beanstalk grew at the following rate:

Every hour the beanstalk grew by 150% and gained an extra 30cm.

So we can plot the following growth table and chart:

Hours Height Calculation Beanstalk Height (in cm)
1 100 100
2 100 x 1.5 + 30 180
3 180 x 1.5 + 30 300
4 300 x 1.5 + 30 480
5 480 x 1.5 + 30 750
6 750 x 1.5 + 30 1155

beanstalk-height-chart

Using this information, can you work out the height of the magic beanstalk after 7 hours?

The next morning, the beanstalk was so high it could reach the sky! Can you work out the height of the beanstalk after 12 hours?

Using an algorithm…


To calculate the height of the beanstalk at any given time/hour we have decided to use an algorithm as follows:
jack-and-the-beanstalk-flowchart
This algorithm is an example of:
iteration-label

Python Code


Your task is to implement this algorithm using Python and calculate the height of the beanstalk after 12 hours or after a full day (24 hours).

unlock-access

Solution...

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

Visual Cryptography

Visual cryptography is a technique that consists of hiding information (text/symbols/graphics) within two semi-transparent pictures (called layers). Overlaying both pictures exactly on top of one another, will reveal the hidden information.

Using this technique, it is impossible to retrieve any of the hidden information if you only have one of the two layers.

The technique consists of splitting each pixel of the original picture (information to hide) into 4 smaller squares as follows:
visual-cryptography

Note that the white squares on layer 1 and 2 are in fact transparent.

By repeating this process for each pixel of the original image, we obtain two layers with what appears to be random noise. However, overlapping these layers will reveal the black pixels of the original image.
visual-cryptography-of-space-invader

You can drag the following layers to position them on top of one another and reveal the secret image:


Online Visual Cryptography


Use our online tool to create your own visual cryptography layers. To do so you will need to:

  1. Create a pixel art graphic on the first canvas. (Note that you can change the number of rows and columns for your canvas if needed)
  2. Press the encrypt button to generate both layers. The tool will also let you preview the result of overlaying both layers to reveal your pixel art.
  3. Press the “Download as PNG” buttons to download both layers (layer-1.png and layer-2.png)
  4. You can now insert both layers using a graphic editing software or an application software such as Powerpoint and try to reveal the secret pixel art by positioning both layers exactly on top of one another.

Tagged with: ,

Step Count Algorithm in LMC

steps-count-controlled-loopCount-controlled loops are used in many programs to increment a counter for each iteration of the loop. Per default the increment for the counter is +1.

FOR counter FROM 1 TO 10:
    OUTPUT (COUNTER)

However you can specify a different step when incrementing your counter in a count-controlled loop. For instance to count in 5:

FOR counter FROM 0 TO 100 STEP 5:
    OUTPUT (COUNTER)

You can also use different starting and ending values:

FOR counter FROM 50 TO 250 STEP 5:
    OUTPUT (COUNTER)

A negative step can also be used to decrement the counter:

FOR counter FROM 20 TO 0 STEP -2:
    OUTPUT (COUNTER)

This challenge consists of writing a program using LMC to implement a count-controlled loop using a step defined by the end user. Your program will:

  • INPUT: Retrieve the starting value for the step count algorithm from the end user.
  • INPUT: Retrieve the ending value for the for step count algorithm from the end user.
  • INPUT: Retrieve the step value from the end user.
  • Count and output all the values (from the starting value to the ending value, using the given step).

Note that this algorithm is an implementation of an arithmetic number sequence.

To complete this challenge you will need to use one of the following online LMC Simulators:

The list of LMC instructions is provided at the bottom of this page.

You will be able to test your algorithm using the following input values:

Test # Input Values Expected Output Pass/Fail
#1 Start Value: 10
End Value: 20
Step: 2
10,12,14,16,18,20
#2 Start Value: 82
End Value: 100
Step: 5
82,87,92,97
#3 Start Value: 10
End Value: 1
Step: -1
negative-step
10,9,8,7,6,5,4,3,2,1

LMC Instruction Set


Note that in the following table “xx” refers to a memory address (aka mailbox) in the RAM. The online LMC simulator has 100 different mailboxes in the RAM ranging from 00 to 99.

Mnemonic Name Description Op Code
INP INPUT Retrieve user input and stores it in the accumulator. 901
OUT OUTPUT Output the value stored in the accumulator. 902
LDA LOAD Load the Accumulator with the contents of the memory address given. 5xx
STA STORE Store the value in the Accumulator in the memory address given. 3xx
ADD ADD Add the contents of the memory address to the Accumulator 1xx
SUB SUBTRACT Subtract the contents of the memory address from the Accumulator 2xx
BRP BRANCH IF POSITIVE Branch/Jump to the address given if the Accumulator is zero or positive. 8xx
BRZ BRANCH IF ZERO Branch/Jump to the address given if the Accumulator is zero. 7xx
BRA BRANCH ALWAYS Branch/Jump to the address given. 6xx
HLT HALT Stop the code 000
DAT DATA LOCATION Used to associate a label to a free memory address. An optional value can also be used to be stored at the memory address.
Tagged with: ,

Atbash Cipher Algorithm

The Atbash Cipher is a monoalphabetic substitution cipher that was originally used for the Hebrew alphabet. It is one of the earliest known subtitution ciphers to have been used. As opposed to a Caesar Cipher, the Atbash cipher does not need a key. It is hence easier to break!

The Atbash Cipher maps each letter of an alphabet it to its reverse, so that the first letter (e.g. A) becomes the last letter (e.g. Z), the second letter (B) becomes the second to last letter (Y), and so on.

Using the Latin Alphabet

Plain A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
Cipher Z Y X W V U T S R Q P O N M L K J I H G F E D C B A

Using the Hebrew Alphabet

  Aleph Bet Gimel Daleth Heh Vav Zayin Het Tet Yodh Kaph Lamed Mem Nun Samech Ayin Peh Tzady Koof Reish Shin Taw
Plain א ב ג ד ה ו ז ח ט י כ ל מ נ ס ע פ צ ק ר ש ת
  Taw Shin Reish Koof Tzady Peh Ayin Samech Nun Mem Lamed Kaph Yodh Tet Het Zayin Vav Heh Daleth Gimel Bet Aleph
Cipher ת ש ר ק צ פ ע ס נ מ ל כ י ט ח ז ו ה ד ג ב א

Encryption/Decryption Algorithm


Note that the same algorithm can be used to encrypt a plaintext into a ciphertext or to decrypt a ciphertext into a plaintext.

The flowchart below is used to encrypt or decrypt text using the Atbash Cipher. To fully understand this algorithm, you will need to understand how ASCII code works. The algorithm above is using the ASCII codes for the uppercase alphabet from letter A (ASCII 65) to letter Z (ASCII 90).

Video TutorialFlowchart

atbash-algorithm-flowchart

We can then use this function in a program used to retrieve the plaintext to encrypt (or ciphertext to decrypt) from the end user:
Atbash-Cipher-Input-Output-flowchart

Python Code


Your task is to implement the above algorithms using Python:

unlock-access

Solution...

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

Polar vs. Cartesian Coordinates

radar-polar-coordinatesIn this blog post we will investigate two types of coordinates used to identify the location of a point on a 2D plan:

  • Cartesian Coordinates (x,y)
  • Polar Coordinates (r,θ)

Both sets of coordinates have their own applications and are often used in computer systems and video games. After reviewing how these sets of coordinates work we will write a Python script based on trigonometric formulas to convert Cartesian coordinates into Polar coordinates and vice versa.

Cartesian CoordinatesPolar Coordinates
Cartesian coordinates are used to identify the exact location of a point on a 2D plan. Two perpendicular axis (x axis and y axis) meet at the origin (0,0). The (x,y) cartesian coordinates are based on the distance of a point from these axis.

Look at the canvas below to understand how Cartesian coordinates work:

When using Cartesian coordinates, we can divide the 2D plan into four quadrants as follows:
xy-coordinates

polar-coordinates
Polar coordinates are also used to identify the exact location of a point on a 2D plan. Using a polar coordinate system, each point on a plane is determined by a distance from a reference point and an angle from a reference direction. The reference point is called the pole, and the ray from the pole in the reference direction is the polar axis.

Look at the canvas below to understand how Polar coordinates work:


Polar to Cartesian Coordinates Conversion Formulas


Using trigonometric formulas we can easily convert Cartesian coordinates to Polar coordinates and vice-versa.
cartesian-polar-coordinates-conversion-formulas

Python Turtle Implementation


Your Task


Adapt the above Python code to generate random polar coordinates and apply the conversion to calculate and output the matching Cartesian coordinates.

Python Turtle Radar Animation


To apply the conversion formulas we have created a radar animation using Python Turtle:

Tagged with: