More results...

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

Pacman Ghost Algorithm

pacman
In a game of Pacman a specific algorithm is used to control the movement of the ghosts who are chasing (running towards) Pacman.

For this challenge we will assume that ghosts can walk through walls (as ghosts do!). So we will implement an algorithm that is slightly different to the algorithm used in the real game of Pacman where ghosts can only run alongside the corridors of the maze.

Our algorithm will be used in a frame based game where the sprites (e.g. Pacman, Ghosts) are positioned using (x,y) coordinates. The Pacman movement will be based on the position of the mouse cursor whereas the Ghosts will use a velocity vector (vx,vy) to move/translate between two frames.

velocity-vector

Trigonometric Ratios: SOH-CAH-TOA


Our algorithm will use the trigonometric ration to find the angle the Ghost needs to head towards to chase Pacman.
pacman-sohcahtoa-angle

The next step of our algorithm will use this angle to calculate the velocity vector (Vx,Vy) of the ghost:
pacman-sohcahtoa-velocity

The final step of our algorithm will update the (x,y) coordinates of our ghost to apply the velocity vector translation before drawing the ghost sprite on the screen.
pacman-sohcahtoa-translation

Python Code


Tagged with:

Bouncing Algorithm

pong-gameBouncing algorithms are often used in arcade games such as Pong or Breakout.

To understand how to implement a bouncing algorithm, it is essential to understand how the computer controls the trajectory of a sprite (e.g. ball) on the screen. Arcade games are based on a frame based animation where the screen is refreshed every x milliseconds. Moving sprites are positioned using (x,y) coordinates and have a velocity vector (Vx,Vy) which specifies the delta in pixels to apply to the (x,y) coordinates of a sprite between two frames:

  • frame n: Sprite Coordinates: (x,y)
  • frame n+1: Sprite Coordinates: (x+Vx,y+Vy)

velocity-vector

As the sprite moves across the screen, it may need to bounce against another sprite or against the edge of the screen.

Let’s investigate how the velocity vector is affected when the sprite bounces against vertical and horizontal walls/edges.

Right Wall/EdgeLeft Wall/EdgeTop Wall/EdgeBottom Wall/Edge
bouncing-algorithm-right
bouncing-algorithm-left
bouncing-algorithm-top
bouncing-algorithm-bottom

Python Code


The following Python code implements a bouncing algorithm against all 4 edges of the canvas.

Tagged with:

Closest Player Detection Algorithm

basket-ballHave you ever noticed when playing a team sport video game such as a (football, basketball, rugby game, etc.) the computer often finds out who the closest player to the ball is so that you can run to the ball with the closest player.

To do so the computer uses a specific algorithm to identify who, of all the players in your team, is the closest to the ball. This algorithm can also be used when you already control a player who has the ball to find out who is your closest team player to pass the ball to.

In this blog post we will investigate how this algorithm works and will implement this algorithm using Python.

On a team sport video game, each player is a sprite that is given an x and a y coordinate to be positioned on the pitch/screen.

The ball is also positioned using (x,y) coordinates.

To find out who the closest player is to the ball, we need to calculate the distance between the ball and each player of the team. To do so we will use Pythagoras formula:
closest-player-detection-algorithm

We can then use an algorithm to find the shortest distance and highlight the corresponding player.

Python Code


Tagged with:

Random Background Generator

artillery-gameIn this challenge we will use a Python script (using Python Turtle) to generate a random background for a 2D video game.

artillery-game-background

To create a mountain range skyline we will use two different approaches:

  1. Using a polynomial function
  2. Using a composite sine wave function

Using a Polynomial Function

Polynomial Function of Degree 2

Polynomial Function of Degree 2

Polynomial Function of Degree 3

Polynomial Function of Degree 3

Polynomial Function of Degree 4

Polynomial Function of Degree 4

Polynomial Function of Degree 5

Polynomial Function of Degree 5

Polynomial Function of Degree 6

Polynomial Function of Degree 6

Polynomial Function of Degree 7

Polynomial Function of Degree 7

 

In our example (see trinket below) we will use a polynomial function of degree 3:

y = a*x3 + b*x2 + c*x + d

The coefficients a,b,c,d of our polynomial function will be randomly generated. This will hence create a different background/skyline every time the program is executed.

We will then use this function to place some trees on the skyline. The x coordinate of the tree will be randomly generated whereas the polynomial equation will be used to calculate the y coordinate of each tree.

Python Code


Your Challenge


Update this code to add another set of trees. The trees could be positioned randomly anywhere on the grass area of the landscape. (Anywhere between the bottom of the screen and the skyline)

Extension Task


Update this code to add some clouds. The clouds should be positioned randomly anywhere in the sky. (Anywhere between the top of the screen and the skyline)

Alternative Approach… Using a composite sine wave


Instead of using a polynomial function we could use a composite sine wave function. You may find this solution either to implement especially when generating several peaks and peats.

A composite sine wave function is a combination of two simple sine waves with different frequency, phase and amplitude.

Here is the equation of a simple sine wave function:


A sine wave is too predictable/repetitive to create an interesting background. We will therefore create a composite function to generate peaks and heaps of different amplitudes.

To create a composite sine wave function we will use two functions as follows:

Here is our demo:

Tagged with: ,

Oblique Projection Formulas

3D-coordinates-cubeThe aim of this challenge is to demonstrate how the oblique projection formulas are used to convert 3D coordinates (x,y,z) into 2D coordinates (x,y).

oblique-projection-formulae

The oblique projection formulas are essential to understand how 3D models are displayed on a 2D screen. They are heavily used in 3D video games, computer animations and virtual reality.

Let’s apply these formulas to represent a simple 3D cube on a 2D canvas using Python Turtle.

Your Task


Compete the code provided above to add some extra vertices and edges to create a 3D house as follows:house-3d-coordinates

unlock-access

Solution...

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

RISC and CISC Processors

cpu-risc-cisc
RISC and CISC are two computers architectures that are used by CPUs.
Complete this drag and drop activity to highlight the characteristics of RISC & CISC processors.

instructions
several
Complex
Reduced
Software
circuitry
1
Desktop
simpler
Embedded devices
Many
clock cycle

RISC Architecture

  • A RISC ( Instruction Set Computers) processor can only decode a small number of
  • A RISC processor has a design so is easier to design and manufacture.
  • A RISC processor processes one instruction per (= machine cycle).
  • In a RISC processor: 1 instruction = 1 FDE Cycle = Clock Cycle
  • Software is more complex to write with a RISC processor.
  • Typical Use: (e.g. Washing Machines, GPS SatNav, mobile phones etc…)

CISC Architecture

  • A CISC ( Instruction Set Computers) processor can decode a larger number of instructions.
  • A CISC processor has a complex design/.
  • A CISC processor processes one instruction using clock cycles (= machine cycles).
  • In a CISC processor: 1 instruction = 1 FDE Cycle = Clock Cycles
  • is easier to write with a CISC processor.
  • Typical Use: , Laptop

Parallax Scrolling Effect

parallax-scrolling-effect2D arcade video games often use a frame based approach. This means that the screen is refreshed every so often (for instance every 20 milliseconds). This enables to animate the Graphical User Interface of the game making the game more engaging.

When the main character is moving across the screen, a parallax scrolling effect can be used to animate the background according to the speed of the player.

A parallax effect is based on the idea that when your character is moving side to side, the objects closer to the camera appear to move faster, while the objects in the distance appear to move more slowly.

Parallax Effect Animation by Nathaniel Domek.

Parallax Effect Animation by Nathaniel Domek.

A parallax scrolling effect is sometimes used in video games to draw and animate the background. This technique is used for instance in the video games Angry Birds and Flappy Bird. It is based on the idea that the background landscape consists of different layers: the foreground closed to the camera viewpoint, short distance background layers (e.g. trees, buildings) and long distance background layers (e.g. mountains).

You can read more about Parallax Scrolling on this page: https://en.wikipedia.org/wiki/Parallax_scrolling

In this challenge we will draw a background consisting of three mountain ranges each having its own skyline. To create our parallax effect we will animate each skyline to translate horizontally at a different speed.

Parallax Effect in 3D games


Parallax effect algorithms can be a lot more complex especially when applied to 3D video games. Such Parallax effect algorithms will involved a lot of trigonometric calculations!

Parallax Effect in a 3D video game

Parallax Effect in a 3D video game

Parallax Scrolling Effect in Web Design


This technique is now used by web-designer to add a parallax animation effect to a web page when the user scroll down the page. It is based on the idea that different components of the web page (background pictures, pictures and video clips, header & footer sections, navigation bar, etc.) are positioned on different layers which will scroll at a different speed when the user scroll down the page.

Layer Cake using Python Turtle

layer-cakeIn this challenge we will use Python Turtle to create and draw a layer cake.

The code provided at the bottom of this blog post is using a few computing concepts such as:

  • A list to store the parameters of the layers of our cake,
  • A dictionary to match specific colour codes to different ingredients,
  • (x,y) coordinates to position the turtle on the screen.


List?


In Python, a list is used to save a collection of values. For instance, to save all the different days of the week we could declare a variable called “daysOfTheWeek” and assign a list as follows (Notice the use of square brackets):

daysOfTheWeek = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]

Based on this what do you think len(daysOfTheWeek) would return?
What’s about daysOfTheWeek[0]?
Or daysOfTheWeek[3]?

Looping through a list


It is possible to access each value of a list one at a time using a for loop. Look at the following code to print the seven days of the week.

daysOfTheWeek = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]

for day in daysOfTheWeek:
    print(day)

Dictionary?


By completing this challenge we are going to learn about Python dictionaries.
In Python, a dictionary consists of pairs (called items) of keys and their corresponding values.

Python dictionaries are also known as associative arrays or hash tables. The general syntax of a dictionary is as follows:
PythonDictionary

myDictionary = {"Red": "#FF0000", "Green": "#00FF00", "Blue": "#0000FF"}
print("The colour code for Green is:")
print(myDictionary["Green"])

Layer Cake Challenge


In this challenge we decided to create a list called layers to store the parameters (height and ingredient) of each layer.

Check the code below and add more layers from line 42. You can use any of the ingredients from the dictionary called ingredients.

layer-cakes

Tagged with: , ,

Computing Operators – Take the Quiz!

While programming with high-level languages such as Python, you will use four different types of operators as follows:

  • The assignment operator ( = ) which is used to assign a value to a variable or a constant.
  • Arithmetic operators ( +, -, *, /, MOD, DIV, ^ ) which are used to perform mathematical calculations.
  • Comparison operators ( >, <, >=, <=, ==, != ) which are used to compare values.
  • Boolean operators ( AND, OR, NOT ) which are often used to complete more than one comparison.

Did you know?


MOD is the remainder of a division. (In Python we used the symbol % instead of MOD). For instance:

    7 MOD 3 = 1

DIV is the quotient of a division. (In Python we used the symbol // instead of DIV). For instance:

    7 DIV 3 = 2

^ means “to the power of”. (In Python we used the symbol **). For instance:

    7^2 = 49

MOD, DIV and ^ are all arithmetic operators.

Take the Quiz!

Understanding Memory Address Modes

There are many ways to locate data and instructions in primary memory and these methods are called “memory address modes”.

Memory address modes determine the method used within the program to access data either from the Cache or the RAM.
In this challenge we will focus on four different memory address modes:

  • Immediate Access
  • Direct Access
  • Indirect Access
  • Indexed Access

We will use LMC programs to see how these modes can impact on the output or flow of a program. Remember, with LMC (or any assembly languages) an instruction consists of an opcode followed by an operand.
For instance:

  • Instruction: ADD 7
  • Opcode (using a mnemonic): ADD
  • Operand: 7

Memory address modes enable us to provide either a hard coded value or a memory location for the operand.

So let’s recap on the difference between these memory address modes.

Immediate AddressingDirect AddressingIndirect AddressingIndexed Addressing

Immediate Addressing


Immediate addressing means that the data to be used is hard-coded into the instruction itself. For instance:

    ADD 7

Nothing needs to be fetched from memory. This instruction means that the value 7 will be added to the value currently stored in the accumulator.

This is the fastest method of addressing as it does not involve fetching anything from the main memory at all.
memory-address-mode-immediate

Direct Addressing


Direct Addressing is a very simple way of addressing memory – it means that the operand of an instruction refers directly to a location in memory.

For example:

    ADD 7

This instruction would not add the value 7 to the accumulator. Instead it would add the value currently stored at memory location 7 (that will be need to be fetched from the Cache/RAM).

The online LMC simulator uses this memory address mode.

This memory address mode is fairly fast (not as fast as immediate addressing though).
memory-address-mode-direct

Indirect Addressing


Indirect addressing means that the address of the data is held in an intermediate location so that the address is first ‘looked up’ and then used to locate the data itself. Fetching the value is a two step process: First the indirect address is used to locate an entry into a lookup table (called Vector Table) where the actual address of where the value can be fetched from is stored.
;
So, indirect addressing mode is a two steps process: the operand is an address towards a memory location that contains an address where the value can be fetched from.
memory-address-mode-indirect

Indexed Addressing


Indexed addressing means that the final address for the data is determined by adding an offset to a base address.

This memory address mode is ideal to store and access values stored in arrays. Arrays are often stored as a complete block in memory (A block of consecutive memory locations). The array has a base address which is the location of the first element, then an index is used that adds an offset to the base address in order to fetch the specified element within the array.
memory-address-mode-indexed

Your Challenge


Ok so, we now understand that there are different memory address modes used in Assembly languages.

For a language like LMC, when using the online simulator, we know that only direct addressing is used.

However if we had a choice between several memory address modes, we need to find a way to specify which mode is used by an instruction.

This can be done by using a specific character.
For instance, “#” could be used to represent immediate addressing, “&” could be used to represent direct addressing, “~” for indirect addressing and “[]” for indexed addressing.

In this case there is no room for confusion to understand which memory address mode is used. e.g.

    ADD #7
    ADD &7
    ADD ~7
    ADD 7[2]

In the following challenges, we will use the notation mentioned above. Your task is to predict the output of these short programs.

Note: This notation is not an official notation. It should only be used to solve the challenges listed below.

Challenge #1
LDA &8
ADD #4
OUT
HLT
6
2
10
15
16
17

Output:

Challenge #2
LDA &8
ADD &5
OUT
HLT
6
2
10
15
16
17

Output:

Challenge #3
LDA &8
ADD ~5
OUT
HLT
7
1
10
15
13
22

Output:

Challenge #4
LDA #7
ADD &6
OUT
HLT
6
2
10
15
16
17

Output:

Challenge #5
LDA ~5
ADD ~5
OUT
HLT
7
2
10
15
16
17

Output:

Challenge #6
LDA #5
ADD 7[0]
OUT
HLT
9
3
10
15
16
17

Output:

Challenge #7
LDA #5
ADD 7[2]
OUT
HLT
6
2
10
15
16
17

Output:

Challenge #8
LDA ~5
SUB #5
OUT
HLT
7
2
10
15
16
17

Output:

Tagged with: