More results...

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

Assembly Language

Assembly language is a low-level programming language. Each assembly language is specific to a particular computer architecture. Assembly language uses mnemonics to represent low-level machine instructions or opcodes. Many operations require one or more operands in order to form a complete instruction. Most assembly languages let you use different modes of addressing to specify the value (immediate addressing) or location/memory address of an operand. Assembly languages also let you use labels in the code to point to specific memory locations or registers.

LMC


LMC (Little Man Computer) is an example of basic assembly language used for educational purposes. It consists of only 11 mnemonics (e.g. INP, OUT, STA, BRP, etc.) and is based on one memory addressing mode: direct addressing.
Little Man ComputerOpen in new tab/window

Translation Process


Because assembly language use a relatively basic syntax and a limited number of mnemonics, the translation process to convert low level code into machine code (aka object code or binary code) is fairly straightforward. This process is called “assembling” and is preformed by an assembler: a piece of software utility used to translate/assemble low-level code into binary code.

Because assembly depends on the machine code instructions, every assembler has its own assembly language which is designed for exactly one specific computer architecture.

Assembly language usually has one statement per machine instruction so there is the 1:1 relationship between a low-level instruction and a machine instruction. Basic computer architectures will result in a reduced number of instructions. More complex architectures will result in a wider range of instructions making it easier to write assembly code. (Find our more about RISC – Reduced Instruction Set – and CISC – Complex instruction Set – processors)

Unlike assembly language, most high-level programming languages are generally portable across multiple architectures but require interpreting or compiling, a much more complicated task than assembling.

Assembler


punched-tapeWe have created an online assembler for the LMC language to demonstrate the process of translating LMC code to machine/binary code. You can use it to load your own LMC programs and assemble them into binary.

In the early days of computer science (1950s, 1960s) computer programs could be “printed” using hole punched cards or tape. Our LMC assembler let you preview the resulting hole punched tape for your programs.


LMC AssemblerOpen in new tab/window

Tagged with:

Radians to Degrees Conversions

The radian is a unit of measure for angles used mainly in trigonometry. It is used as an alternative to degrees.
Whereas, in degrees a full circle is 360 degrees, in radians a full circle is 2π radians:
degrees-to-radians-conversions

It is easy to convert an angle from degrees to radians and vice-versa using the following formulas:
degrees-to-radians-formularadians-to-degrees-formula

Python Challenge


In this challenge we will write a program to convert an angle from degrees to radians or from radians to degrees based on the user’s choice. Our program will:

  • Display a menu of options to the end user.
  • Ask the end-user to choose an option from the menu.
  • Ask the end-user to input an angle in the required unit.
  • Calculate and output the angle in the alternative angle unit.

To structure this program we will make use of 3 subroutines as follows:

  • A menu() function that displays the available options, ask the user for an otpion and return the selected option.
  • A procedure called convertRadiansToDegrees() that ask the user to input an angle in radians, convert this angle using the appropriate conversion formula and output the angle in degrees.
  • A procedure called convertDegreesToRadians() that ask the user to input an angle in degrees, convert this angle using the appropriate conversion formula and output the angle in radians.

We will then write an algorithm to complete this challenge, making use of our three subroutines.

Flowcharts


We have designed the flowcharts for the three subroutines and for the main algorithm.

Flowchart #1Flowchart #2 and #3Flowchart #4
flowchart-radians-to-degrees-menu
flowchart-radians-to-degrees-subroutines
flowchart-radians-to-degrees

Python Code


Your task is to complete the Python code for this challenge, using the flowcharts provided above.

unlock-access

Solution...

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

Tagged with: , ,

Pygame Framework

The pygame library contains several modules and classes that you will use when creating video retro arcade games.

You will need to familiarise yourself with the most useful modules and classes as listed below: (Click on a module/class to access a description of the module/class)
pygane-framework
Zoom in / Open pygame framework in new window pygame top level module pygame.display module pygame.time module pygame.event module pygame.mouse module pygame.key module pygame.mixer module pygame.music module pygame.sprite module pygame.draw module pygame.transform module Sprite Class Surface Class Clock Class Event Class Group Class Rect Class Font Class Sound Class

You can access the Pygame online documentation to gain a better understanding of the main functions/methods and attributes from this framework and access relevant code examples.

Please note that the following list of modules classes and their matching functions/methods is only a selection of some of the most useful features of the pygame library. It is not an exhaustive list.

Modules/Classes Description Pygame Documentation
pygame-pygame pygame.init()
Initialise all imported pygame modules.

pygame.quit()
Uninitialise all pygame modules.

Access online documentation
pygame-sprite Sprite()
The base class for all the sprites of your game.

Group()
A container class to hold multiple Sprite objects.

spritecollide()
List all the sprites in a group that collide with a specified sprite.

groupcollide()
Find all sprites that collide between two groups.

collide_mask()
Check if two sprites are colliding (using mask/transparency).

Access online documentation
pygame-sprite-class alive
Does this sprite belong to any group? (Boolean value)

groups
A list of all the groups that contain this sprite.

update()
A method that can be overridden (in a derived class) to implement the behaviour of a sprite.

add()
Add this sprite to the specified group(s).

remove()
Remove this sprite from the specified group(s).

kill()
Remove the sprite from all groups.

Access online documentation
pygame-group-class sprites
A list of all the sprites contained by this group

add()
Add the specified sprite(s) to this group.

remove()
Remove the specified sprite(s) from this group.

has()
Check if specified sprite(s) are in this group.

update()
Call the update() method on all the sprites from this group.

draw()
Blit all the sprites images,

clear()
Draw the specified background over the sprites from this group.

empty()
Remove all sprites from this group.

Access online documentation
pygame-display init()
Initialise the display module.

quit()
uninitialise the display module.

set_mode()
Initialise a window or a screen for display using the specified size. This function returns a Surface object.

get_surface()
Get a reference to the currently set display surface.

flip()
Update the full display Surface to the screen.

update()
Update portions of the screen for software displays.

set_icon()
Change the system image for the display window.

set_caption()
Set the current window caption.

get_caption()
Get the current window caption.

get_window_size()
Return the size of the window or screen as a tuple: (width, height).

Access online documentation
pygame-draw line()
Draw a line on the specified surface.

rect()
Draw a rectangle on the specified surface.

polygon()
Draw a polygon on the specified surface.

circle()
Draw a circle on the specified surface.

ellipse()
Draw an ellipse on the specified surface.

Access online documentation
pygame-transform flip()
Flip the specified horizontally and/or vertically.

scale()
Resize the specified surface to a new resolution (width,height).

rotate()
Rotate a specified surface using a specified angle (in degrees).

Access online documentation
pygame-surface-class blit()
Draw a specified image/surface on this surface.

convert()
Change the pixel format of this surface/image.

convert_alpha()
Change the pixel format of this surface/image including per pixel alphas to support opacity/transparency.

fill()
Fill this surface with a solid color

set_colorkey()
Set the transparent colorkey.

set_alpha()
Set the alpha value for the full Surface image. (To allow transparency)

get_width()
Get the width of this surface.

get_height()
Get the height of this surface.

get_rect()
Returns the rectangular area (Rect object) of this Surface.

get_at()
Set the colour value for a single pixel identified using its (x,y) coordinates.

Access online documentation
pygame-rect-class x,y
Used to set or retrieve the x and y coordinates of the rectangle object. Other properties can also be used such as top, left, bottom, right, topleft, bottomleft, topright, bottomright, midtop, midleft, midbottom, midright, center, centerx, centery.

width
Used to set or retrieve the width coordinates of the rectangle object.

height
Used to set or retrieve the height coordinates of the rectangle object.

copy()
Create a copy the rectangle object.

move()
Move a copy the rectangle object to the specified (x,y) coordinates.

inflate()
Grow or shrink the rectangle size.

collidepoint()
Check if a point (identified using (x,y) coordinates) is inside a rectangle.

colliderect()
Check if this rectangle object overlaps with another specified rectangle object.

collidelist()
Check if this rectangle object overlaps with any other specified rectangle objects.

Access online documentation
pygame-font-class render()
Add text on a new surface.

set_underline()
To underline the text!

set_bold()
To render the text in bold!

set_italic()
To render the text in italic!

Access online documentation
pygame-time wait()
Pause the program for a specified amount of milliseconds.

delay()
Pause the program for a specified amount of milliseconds.

get_ticks()
Return the number of milliseconds since pygame.init() was called.

set_timer()
Set an event type to appear on the event queue every given number of milliseconds.

Clock()
Create a clock object to help track time and set the desired frame rate.

Access online documentation
pygame-clock-class tick()
Update the clock. Should be used once per frame.

get_time()
Return the number of milliseconds that passed between the previous two calls to Clock.tick().

get_fps()
Compute your game’s framerate (in frames per second) by averaging the last ten calls to Clock.tick().

Access online documentation
pygame-event Event()
Instantiate a new event object.

get()
Get (and remove) all the events from the queue. Type(s) of events to be retrieved can be specified.

wait()
Wait for a single event from the queue. The event will be returned and removed from the queue. While the program is waiting it will sleep in an idle state.

clear()
Remove all events from the queue. Type(s) of events to be removed can be specified.

Access online documentation
pygame-event-class type
The type of event such as QUIT, KEYDOWN, KEYUP, MOUSEMOTION, MOUSEBUTTONDOWN, MOUSEBUTTONUP, etc.

key
To find out which key has been pressed.

pos
To find out the position of the mouse cursor using (x,y) coordinates.

Access online documentation
pygame-mouse get_pressed()
Returns a list of Boolean values representing the state of all the mouse buttons.

get_pos()
Returns the position of the mouse cursor, using (x,y) coordinates.

set_pos()
Sets the position of the mouse cursor, using (x,y) coordinates.

set_visible()
Hide or show the mouse cursor.

set_cursor()
Change the image for the mouse cursor.

Access online documentation
pygame-key get_pressed()
Returns a list of Boolean values representing the state of all the keyboard keys.

get_mods()
Used to determine which modifier key(s) are being held.

name()
Returns the name (string value) of a key identifier.

Access online documentation
pygame-music load()
Load a music file for playback.

unload()
Unload the currently loaded music to free up resources.

play()
Start the playback of the music stream.

rewind()
Reset the playback of the current music to the beginning.

pause()
Temporarily stop music playback.

unpause()
Resume the previously paused playback.

fadeout()
Stop music playback with a fading out effect over a specified number of milliseconds.

stop()
Stop the music playback.

get_volume()
Set the music volume to a value between 0.0 and 1.0.

set_volume()
Return the current volume for the music. The value will be between 0.0 and 1.0.

queue()
Queue a sound file to follow the current. Only one sound file can be queued at a time.

Access online documentation
pygame-mixer pre_init()
Preset the mixer init arguments

init()
Initialise the mixer module.

pause()
Temporarily stop playback of all sound channels.

unpause()
Resume paused playback of sound channels.

fadeout()
Fade out the volume on all sounds before stopping.

stop()
Stop playback of all sound channels.

quit()
Uninitialise the mixer.

Sound()
Create a new Sound object from a file or buffer object.

Access online documentation
pygame-sound-class play()
Begin sound playback.

stop()
Stop sound playback.

fadeout()
Stop sound playback after fading out.

set_volume()
Set the playback volume for this Sound using a value between 0.0 and 1.0.

get_volume()
Get the playback volume for this Sound using a value between 0.0 and 1.0.

get_length()
Get the length in seconds of this Sound.

Access online documentation

Tagged with:

Abstract Syntax Tree Generator

ASTIn computer science, an abstract syntax tree (AST), or just syntax tree, is a tree representation of the high level source code.

The compilation process consists of translating the high level source code (e.g. Java, Python, C++, FORTRAN, etc.) into machine code. This process consists of 4 steps:

  1. Lexical Analysis
  2. Syntax Analysis
  3. Code Generation
  4. Code Optimisation

A list of tokens is generated during the lexical analysis of the compilation process.
An Abstract Syntax Tree (AST) is generated during the syntax analysis of the compilation process.

The following tool enables you to type/import some high level code (Javascript) in the first tab below and generate the list of tokens and the Abstract Syntax Tree corresponding to your code. You can see what the tree looks like using the JSON format (third tab) or as a visual representation (fourth tab).

Source CodeTokens (JSON)TokensAST (JSON)AST Tree

Javascript Code:


Copy and paste your JavaScript code in the textarea below and press the “Generate Abstract Tree” button below to generate the list of tokens (lexical analysis) on tab 2 and the AST tree (syntax analysis) on tab 3 and tab 4.
Generate Abstract Syntax Tree

List of Tokens (JSON format)


The list of tokens is generated from the source code during the lexical analysis stage of the compilation. Notice how, during the lexical analysis, annotations and white spaces are discarded and are hence not included in the list of tokens.

List of Tokens


The list of tokens is generated from the source code during the lexical analysis stage of the compilation. Notice how, during the lexical analysis, annotations and white spaces are discarded and are hence not included in the list of tokens.

Abstract Syntax Tree (JSON format)


The Abstract Syntax Tree is generated using both the list of tokens (from the lexical analysis) and the source code. The AST is generated during the syntax analysis stage of the compilation. Any syntax error would be detected and a syntax error message would then be returned, stopping the compilation process.

Abstract Syntax Tree

Open AST in new window

Did you know?


Rear Admiral Grace Hopper, 1984

Rear Admiral Grace Hopper, 1984

One of the first programming languages to be compiled was COBOL. It was invented in the 1950s based on the work of Grace Hopper (1906 – 1992). Grace Hopper was an American computer scientist and United States Navy rear admiral. she was a pioneer of computer programming who invented the first compiler. While at the time all programs were based on mathematical notations, she believed that a programming language based on English words was possible and would be more accessible to a wider range of programmers. In 1955, she and her team wrote a specification for such a programming language and implemented a prototype: The FLOW-MATIC compiler became publicly available in the late 1950s. Her compiler converted English terms into machine code understood by computers. Her work also focused on the idea of designing machine-independent programming languages, which led to the development of COBOL, an early high-level programming language still in use today.

Grace Hopper had a key role in the development of computer science. She invented the concept of sub-routines to help programmers save time when writing code. Her work on developing high-level languages was also motivated by the need to be able to save time when writing programs, as writing low-level code can be extremely time consuming.

Women in STEM


Listen to what Megan Smith (U.S. Chief Technical Officer) said about Grace Hooper in 2014:
Source: Women in Stem, U.S. Chief Technology Officer Megan Smith / Public domain

The first computer bug!


Nowadays, when we find an error in a computer program, we call this error a bug. While Grace Hopper was working on a Mark II Computer at Harvard University in 1947, her team discovered a moth stuck in a relay. The moth impeded the operation of the relay by creating a short-circuit. The problem was fixed by removing the moth (debugging the relay!). The following picture is a photo of the notes from Grace Hopper and her associates with a picture of the actual moth!
The first computer bug!

The first computer bug!

Source: Naval History and Heritage Command

Arduino: RGB Gradient

In this challenge we will use the Arduino board to control a RGB LED to create a gradient light effect where the LED will fade from red to purple, to blue, to purple and back to red.

gradient-red-blue-red

You do not need to have access to an Arduino board. Instead you can use the online Arduino simulator from Tinkercad to recreate the electronic circuit and add the code provided below.

Open Tinkercad in new window

RGB Colour Codes


Did you know that every 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)

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

Electric Circuit


An RGB LED is a 3-in-1 LED. It consists of a RED LED, a Green LED and a Blue LED all within the same component. It has 3 cathodes (+ pins) that can take different amperages. It has 1 common anode (- pin).
RGB-LED
This is how we will connect our RGB LED to our Arduino board.
arduino-RGB-gradient

The purpose of the resistors is to limit the amperage in the circuit and hence protect the LED from receiving a too strong current (which could damage the LED). The resistors we use here are 100 ohms (Brown Black Brown rings).

C/C++ Code

// Arduino - RGB Gradient - www.101computing.net/arduino-rgb-gradient
int redOut = 13;
int greenOut = 11;
int blueOut = 12;

void setup() {
  pinMode(redOut, OUTPUT);
  pinMode(greenOut, OUTPUT);
  pinMode(blueOut, OUTPUT);
}

void setRGB(int red, int green, int blue)
 {
    analogWrite(redOut, red);
  	analogWrite(greenOut, green);
  	analogWrite(blueOut, blue);
}

void loop() {
  int red = 255;
  int green = 0;
  int blue = 0;
  for (int i = 0; i <= 255; i++) {
    blue = i;
	setRGB(red,green,blue);
    delay(20);
  } 
  for (int i = 0; i <= 255; i++) {
    blue = 255 - i;
	setRGB(red,green,blue);
    delay(20);
  } 
  
}

Your Challenge


Tweak this code to create other gradient animations:
Gradient 1: Cyan, Magenta, Cyan
gradient-cyan-magenta-cyan
Gradient 2: Cyan, Yellow, Cyan
gradient-cyan-yellow-cyan
Gradient 3: Green, Yellow, Magenta, Cyan, Green
gradient-green-yellow-magenta-cyan-green

Arduino Whack a Mole

For this challenge we will create a a game of Whack-A-Mole using an Arduino device/board, three LEDs, three push buttons and a piezo buzzer.

You do not need to have access to an Arduino board. Instead you can use the online Arduino simulator from Tinkercad to recreate the electronic circuit and add the code provided below.

Open Tinkercad in new window

Electronic Circuit


First you will need to recreate the following electronic circuit:
arduino-Whack a Mole

C/C++ Code


Then you will need to use the following code (When using tinkerpad, choose the text option rather than blocks)

// Arduino Whack-A-Mole - www.101computing.net/arduino-whack-a-mole
int red = 0;
int green = 0;
int blue = 0;
int redIn = 5;
int redOut = 11;
int greenIn = 6;
int greenOut = 12;
int blueIn = 7;
int blueOut = 13;
int piezoPin = 10;
int incorrectOut = 10;
int correctOut = 9;
int mole = -1;

void setup()
{
  pinMode(redOut, OUTPUT); 
  pinMode(greenOut, OUTPUT); 
  pinMode(blueOut, OUTPUT); 
  pinMode(redIn, INPUT); 
  pinMode(greenIn, INPUT); 
  pinMode(blueIn, INPUT); 
}

// During the pause all thre moles are hidden, pressing any button would trigger a low pitch noise
void pause() {
  unsigned long current;
  unsigned long end;
  
  mole = -1;
  digitalWrite(redOut, LOW);
  digitalWrite(greenOut, LOW);
  digitalWrite(blueOut, LOW);
  
  int pause = rand() % 500 + 100;
  current = millis();
  end = millis() + pause;
  while  (millis()<end) {
   	red = digitalRead(redIn); 
   	green = digitalRead(greenIn); 
   	blue = digitalRead(blueIn); 
    if (red == HIGH || green == HIGH || blue == HIGH) { 
       tone(piezoPin, 100, 300); //Pin,Frequency,Duration
       delay(300);
    }
  }
}

// Randomly decide which LED to turn on
void displayMole() {
  mole = rand() % 3 + 1;
  if (mole==1) {
    digitalWrite(redOut, HIGH); 
  } else if (mole==2) {
    digitalWrite(greenOut, HIGH);
  }else if (mole==3) {
    digitalWrite(blueOut, HIGH); 
  }
}

// If the user presses a button corresponding to the right LED (Whack a mole) > High pitch noise
// If the user presses the wrong button > Low pitch noise
void whackMole() {
  unsigned long current;
  unsigned long end;
  current = millis();
  end = millis() + 500;
  while  (millis()<end) {
  	red = digitalRead(redIn);  // read input value
  	if (red == HIGH) {         // check if the input is pressed
   		if (mole==1) {
        	// High pitch tone +++
    		tone(piezoPin, 1000, 10); //Pin,Frequency,Duration
    		delay(10);
    	} else {
        	// Low pitch tone ---
        	tone(piezoPin, 100, 300); //Pin,Frequency,Duration
    		delay(300);
   	 	}  
  	}
    green = digitalRead(greenIn);  // read input value
  	if (green == HIGH) {         // check if the input is pressed
   		if (mole==2) {
        	// High pitch tone +++
    		tone(piezoPin, 1000, 10); //Pin,Frequency,Duration
    		delay(10);
    	} else {
        	// Low pitch tone ---
        	tone(piezoPin, 100, 300); //Pin,Frequency,Duration
    		delay(300);
   	 	}  
  	}
    blue = digitalRead(blueIn);  // read input value
  	if (blue == HIGH) {         // check if the input is pressed
   		if (mole==3) {
        	// High pitch tone +++
    		tone(piezoPin, 1000, 10); //Pin,Frequency,Duration
    		delay(10);
    	} else {
        	// Low pitch tone ---
        	tone(piezoPin, 100, 300); //Pin,Frequency,Duration
    		delay(300);
   	 	}  
  	}    
  }  
}

void loop() {
  pause();
  displayMole();
  whackMole();
}
Tagged with:

Arduino Traffic Lights

For this challenge we will create a traffic lights using an Arduino device/board and three LEDs.

We will use C/C++ to create the code to control the Arduino board to reproduce a following traffic lights sequence:
traffic-light-sequence

You do not need to have access to an Arduino board. Instead you can use the online Arduino simulator from Tinkercad to recreate the electronic circuit and add the code provided below.

Open Tinkercad in new window

Electronic Circuit


First you will need to recreate the following electronic circuit:
arduino-traffic-light

C/C++ Code


Then you will need to use the following code (When using tinkerpad, choose the text option rather than blocks)

// Arduino Trafic Lights - www.101computing.net/arduino-traffic-lights

void setup()
{
  pinMode(13, OUTPUT); // Red LED
  pinMode(12, OUTPUT); // Amber LED
  pinMode(11, OUTPUT); // Green LED
}

void loop()
{
  // Green
  digitalWrite(13, LOW);
  digitalWrite(12, LOW);
  digitalWrite(11, HIGH);
  delay(3000); // Wait for 3000 millisecond(s)
  
  // Amber
  digitalWrite(12, HIGH);
  digitalWrite(11, LOW);
  delay(1000); // Wait for 1000 millisecond(s)

  // Red
  digitalWrite(13, HIGH);
  digitalWrite(12, LOW);
  delay(3000); // Wait for 3000 millisecond(s)

  // Red + Blinking Amber
  digitalWrite(13, HIGH);
  digitalWrite(11, LOW);
  for (int i = 0; i < 3; i++) {
  	digitalWrite(12, HIGH);
    delay(500); // Wait for 500 millisecond(s)
  	digitalWrite(12, LOW);
    delay(500); // Wait for 500 millisecond(s)
  }
}

Lego Traffic Ligths


If you have access to an Arduino board you can create your own traffic lights and you can plug your LEDs on a breadboard or use lego bricks to create your traffic lights.
lego-traffic-light-frontlego-traffic-light-backlego-led

LEDYou will need:

  • 1 arduino board
  • 1 breadboard
  • 3 resistors (220Ω)
  • 3 LEDs (Red, Organe/Yellow, Green)

Make sure that you always connect the cathode of the LED (short leg, flat edge of the LED) to a black wire.

Create your own Sound Effects in Python

zapThe purpose of this challenge is to create your own collection of sound effects to be used a library of assets for your own retro arcade games.

We will use Python code online to create the sound file using EarSketch.

EarSketch?


A Digital Audio Workstation (DAW), is the main tool for producing music on a computer. A DAW is specialised computer software for recording, editing, and playing digital audio files. EarSketch is a DAW which let you place audio clips and effects into a DAW timeline using either Python code or JavaScript code.

Check the following sound effects that we have created using EarSketch. You can re-use and adapt the code for your own video game projects.

Cannon EffectRefill EffectAlternative Cannon Effect
#Cannon Effect by 101Computing.net
from earsketch import *

init()
setTempo(120)
clip = DUBSTEP_BASS_WOBBLE_018
clip = EIGHT_BIT_ATARI_SFX_001

# 0 starts playing a clip, - is a rest/silence, + extends the audio clip into the next sixteenth note sub-beat
beat = "-0+0+-0+0+-0+0+--000000+-000000+"

makeBeat(clip, 1, 1, beat)

finish()
Open sound effect using EarSketch
#Refill/Reload Effect by 101Computing.net
from earsketch import *
init()
setTempo(120)

clip = EIGHT_BIT_ATARI_LEAD_007
beat = "00000000000000000000000000000000"
makeBeat(clip, 1, 1, beat)
setEffect(1, PITCHSHIFT, PITCHSHIFT_SHIFT, 0, 1, 12, 3)

# Finish
finish()
Open sound effect using EarSketch
#Cannon Effect by 101Computing.net
from earsketch import *

init()
setTempo(120)
clip = DUBSTEP_BASS_WOBBLE_018

# 0 starts playing a clip, - is a rest/silence, + extends the audio clip into the next sixteenth note sub-beat
beat = "-00+-00+-00+-00+"
makeBeat(clip, 1, 1, beat)

finish()
Open sound effect using EarSketch

Using Sound Effects with PyGame


To add sound effects, download some wav or mp3 files into a folder called “Sounds” and add the following code when you want to play the sound effect:

effect = pygame.mixer.Sound('Sounds/cannon_effect.mp3')
effect.play()

Create your own music using Python!

retro-musicFor this challenge we will investigate how we can use Python code to create our own background music and sound effects to be used in a retro arcade game.

Most music editing software (e.g. GarageBand, Cubase, FL Studio, Logic Pro etc.), are Digital Audio Workstations (DAW) and let you create your own music by adding audio clips, virtual instruments and effects to a multi-track timeline. Editing and mixing your music is done through a Graphical User Interface.

On occasions, you may try a different approach to control the DAW through code. Websites such as EarSketch let you create your code online using either Python or JavaScript and import it to a DAW to visualise your timeline and play it.

Digitial Audio Workstation

Digitial Audio Workstation

In the example below, we are using Python code with basic audio clips from the “Eigthbit” library to recreate some retro arcade game music to be used on a game intro / splash screen.

It demonstrates some of the key basic features of EarSketch:

  • Set the tempo
  • Import audio clips (on different tracks and at specified times)
  • Add audio clips to the timeline
  • Add effects (including fade in, fade out and delay effects)
  • Use a loop to repeat a clip

Python Code

#		python code
#		script_name: Game_Intro.py
#
#		author: 101Computing
#		description: Background music for intro 
#

from earsketch import *

init()
setTempo(120)

clip1 = EIGHT_BIT_ATARI_SFX_004
clip2 = EIGHT_BIT_ATARI_LEAD_011
clip3 = EIGHT_BIT_ATARI_LEAD_010

pointA = 1.75
repeat = 3
pointD = pointA + repeat 

#fitMedia(Clip,Track,StartMeasure,EndMeasure)
fitMedia(clip1,1,1,2)
for i in range(0,repeat):
  fitMedia(clip2,2,pointA + i,pointA + i + 1)

fitMedia(clip3,3,pointA,pointD + 1)

#setEffect(Track,effect,parmeter,value)
setEffect(3, VOLUME, GAIN, -10)

#setEffect(Track,effect,parmeter,value,start measure,value,end measure)
#Fade in
setEffect(1, VOLUME, GAIN, -40, 1, 0, 1.75)
#Delay Effect
setEffect(1, DELAY, DELAY_TIME, 250)
setEffect(2, DELAY, DELAY_TIME, 250)
#Fade Out
setEffect(3, VOLUME, GAIN, -10, pointD, -60, pointD+1)

finish()

Test this code on EarSketch


You can test this code on EarSketch.

Adding Background Music with PyGame


To add a background soundtrack, download a wav file or mp3 file into a folder called “Sounds”.

At the start of your code (main.py), after importing the pygame library, add the following lines of code:

pygame.mixer.pre_init(frequency=44100, size=-16, channels=2, buffer=4096)
pygame.mixer.music.load('Sounds/soundtrack.mp3')
pygame.mixer.music.play(-1) #-1 means loops for ever, 0 means play just once)

Note that you can stop the music at any time using the following instruction:

pygame.mixer.music.stop()

You may prefer to pause the music:

pygame.mixer.music.pause()

… or unpause the music:

pygame.mixer.music.unpause()

Adding Sound Effects using PyGame


To add sound effects, download some wav or mp3 files into a folder called “Sounds” and add the following code when you want to play the sound effect:

effect = pygame.mixer.Sound('Sounds/beep.wav')
effect.play()

Scratch -Take the Quiz!

Answer these 10 questions to test your understanding of Block Programming when using Scratch.

Take the Quiz! (open full screen)


Check that you understand the different types of validation checks by completing this quiz:

Extension Task


Use the scratch website to recreate some of the scripts used in this quiz.

Tagged with: , ,