More results...

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

Candy Crush – Level Generation

In this Python challenge we will complete an algorithm to generate the 9×9 grid of candies used in the game Candy Crush.

In the game of Candy Crush, 81 candies are displayed using 9 rows of 9 candies. There are 6 different candies of different shapes and colours.

To implement this game, we will be using a 2D array of integer values. Each value be stored as an integer between 1 and 6. We will also use 6 different pictures of sweets so that we can render the grid by replacing the numbers stored with their corresponding picture.

Here is our 2D array matching the above Candy Crush grid:

grid = [[1,2,3,4,6,2,5,1,3],
        [5,2,6,4,5,6,1,2,3],
        [4,1,1,3,3,6,2,4,5],
        [2,3,4,1,5,1,6,4,1],
        [5,5,3,2,1,4,3,2,2],
        [1,3,6,2,5,5,1,4,4],
        [6,1,6,3,4,6,6,3,6],
        [4,6,4,2,3,4,2,5,3],
        [4,5,1,1,3,5,2,4,6]]

Python Code so far…

Task 1: Generating a Random Grid

The code provided above will always generate the same starting grid. Your task is to add some code to randomise the grid so that each of the 81 cells of the grid contains a random integer value between 1 and 6. The following flowchart will help you implement this code.

Task 2: Identifying and Removing Blocks

In the game Candy Crush, every time a block of 3 or more adjacent candies of the same type in a row or in a column is detected, it is automatically removed from the grid. Your second task consists of detecting if the grid that was randomly generated (task 1) contains any blocks of 3 adjacent candies, and if so replace these candies.

In order to identify blocks of at least 3 adjacent candies, we can search for any candy on the grid which has two candies of the same type on either side (left and right) or above and below.

Let’s see how we can identify a block of three in a row:

Let’s see how we can identify a block of four in a column:

Once a block has been identified, we can break it by replacing either all three candies or by simply replacing the candy in the middle position. Not that in the game of Candy Crush, when a candy is removed, the candies above fall down to fill up the empty space and a new candy is generated at the top of the grid. However, we do not need to implement this at this stage, as we are only working on generating a valid start up grid that does not contain any block of 3 or more candies of the same type.

Let’s investigate the algorithm needed to detect and remove any block of three adjacent candies using the following flowchart:

Your task is to implement the above flowchart within the Python code provided above. Once done, all generated grids should not contain any blocks of 3 or more adjacent candies of the same type.

Extension Task

Now that thew grid is ready, we could ask the user to enter a row and column number of the candy they would like to remove. From there, we should implement the rules of the Candy Crush game to drop new candies from the top and see when a block has been created and should hence be removed from the grid.

unlock-access

Solution...

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

Snakes and Ladders using Python

Snakes and ladders is a board game for two or more players and is played worldwide. It originated in ancient India as “Moksha Patam”, and was brought to the UK in the 1890s. It is a race game where each player progresses through the 100 numbered cells of the board by rolling a dice. When a player lands at the bottom of the ladder, they can automatically move their token to the top of the ladder. However, when a player lands in the mouth of a snake, they slide down to the tail of the snake.
Snakes and Ladders
The first player to reach the last cell of the board (cell 100), they win. However they have to land exactly on this cell. If they reach a number higher than 100, then their token bounce back. For instance, if a player is on cell 98 and rolls a 6, they move as follows: 98 >> 99 >> 100 >> 99 >> 98 >> 97 >> 96.

Another rule is that when a player rolls a 6, they can have another turn.

We have started to implement the game using Python code. However our code is incomplete. For instance, we our game is only for one player. We dd not implement all the ladders and snakes of the board. And we did not check if the player is allowed another go (when rolling a 6).

After checking and testing the code provided below, you will need to complete 3 tasks to finalise this code:

    Add some Python code (from line 55) to make sure all ladders and snakes are catered for.
    Add some Python code to allow the player to have another go when they roll a 6.
    Add some Python code to add a second player to the game.

Python code so far…

unlock-access

Solution...

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

Pacman – Pac-dots Randomiser

In this challenge, we are looking at using a 2D Array to create the maze used in a Pacman Game.

Our 2D array will contains different numerical values to represents the corridors, walls and the pac-dots:

So in our 2D-array a corridor is represented using a 0, a wall using a 1 and a pac-dot using a 2.

maze = [[1,1,1,1,1,1,1,1,1,1,1,1,1],
        [1,0,0,0,0,0,0,0,0,0,0,0,1],
        [1,0,1,1,0,1,0,1,0,1,1,0,1],
        [1,0,1,0,0,1,0,1,0,0,1,0,1],
        [1,0,0,0,1,1,0,1,1,0,0,0,1],
        [1,0,1,0,0,0,0,0,0,0,1,0,1],
        [1,0,1,0,1,1,0,1,1,0,1,0,1],
        [1,0,1,0,0,0,0,0,0,0,1,0,1],
        [1,0,0,0,1,1,0,1,1,0,0,0,1],
        [1,0,1,0,0,1,0,1,0,0,1,0,1],
        [1,0,1,1,0,1,0,1,0,1,1,0,1],
        [1,0,0,0,0,0,0,0,0,0,0,0,1],
        [1,1,1,1,1,1,1,1,1,1,1,1,1]]


We can then easily add pac-dots in our maze using the following code:

maze[3][3] = 2
maze[3][9] = 2
maze[9][3] = 2
maze[9][9] = 2

We can then use a script to paint all the tiles of this maze on the screen. In this case we have done so using Python Turtle.

Python Code

Your Task

Your task is to add a piece of Python code to add four new pac-dots on this maze. These pac-dots should be randomly placed in the maze but not over a wall or an existing pac-dot.

Here is the flowchart for this algorithm:

unlock-access

Solution...

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

Hogwarts Sorting Hat Algorithm

In this challenge, we will implement an algorithm to help the sorting hat at Hogwarts school of witchcraft and wizardry decide which house you would more likely belong to.

When a new student join Hogwarts school, they are assigned to one of the four school houses depending on their personal qualities. The four houses are:

  • Gryffindor values bravery, loyalty and chivalry
  • Ravenclaw values curious minds, creativity and inventiveness
  • Hufflepuff values kindness, friendliness, patience
  • Slytherin values ambition and competitiveness

Now let’s look at our algorithm step by step using a flowchart that we will convert into a Python program.

Our algorithm will work by asking the end-user some yes/no questions to help define their personality and main qualities. Based on the answers provided by the end-user, the algorithm will allocate points to four score variables, one for each house.

At the end, after collecting all the end-user’s answers, the algorithm will find which house scored the most point and inform the end-user of the house that is a best match to their personality.

Step 1: Initialising the Sorting Hat Algorithm

FlowchartPython Code
Flowchart

Python Code

# Hogwarts Sorting Hat Algorithm

# Step 1: Initialise the Sorting Hat
print("~~~~~~~~~~~~~~~~~~~~~~~")
print("~                     ~")
print("~   The Sorting Hat   ~")
print("~                     ~")
print("~~~~~~~~~~~~~~~~~~~~~~~")
print("")
print("Welcome to Hogwarts school of witchcraft and wizardry!")
print("Answer the following questions to be assigned your new house.")
print("")
gryffindor = 0	
hufflepuff = 0
ravenclaw = 0
slytherin = 0

Python Code

Complete the Python code below…

Step 2: Asking Yes/NO Question

Using IF statements
Let’s ask our first question to see if the user is considering themselves as being a brave person. If so we will add one point to their score for Gryffindor as bravery is a trait of the Gryffindor house.

FlowchartPython Code
Flowchart

Python Code

# Step 2: Collect user inputs
brave = input("Are you a brave person?").lower()
if brave=="yes":
  gryffindor = gryffindor + 1
Using IF and ELSE statements
Now let’s consider another question which could lead to two outcomes depending on the user’s answer. For instance let’s ask if the user considers themselves as being patient. If the answer is “yes” we will increase their Hufflepuff score by one however, if their answer is “no” we will increase their Slytherin score by 1 as students from the Slytherin students tends to be rather impatient.

FlowchartPython Code
Flowchart

Python Code

patient = input("Would you describe yourself as being patient?").lower()
if patient=="yes":
  hufflepuff = hufflepuff + 1 
else:
  slytherin = slytherin + 1 

Step 3: Adding more questions

It’s now your turn to work out the Python code needed to add the following 8 questions:

Question 3Question 4Question 5Question 6Question 7Question 8Question 9Question 10

Step 4: Displaying the scores for each house

FlowchartPython Code
Python Code

# Step 4: Display the scores
print("Total Scores:")
print(" - Gryffindor:" + str(gryffindor))
print(" - Ravenclaw:" + str(ravenclaw))
print(" - Hufflepuff:" + str(hufflepuff))
print(" - Slytherin:" + str(slytherin))

Step 5: Selecting the house with the highest score

FlowchartPython Code
Python Code

# Step 5: Select the house with the highest score
if gryffindor>=ravenclaw and gryffindor>=hufflepuff and gryffindor>=slytherin:
   print("You belong to Gryffindor!")
elif ravenclaw>=gryffindor and ravenclaw>=hufflepuff and ravenclaw>=slytherin:
   print("You belong to Ravenclaw!")
elif hufflepuff>=ravenclaw and hufflepuff>=gryffindor and hufflepuff>=slytherin:
   print("You belong to Hufflepuff!")
elif slytherin>=ravenclaw and slytherin>=hufflepuff and slytherin>=gryffindor:
   print("You belong to Slytherin!")

Extension Task

Can you think of any additional questions you could add to your program to take more accurate decisions?

unlock-access

Solution...

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

Structure Diagram for an online-shop

An online-shop or e-commerce website is a complex web-based system that includes many functionalities. In order to design such a complex system. it is essential to think think abstractly to simplify the system we want to create and to break down the system into smaller modules.

Abstraction

An online shop is an abstraction, in other words a simplified model of a real life supermarket.

To define an abstraction, you need to consider which details your system will include and which details will be removed from your system to simplify it.

Online Shop Abstraction
Details to keep Details to remove
The ability to browse through different categories
The ability to pick an item and view its full description and price
The ability to add an item to your shopping basket
The ability to proceed to checkout
The ability to enter your card details and proceed to payment
The physical layout of the supermarket
The building aspect, colour of the walls, width of the aisles, type of floor, etc.
The physical dimensions of your trolley or shopping basket
The ability to pick up an item and manipulate it.
The ability to pay in cash
The need for the cashier to scan every item of your shopping trolley
The presence of other customers in the shop

There are many reasons why we would want to simplify our model:

  • A simplified model will be easier to code
  • You will be able to complete the project in a shorter timeframe
  • The system will not require too much processing power to run smoothly
  • The system will be adapted to the input and output devices available
  • The system will be easier to use

Once you have defined the scope of your abstraction (the details that your system will include) the next step is to break down this system into many sub-modules that can be tackled one at a time. This is what we call decomposition.

Decomposition

Decomposition consists of breaking down a complex system into smaller sub-systems / modules.

The benefits of decomposition is to:

  • Break down a complex system into smaller, more achievable sub-tasks
  • Organise your time and resources more effectively, especially when working as a team. Different team members can work on different sub-tasks.
  • Identify opportunities where you can re-use existing modules that you may already have implemented within other projects. For instance many system will require a login screen, many games will require a leaderboard. You might already have the code for these sub-modules.

Structure Diagrams

Structure diagrams are often use in computer science to help with the decomposition stage of the project. They help you break down your project into smaller sub-systems. And then for each sub-system you can break these down further into smaller modules or sub-tasks.

For instance, use the drag and drop activity below to complete the structure diagram for an online shop such as Amazon:
Structure Diagram – Online ShopOpen in New Window

Abstraction, Decomposition and Structure Diagrams

Any software developer, working on a new project will need to take time to step back and think before going straight into programming mode and writing their first line of code!

Their first step will be to consider their new system as an abstraction of reality: in other words a computer system is a simplified model of a real life situation.

Let’s consider a game of Pong for instance. A game of Pong is an abstraction of a tennis game at Wimbledon or Rolland Garros.

Abstraction

To define an abstraction, you need to consider which details your system will include and which details will be removed from your system to simplify it.

Pong Game Abstraction
Details to keep Details to remove
A bouncing ball
Two rackets/paddles that can move up and down
The net (a line across the screen)
A basic scoring system
The spectators / the stands
The referee
Light and shadow effects
Player and ball movement in 3D
Impact of gravity on the ball
Spin effects applied to the ball
The concept of games and sets
The Texture (grass/clay) and line marking of the court
Sound effects when the player runs or hits the ball
Weather conditions (incl. wind, rain, etc.)

There are many reasons why we would want to simplify our model:

  • A simplified model will be easier to code
  • You will be able to complete the project in a shorter timeframe
  • The system will not require too much processing power to run smoothly
  • The system will be adapted to the input and output devices available
  • The system will be easier to use

Once you have defined the scope of your abstraction (the details that your system will include) the next step is to break down this system into many sub-modules that can be tackled one at a time. This is what we call decomposition.

Decomposition

Decomposition consists of breaking down a complex system into smaller sub-systems / modules.

The benefits of decomposition is to:

  • Break down a complex system into smaller, more achievable sub-tasks
  • Organise your time and resources more effectively, especially when working as a team. Different team members can work on different sub-tasks.
  • Identify opportunities where you can re-use existing modules that you may already have implemented within other projects. For instance many system will require a login screen, many games will require a leaderboard. You might already have the code for these sub-modules.

Structure Diagrams

Structure diagrams are often use in computer science to help with the decomposition stage of the project. They help you break down your project into smaller sub-systems. And then for each sub-system you can break these down further into smaller modules or sub-tasks.

For instance, use the drag and drop activity below to complete the structure diagram of the game of Pong:
Structure Diagram – Pong GameOpen in New Window

OCR – H446 – Computer Science A-Level

H446 Course Overview
The OCR Computer Science A Level (H446 Specification) consists of 3 units of work as follows:
H446/01 - Computer Systems
1.1 – The characteristics of contemporary processors, input, output and storage devices
1.2 – Software and software development
1.3 – Exchanging data
1.4 – Data types, data structures and algorithms
1.5 – Legal, moral, cultural and ethical issues
H446/02 - Algorithms and programming
2.1 – Elements of computational thinking
2.2 – Problem solving and programming
2.3 – Algorithms to solve problems and standard algorithms
H446/03 - Programming Project
3.1 – Analysis of the problem
3.2 – Design of the solution
3.3 – Developing the solution
3.4 – Evaluation

Extra Revision Resources…

OCR – J277 – Computer Science GCSE

J277 Course Overview
The OCR Computer Science GCSE (J277 Specification) consists of 2 units of work as follows:
J277/01 - Computer Systems
1.1 – Systems architecture
1.2 – Memory and storage
1.3 – Computer networks, connections and protocols
1.4 – Network security
1.5 – Systems software
1.6 – Ethical, legal, cultural and environmental impacts of digital technology
J277/02 - Computational thinking, algorithms and programming
2.1 – Algorithms
2.2 – Programming fundamentals
2.3 – Producing robust programs
2.4 – Boolean logic
2.5 – Programming languages and Integrated Development Environments

Extra Revision Resources…

OCR H446/02 – 2.3 Algorithms

2.3 Algorithms - Overview / Checklist
2.3.1 Algorithms
(a) Analysis and design of algorithms for a given situation.
(b) The suitability of different algorithms for a given task and data set, in terms of execution time and space.
(c) Measures and methods to determine the efficiency of different algorithms, Big O notation (constant, linear, polynomial, exponential and logarithmic complexity).
(d) Comparison of the complexity of algorithms.
(e) Algorithms for the main data structures, (stacks, queues, trees, linked lists, depth-first (post-order) and breadth-first traversal of trees).
(f) Standard algorithms (bubble sort, insertion sort, merge sort, quick sort, Dijkstra’s shortest path algorithm, A* algorithm, binary search and linear search).

Recommended Resources

2.3.1 Algorithms
Searching & Sorting Algorithms
Bubble Sort Algorithm – Visualisation Merge Sort Algorithm – Visualisation Quick Sort Algorithm Sorting Algorithms – Visualisation Searching & Sorting Algorithms – Practice Linear Search Functions Binary Search: Guess The Number Linear vs Binary Search: Domain Name Server Challenge Bubble Sort Algorithm – Visualisation Insertion Sort Algorithm – Visualisation Sorting Algorithms – Python Code Shuffling Algorithm (Python Challenge)

Algorithms & Data Structures
– Binary Trees
Breadth-First Traversal of a Binary Tree Binary Search Tree Implementation Prime Factor Tree Algorithm Morse Code using a Binary Tree Huffman Coding Algorithm – Graphs
Air-Flight Route Planner The Social Network Food Chain and Food Web London Underground Journey Planner

– Hash Tables
Airport Lookup Check Chemical Elements Quiz

– 2D and 3D Arrays
Cinema Booking Challenge Laser Maze Game My Weekly Timetable Four in a row Challenge Noughts & Crosses Challenge Battleship Challenge Drone Display Space Invaders 2D/3D Pixel Art

– Stack & Queues
Stacks and Queues using Python The Ice Cream Stack Bracket Validator (using a Stack) Reverse Polish Notation (using a Stack)


Big O Notation

Big O Notation

The question we will try to answer in this blog post is as follows: How can we measure the effectiveness/performance of an algorithm? First let’s consider this quote from Bill Gates (Founder of Microsoft): “Measuring programming progress by lines of … Continue reading


Big O Notation – Quiz

Before completing this quiz, we invite you to revisit the main Big O Notations used to describe the time complexity and space complexity of an algorithm.. The main Big O Notations this quiz will focus on are: Take the Quiz! … Continue reading


Short Path Algorithms

Dijkstra’s Shortest Path Algorithm

Dijkstra’s Shortest Path Algorithm is an algorithm used to find the shortest path between two nodes of a weighted graph. Before investigating this algorithm make sure you are familiar with the terminology used when describing Graphs in Computer Science. Let’s … Continue reading


A* Search Algorithm

The A* Search algorithm (pronounced “A star”) is an alternative to the Dijkstra’s Shortest Path algorithm. It is used to find the shortest path between two nodes of a weighted graph. The A* Search algorithm performs better than the Dijkstra’s … Continue reading


Short Path Algorithm Practice

Before completing this task, you will need to familiarise yourself with the following 2 algorithms used to find the shortest path between two nodes of a weighted graph: Dijkstra’s Short Path Algorithm A* Algorithm Dijkstra’s Short Path Algorithm For each … Continue reading


Air Flight Route Planner London Underground Journey Planner The Social Network

OCR H446/01 – 2.2 Problem solving and programming

2.2 Problem solving and programming - Overview / Checklist
2.2.1 Programming techniques
(a) Programming constructs: sequence, iteration, branching.
(b) Recursion, how it can be used and compares to an iterative approach.
(c) Global and local variables.
(d) Modularity, functions and procedures, parameter passing by value and by reference.
(e) Use of an IDE to develop/debug a program.
(f) Use of object oriented techniques.
2.2.2 Computational methods
(a) Features that make a problem solvable by computational methods.
(b) Problem recognition.
(c) Problem decomposition.
(d) Use of divide and conquer.
(e) Use of abstraction.
(f) Learners should apply their knowledge of:

    backtracking
    data mining
    heuristics
    performance modelling
    pipelining
    visualisation to solve problems.

Recommended Resources