More results...

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

Space Invaders – 3D Pixel Art

space-invaders-pixel-artIn this blog post we will use Glowscript to create a 3D animation of a space invader.

2D Graphics used in retro arcade games consist of pixels. A 2D graphic can be described as a grid of pixels of different colours.
space-invaders-pixels

In programming we can use a 2D array data structure to represent a graphic. In Python, 2D arrays are implemented using a list of lists.

In our code (see below) we have declared a 2D array called pixels to store the value of each pixel used to represent one of the space invaders.

pixels   =   [[0,0,1,0,0,0,0,0,1,0,0]]
pixels.append([0,0,0,1,0,0,0,1,0,0,0])
pixels.append([0,0,1,1,1,1,1,1,1,0,0])
pixels.append([0,1,1,0,1,1,1,0,1,1,0])
pixels.append([1,1,1,1,1,1,1,1,1,1,1])
pixels.append([1,0,1,1,1,1,1,1,1,0,1])
pixels.append([1,0,1,0,0,0,0,0,1,0,1])
pixels.append([0,0,0,1,1,0,1,1,0,0,0])

Using a 2 nested loops we then looped through each row and each column of this array to retrieve the value of each pixel in order to create the cubes needed to create a 3D model of a space invader.

We then create a compound object to join these cubes together in a single object. Finally using an infinite while loop we animate/rotate our invader around itself.

Here is our 3D animation: (Use Google Chrome to preview this animation)


Right Click on the animation to change the view point (rotate camera angle).

Find out more…


To learn more about all the instructions you can use in GlowScript/VPython, use this on-line documentation.

Your task:


space-invaders
Create and animate all the different Space Invaders.

From 2D to 3D: Crossy Road Chicken


This technique of creating 2D graphics can also be used for 3D graphics. In this case a 3D array is used to store the pixels alongside 3 dimensions: x, y and z.

Let’s look at the code below used to create a 3D model of the chicken from the Crossy Road game:
crossy-road-chicken

Check in the code below to see how a list of lists of lists is used in Python to create a 3D array.

Also look at how, using 3 nested loops we can iterate through each “pixel” of the 3D array.

We have also used a 1D array called palette to store all the colours to be used in our 3D model.

Can you think of other games that might use 3D arrays?
mine-craft-block

Tagged with: , , , , ,

London Underground – Journey Planner

london-underground-signThe aim of this Python challenge is to investigate how graphs can be used in Computer Science and investigate the key algorithms used when manipulating graphs in Python such as an algorithm to find the shortest path between two nodes of a graph.

For this challenge we will focus on a graph used to represent the London Underground Map (Zone 1).
tubemap

Access London Tube Map

Most programming languages do provide direct support for graphs as a data type. Python for instance does not have a graph data structure. However, graphs can be built out of lists and dictionaries. For instance, here is a graph to represent some of the connections between a selection of London tube stations:

tubemap = {"Aldgate" : ["Liverpool Street","Tower Hill"],
"Aldgate East" : ["Tower Hill","Liverpool Street"],
"Angel" : ["King's Cross St. Pancras","Old Street"],
"Baker Street" : ["Marylebone","Regent's Park","Edgware Road (C)","Great Portland Street","Bond Street"],
"Bank" : ["Liverpool Street","St. Paul's","London Bridge","Moorgate","Waterloo"],
"Barbican" : ["Farringdon","Moorgate"]
#...
}

This graph is a dictionary where the keys are the nodes of the graph. For each key, the corresponding value is a list containing the nodes that are connected by a direct arc from this node.

The full dictionary with all the stations for London Underground can be found in the Python trinkets below.

Find Path Algorithm


Our first algorithm is used to determine if there is a path between two nodes of a graph, and if so it returns one path that can be used to connect both nodes. A path is a list of nodes which are connected to each others.

This algorithm uses a backtracking approach to explore different paths. It does stop as soon as a path has been found. Note that the path that will be found first may not be the shortest path though.

def find_path(graph, start, end, path=[]):
  path = path + [start]
  if start == end:
    return path
  if not start in graph:
    return None
  for node in graph[start]:
    if node not in path:
      newpath = find_path(graph, node, end, path)
      if newpath: return newpath
  return None

Find All Paths Algorithm


This second algorithm is very similar to the find_path() algorithm. The difference is that this time the backtracking algorithm will explore and return all the possible paths between the two nodes as a list of paths. (List of lists).

def find_all_paths(graph, start, end, path=[]):
  path = path + [start]
  if start == end:
    return [path]
  if not start in graph:
    return []
  paths = []
  for node in graph[start]:
    if node not in path:
      newpaths = find_all_paths(graph, node, end, path)
      for newpath in newpaths:
        paths.append(newpath)
  return paths

Find Shortest Path Algorithm


Our final algorithm is probably the most useful algorithm as it will identify amongst all the paths that have been found, which one is the shortest path (The path that has the smallest number of nodes).

To make this algorithm more effective we also have a stopping condition to stop exploring a path that would be longer than the shortest path found so far.

def find_shortest_path(graph, start, end, shortestLength=-1, path=[]):
  path = path + [start]
  if start == end:
    return path
  if not start in graph:
    return None
  shortest = None
  for node in graph[start]:
    if node not in path:
      if shortestLength==-1 or len(path)<(shortestLength-1):
        newpath = find_shortest_path(graph, node, end, shortestLength, path)
        if newpath:
          if not shortest or len(newpath) < len(shortest):
            shortest = newpath
            shortestLength = len(newpath)  
  return shortest

Python Code


We will use the find_shortest_path() algorithm to find the shortest path between two tube stations.

Zone 1 OnlyFull Map (Zone 1 to 10)

With a more complex graph, this algorithm will take longer to find the shortest path.

Extension


A backtracking algorithm can sometimes take a very long time to explore all possible paths. This is due to the complexity of the graph (e.g. tube map) which contains many nodes and connections between nodes, hence the high number of potential routes to explore using a backtracking algorithm.

More advanced algorithms can be implemented to overcome this issue. You may want to explore the following algorithms:

Tagged with: , ,

Insertion Sort Algorithm

Insertion-sort-1-9The Insertion sort algorithm is one of the key sorting algorithms used in Computer Science.

To start with, the algorithm considers the first value of a list as a sorted sub-list (of one value to start with). This iterative algorithm then checks each value in the remaining list of values one by one. It inserts the value into the sorted sub-list of the data set in the correct position, moving higher ranked elements up as necessary.

This algorithm is an O(n2) algorithm which is relatively efficient for small lists and mostly sorted lists, and is often used as part of more sophisticated algorithms.

Python Implementation of an Insertion Sort algorithm


The Python code belows let you visualise how a Insertion sort algorithm with a small set of values (from 1 to 9). The list of values is shuffled every time you run this code.

Tagged with: , ,

Bubble Sort Algorithm

Bubble-sort-1-9The Bubble sort algorithm is one of the key sorting algorithms used in Computer Science. It is a fairly simple algorithm to implement and is particularly useful when you need to find the top x values of a list.

The algorithm starts at the beginning of the data set. It compares the first two value, and if the first is greater than the second, it swaps them. It continues doing this for each pair of adjacent values to the end of the data set. It then starts again with the first two elements, repeating until no swaps have occurred on the last pass.

This algorithm’s average and worst-case performance is O(n2), so it is rarely used to sort large, un-ordered data sets. Bubble sort can be used to sort a small number of items and is a lot more effective on data sets where the values are already nearly sorted.

Python Implementation of a Bubble Sort algorithm


The Python code belows let you visualise how a Bubble sort algorithm with a small set of values (from 1 to 9). The list of values is shuffled every time you run this code.

Tagged with: , ,

Backtracking Maze – Path Finder

backtracking-maze-algorithmThe purpose of this Python challenge is to demonstrate the use of a backtracking algorithm to find the exit path of Maze.

Backtracking Algorithm


A backtracking algorithm is a recursive algorithm that attempts to solve a given problem by testing all possible paths towards a solution until a solution is found. Each time a path is tested, if a solution is not found, the algorithm backtracks to test another possible path and so on till a solution is found or all paths have been tested.

The typical scenario where a backtracking algorithm is when you try to find your way out in a maze. Every time you reach a dead-end, you backtrack to try another path until you find the exit or all path have been explored.

Backtracking algorithms can be used for other types of problems such as solving a Magic Square Puzzle or a Sudoku grid.

Backtracking algorithms rely on the use of a recursive function. A recursive function is a function that calls itself until a condition is met.

Python Code

unlock-access

Solution...

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

Backtracking Algorithm – Sudoku Solver

The purpose of this Python challenge is to demonstrate the use of a backtracking algorithm to solve a Sudoku puzzle.

Did You Know?


The objective of a Sudoku puzzle is to fill a 9×9 grid with digits so that each column, each row, and each of the nine 3×3 subgrids that compose the grid (also called “boxes”) contains all of the digits from 1 to 9. A Sudoku puzzle is a partially completed grid, which for a well-posed puzzle has a single solution.

sudoku-grid

Backtracking Algorithm


A backtracking algorithm is a recursive algorithm that attempts to solve a given problem by testing all possible paths towards a solution until a solution is found. Each time a path is tested, if a solution is not found, the algorithm backtracks to test another possible path and so on till a solution is found or all paths have been tested.

The typical scenario where a backtracking algorithm is when you try to find your way out in a maze. Every time you reach a dead-end, you backtrack to try another path untill you find the exit or all path have been explored.

Backtracking algorithms can be used for other types of problems such as solving a Magic Square Puzzle or a Sudoku grid.

Backtracking algorithms rely on the use of a recursive function. A recursive function is a function that calls itself until a condition is met.

Note that there are other approaches that could be used to solve a Sudoku puzzle. The Backtracking approach may not always be the most effective but is used in this challenge to demonstrate how a backtracking algorithm behaves and how it can be implemented using Python.

Python Code


Extra Challenge:


An extra challenge would be to design an algorithm used to create a Sudoku Grid. The generated Sudoku grid should have enough clues (numbers in cells) to be solvable resulting in a unique solution.
unlock-access

Solution...

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

Backtracking Algorithm – Magic Square Solver

magic-squareThe purpose of this Python challenge is to demonstrate the use of a backtracking algorithm to solve a Magic Square puzzle.

Did You Know?


A 3×3 magic square is an arrangement of the numbers from 1 to 9 in a 3 by 3 grid, with each number occurring exactly once, and such that the sum of the entries of any row, any column, or any main diagonal is the same.

magic-square-3x3

Backtracking Algorithm


A backtracking algorithm is a recursive algorithm that attempts to solve a given problem by testing all possible paths towards a solution until a solution is found. Each time a path is tested, if a solution is not found, the algorithm backtracks to test another possible path and so on till a solution is found or all paths have been tested.

The typical scenario where a backtracking algorithm is when you try to find your way out in a maze. Every time you reach a dead-end, you backtrack to try another path until you find the exit or all paths have been explored.

Backtracking algorithms can be used for other types of problems such as solving a Magic Square Puzzle or a Sudoku grid.

Backtracking algorithms rely on the use of a recursive function. A recursive function is a function that calls itself until a condition is met.

Note that there are other approaches that could be used to solve the magic square puzzle. The Backtracking approach may not be the most effective but is used in this challenge to demonstrate how a backtracking algorithm behaves and how it can be implemented using Python.

Python Code


Extension Task


Adapt this challenge to implement a backtracking algorithm used to solve a Sudoku grid!
sudoku-grid
unlock-access

Solution...

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

Food Chain Game Using Python

food-chain-frog

Learning Objectives?


In this set of Python challenges we will investigate the use of two data structures used in programming to represent data:

  • We will use an array/list to represent a food chain.
  • We will use a graph to represent a food web.

Did you know?


A food chain shows the different organisms that live in a habitat, and what eats what.

A predator is an animal that eats other animals, and the prey is the animal that gets eaten by the predator.

Here is an example of food chain:

Grass > grasshopper > frog > snake > eagle

In the food chain above:

  • the frog is a predator and the grasshopper is its prey.
  • the snake is a predator and the frog is its prey.

Python Challenge

For this challenge you will write a Python program that stores the organisms a food chain using a list.

food-chain

You program will randomly pick two organisms from the food chain. One for the player, one for the computer.

The program will find out the positions of these organisms in the given food chain. (This is known as the trophic level of an organism which is the position it holds in a food chain).

The program will compare both positions, the player with the highest position in the food chain will win the game.

We have started the code for you. Complete this code to:

  • Randomly select the “computer organism” from the list.
  • Make sure that both selected organisms are different.
  • Compare the positions of both organisms to decide who, between the computer and the player, wins the round.

Food Web


When all the food chains in a habitat are joined up together they form a food web. Here is an example of a food web:

food-web

Although it looks complex, it is just several food chains joined together. Here are some of the food chains in this food web:

grass > insect > vole > hawk

grass > insect > frog > fox

grass > insect > vole > fox

To represent a food web we will use a different data structure called a graph.

Most programming languages do provide direct support for graphs as a data type. Python for instance does not have a graph data structure. However, graphs can be built out of lists and dictionaries. For instance, here is a graph to represent the above food web:

foodWeb = {'insect': ['grass'],
           'rabbit': ['grass'],
           'slug': ['grass'],
           'thrush': ['slug','insect'],
           'vole': ['insect'],
           'frog': ['insect'],
           'hawk': ['frog','vole','thrush'],
           'fox': ['rabbit','frog','vole']}

This graph is a dictionary where the keys are the nodes of the graph. For each key, the corresponding value is a list containing the nodes that are connected by a direct arc from this node. Note that this is a directed graph as each link/arc has a direction.

Python Code

Compete the code below to:

  • Find out if the computer organism and the player organism are linked (Direct link or indirect link).
  • If a link/path is detected, decide who, between the computer and the player, wins the game.

Tip: Use the find_path() algorithm described on https://www.python.org/doc/essays/graphs/


unlock-access

Solution...

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

Lighthouse Animation Challenge

lighthouseThe purpose of this challenge is to use a Python program to demonstrate how frame-based animations can be implemented.

For this challenge we are using the Processing.py library.

The code below will run the setup() procedure once, when the program starts. Then the animateLighthouse() procedure will be called 20 times per second (based on the frame rate), indefinitely.

This code makes use of two transformations:

  • A translation: 2D translations are often used to re-position or animate objects on screen (gliding effect)
  • A rotation: in this case, a rotation is applied to animate the light beam. The angle of rotation increments by 0.5 degrees between each frame.

lighthouse-translation-rotation

Python Code


Your Challenge


Complete this code to animate the boat:

  • The boat should translate/glide horizontally from left to right.
  • Once the boat fully disappears to the right of the screen, it should reappear to the left.

lighthouse-translation

unlock-access

Solution...

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

Python Turtle – WordArt Challenge

In this challenge we will use Python Turtle to draw text on screen and customise the appearance of our text.

To do so we have created our own font as a Python dictionary. Each letter of the alphabet is represented as a set of (x,y) coordinates as follows:
character-A-dot-to-dot
We will then use these coordinates to trace a line using Python Turtle using a “dot-to-dot” approach.

WordArt #1: Dot-To-Dot Text


WordArt #2: Oblique Text


WordArt #3: Circular Text


Your Challenge


Customise the code above to create your own WordArt effects such as:

  • Growing Text: Write text where each letter is bigger than the previous one.
  • Backwards Text: Write text where the text is written backwards.
  • Vertical Text: Write text where the text is written vertically.
  • Wrapped Text: Write text where long text is written across multiple lines.
  • Reflective Text: Write text with its own reflection underneath.
Tagged with: ,