More results...

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

Prolog – Food Web Challenge

Prolog is a language built around the Logical Paradigm: a declarative approach to problem-solving.

There are only three basic constructs in Prolog: facts, rules, and queries.

A collection of facts and rules is called a knowledge base (or a database) and Prolog programming is all about writing knowledge bases. That is, Prolog programs simply are knowledge bases, collections of facts and rules which describe some collection of relationships that we find interesting.

So how do we use a Prolog program? By posing queries. That is, by asking questions about the information stored in the knowledge base. The computer will automatically find the answer (either True or False) to our queries.

Source: http://www.learnprolognow.org/

Knowledge Base (Facts & Rules)


Check the following knowledge base used to store the information that appears on a food web:

/* Facts */
plant(grass).
plant(berries).
plant(nuts).

insect(caterpillar).
insect(butterfly).

animal(squirrel).
animal(goldfinch).
animal(fox).
animal(snake).
animal(frog).
animal(eagle).
animal(X) :- insect(X).

insectivore(frog).
insectivore(goldfinch).  

eats(caterpillar,grass).
eats(butterfly,berries).
eats(goldfinch,berries).
eats(squirrel,nuts).
eats(fox,squirrel).
eats(fox,goldfinch).
eats(snake,goldfinch).
eats(snake,frog).
eats(eagle,frog).
eats(eagle,snake).
eats(eagle,goldfinch).
eats(X,Y) :- insectivore(X), insect(Y).         

/* Rules */
herbivore(X):- eats(X,Y), plant(Y).
carnivore(X):- eats(X,Y), animal(Y).
omnivore(X):- herbivore(X), carnivore(X).

predator(X,Y):- eats(X,Y).
prey(X,Y):- eats(Y,X).

pyramid(X,Y):- prey(Y,X).
pyramid(X,Y):- prey(Z,X), pyramid(Z,Y).

Queries


We can now query this database. For each of the queries listed below, what do you think the computer will return?

True or False Queries:
The following queries would return either True or False.

?-herbivore(butterfly).
?-herbivore(fox).
?-omnivore(goldfinch).
?-predator(fox,squirrel)
etc.

Other Queries:
The following queries would return a solution which could be either:

  • A unique value
  • A list of values
  • False if no solution can be found
?-animal(X)
?-herbivore(X).
?-predator(goldfinch,X).
?-pyramid(fox).
etc.

Your Task:


Use a range of queries, similar to the one above to interrogate the knowledge base and complete the food web provided below.

To run your queries you will need to use the online Prolog environment:
https://swish.swi-prolog.org/p/Food-Web-Prolog.pl

Here is the template for the food web for you to complete:
prolog-food-web

Tagged with:

Logic Gates Diagrams (Whiteboard)

QuestionAnswer
Draw the logic gates diagram for the following Boolean expression:

Next Question
Next Question

Scratch – Sprite Movement using a Touchscreen

Many tutorials on how to create a game in Scratch will be based on using the arrow keys to control the main sprite. This is a great approach indeed but is not suitable if you are designing the game toe be used on a tablet or smartphone. In this case, your input device to control the main sprite is not the keyboard but the touchscreen.

The following short tutorial will show you how you can control the movement of your sprite (in this case the cat) using a touchscreen. The idea will be to create two other sprites/buttons called Arrow_Left and Arrow_Right that, when clicked using a mouse or tapped using a touchscreen will tell the cat sprite to move in the relevant direction.
scratch-touchscreen-sprite-movement
You can recreate this code online using the scratch website.

Step 1: Right ArrowStep 2: Left ArrowStep 3: Main SpriteStep 4: Up & Down

Step 1: Arrow_Right Sprite


scratch-new-sprite
You will need tot create a new sprite and use the arrow sprite from the scratch library.
scratch_arrow_sprite

You should rename this sprite “Arrow_Right”.

You will then need to add the following code to this sprite to detect when the user clicks or taps on this sprite:
scratch-arrow-right-code

Step 2: The Arrow Left


Repeat the instructions from Step 1 to create another arrow sprite and call it “Arrow_Left”. The code for this new sprite will be as follows:
scratch-arrow-left-code

You will also need to change the costume of this sprite to show an arrow pointing to the left:
scratch-arrow-costume

The main sprite (in this case the cat, will need to move left or right when it receives the messages “left” and “right”. To do so we will use the following code (on the cat sprite):
scratch-cat-sprite-left-right
You can repeat the above steps to create an Arrow_Up and a Arrow_Down sprite if it is relevant to your game.

Thank You Medical Staff and Key Workers!

During the coronavirus pandemic, the rainbow has become a symbol of gratitude for the medical staff working in hospitals as well as all the other key workers who carried on working to provide essential services to their community.

All over the UK, children have drawn or painted colourful rainbows and have displayed them on their windows or front doors.

In this challenge, we will use some python code to draw a rainbow and a “Thank You” message to all medical staff and key workers.

This is what the output of our code should look like:
thank-you-medical-staff-and-key-workers

Your Task


We have written the code using Python Turtle but it does not produce the expected outcome.

Could you:

  • Change lines 20 to 28 to make sure the code displays the colours of the rainbow in the right order
  • Change lines 30 to 35 to make sure the stars and text are of the right colours.

The output of your code should be the same as the above picture.

Extension Task


You can tweak this code further to change the message or improve the overall look and feel further for instance by adding more stars and playing with the colours used to display the text.

unlock-access

Solution...

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

Colour Luminance and Contrast Ratio

The luminance of a colour is a measure used to describe the perceived brightness of a colour. It is possible to calculate the luminance of a colour based on its RGB colour code.
colour-luminance-values

So let’s consider an algorithm that collects an RGB colour code as an input, using the (255,255,255) format. The algorithm will then convert these R, G, B values to a 0 to 1 scale as follows:
colour-luminance-RGB-conversion

New R1,G1 B1 values are then calculated using the following rules:
colour-luminance-formula-Red
colour-luminance-formula-Green
colour-luminance-formula-Blue

Finally, the luminance value of the colour can be calculated using the following formula:
colour-luminance-RGB-formula

The reason such complex formulas are necessary to calculate the luminance (“perceived brightness”) of a colour is partly because our eyes’ perception of the brightness of a colour is not linear (it is not directly proportionate to the number of photons being emitted by a computer screen). Effectively our eyes perceive more levels of light in dim conditions, and less in brighter conditions.

Luminance Function


Your first task is to write a function called luminance() that takes 3 parameters r, g and b corresponding to the RGB values of a colour (integer values between 0 and 255). Your function will use the above algorithm to calculate and return the luminance of the given colour.

You can use the trinket at the bottom of this page to write the Python code for this fucntion.

Contrast Ratio


The contrast ratio defines how easy a human eye recognises text or images on a coloured background.

  • The contrast ratio is a numerical ratio between 1:1 and 21:1.
  • To be easily readable, the contrast ratio between the text colour and the background colour must be at least 7:1.
  • A contrast ratio of at least 4.5 may suffice for larger text.

contrst-ratio-low-medium-high

To calculate the contrast ratio between two colours (e.g. font/text colour and background colour) you must first calculate the luminance of both colours and identify which colour is the lightest colour and which colour is the darkest colour. You can then use these luminance values (labelled Llight and Ldark) to calculate the contrast ratio as follows:
contrast-ratio-formula

Contrast Ratio Function


Your second task is to write a function called contrastRatio() that takes 6 parameters corresponding to the RGB values of two colours (integer values between 0 and 255). Your function will work out the luminance values of both colours, identify the lightest of the two colours and use the above formula to calculate and return the contrast ratio between these two colours.

Test Plan


Once your code is complete, check that it works as expected using the following four tests:

Test # Input Values Expected Output Pass/Fail?
#1 (255,255,255)
(0,0,0)
Luminance: 100%
Luminance: 0%
Contrast Ratio: 21
#2 (148, 57, 173)
(174, 84, 199)
Luminance: 12.24%
Luminance: 19.46%
Contrast Ratio: 1.42
#3 (148, 57, 173)
(209, 157, 223)
Luminance: 12.24%
Luminance: 43%
Contrast Ratio: 2.78
#4 (148, 57, 173)
(245, 232, 248)
Luminance: 12.24%
Luminance: 83.9%
Contrast Ratio: 5.16

Magic Trick Algorithm

playing-cardsIn this blog post we are investigating whether we can teach a computer how to perform a magic trick.

Algorithm


If you want a computer to perform a specific task you need to provide this computer with a clear set of instructions that the computer will repeat, one instruction at a time. We call such a set of specific instructions an algorithm.

One of the key characteristic of an algorithm is that the instructions are given in a specific order, forming a sequence of instructions. When the computer will complete your algorithm, it will complete each instructions one instruction at a time in the order they appear on the algorithm. We call this sequencing, a key concept of computer algorithms.
sequencing-label

When designing an algorithm, we can either write our instructions as a list (Pseudocode) or we can use a more visual representation of our algorithm using a flowchart.

Magic Trick Algorithm


We have implemented a magic trick algorithm based on a small deck of cards. When you press the start button below, the computer will follow the sequence of instructions from this algorithm to perform the magic trick.

Let’s see if the computer can perform this magic trick successfully:


Click on the button below to start the magic trick!

Magic Trick Algorithm/Flowchart


The flowchart for this algorithm will help you work out how the actual card trick works!
magic-trick-flowchart
Click on the above flowchart to open in a new window.

Tagged with:

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