More results...

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

Sliding Puzzle

The aim of this challenge is to use HTML, CSS and Javascript to create an interactive sliding puzzle.

Step 1: Creating 9 tiles from a single picture, using CSS


Our aim is the use a single picture file called flower.png and to create 9 CSS classes for each tile of the picture as displayed below:
sliding-puzzle-slicing

We will create our tiles using DIV tags. We will use the flower.png picture file as the background for each tile and by applying different background-position we will create the 9 different tiles as needed.

.tile1 {
width: 120px;
height: 120px;
background: url(flower.png)
background-position: left top;
}
.tile2 {
width: 120px;
height: 120px;
background: url(flower.png)
background-position: center top;
}
.tile3 {
width: 120px;
height: 120px;
background: url(flower.png)
background-position: right top;
}
.tile4 {
width: 120px;
height: 120px;
background: url(flower.png)
background-position: left center;
}
.tile5 {
width: 120px;
height: 120px;
background: url(flower.png)
background-position: center center;
}
.tile6 {
width: 120px;
height: 120px;
background: url(flower.png)
background-position: right center;
}
.tile7 {
width: 120px;
height: 120px;
background: url(flower.png)
background-position: left bottom;
}
.tile8 {
width: 120px;
height: 120px;
background: url(flower.png)
background-position: center bottom;
}
.tile9 {
width: 120px;
height: 120px;
background: white;
}

Step 2: Table Layout


We now need to position our 9 tiles using a 3×3 table layout in HTML & CSS. To do so, we will use the display property in CSS using the following three options:

  • display: table;
  • display: table-row;
  • display: table-cell;

This is an alternative to using the <TABLE>, <TR> and <TD> tags in HTML.

<div id="table" style="display: table;">
   <div id="row1" style="display: table-row;">
      <div id="cell11" class="tile1" style="display: table-cell;"></div>
      <div id="cell12" class="tile2" style="display: table-cell;"></div>
      <div id="cell13" class="tile3" style="display: table-cell;"></div>
   </div>
   <div id="row2" style="display: table-row;">
      <div id="cell21" class="tile4" style="display: table-cell;"></div>
      <div id="cell22" class="tile5" style="display: table-cell;"></div>
      <div id="cell23" class="tile6" style="display: table-cell;"></div>
   </div>
   <div id="row3" style="display: table-row;">
      <div id="cell31" class="tile7" style="display: table-cell;"></div>
      <div id="cell32" class="tile8" style="display: table-cell;"></div>
      <div id="cell33" class="tile9" style="display: table-cell;"></div>
   </div>
</div>

Step 3: Adding Interactivity and Game Logic using JavaScript


For each cell we will add an onClick attribute to call a JavaScript function to implement the game logic when the user clicks on one of the 9 cells.

We will also add a re-shuffle button to shuffle all the tiles and start a new game.

Full Code


We have implemented the HTML and CSS code above and added on onClick attribute on each tile. When a tile is clicked the javascript function clickTile() is called. This is where the code will check if the tiles can be swapped.

We have also added the “New Game” button and the JavaScript code to reshuffle all the tiles of the grid.

See the Pen Sliding Puzzle by 101 Computing (@101Computing) on CodePen.


Note that this script uses one picture. In case this picture is not displaying properly, you may have to replace its URL in the CSS code, using the following address:

Your Challenge


Amend the HTML, CSS and JavaScript code provided above to create a sliding puzzle based on a 4×4 grid (instead of 3×3).
sliding-puzzle-4x4

Tips:

  1. Start by changing the HTML code to add enough <DIV> tags to create a grid of 16 tiles.
  2. Change the CSS code to add extra classes for .tile10, .tile11, … to .tile16.
    Not that you will have to use more accurate background positioning using the following approach:
    .tile10 {
    width: 90px;
    height: 90px;
    background: url(flower.png)
    background-position: -90px -180px;
    }

    You will also need to revisit the CSS definitions for classes .tile1, .tile2, … to .tile9.
    Note that the white tile should now be tile 16.

  3. Adapt the JavaScript code to ensure it works with a 4 by 4 grid instead of a 3 by 3 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:

Guitar Chords Reader

guitar-chords-notationThe idea of this python challenge is to write a python program to help guitar players learn and practise new songs.

Our program will read all the chords used in a song and display and animate a visual representation/chart of the chord being played.

First, let’s recap what are the main chords when playing the guitar:
guitar-chords

The code appearing underneath each chord indicates the position of the fingers as described on each chart. With this code:

  • “x” means the string is not played,
  • “0” means the string played as an open string,
  • a number tells you which fret to place your finger on.

Python Code


The following python code makes use of different data structures:

  • chords is a dictionary where each chord (e.g. C) if given a “fret notation” such as “x32010”
  • songChords is a list containing all the chords used in the given song

The subroutine displayChord() takes one parameter, the name of the chord (e.g. “C”) and displays the chart for this chord. e.g.

C
x_____
||||O|
||O|||
|O||||
||||||

guitar_pick

Your Challenge #1


You can improve this challenge by adding more chords to the dictionary.

You can then add your own songs to this code and let the user decide which songs they would like to visualise.

You can use websites such as www.ultimate-guitar.com to find all he chords with their “fret notation” used in wide range of songs.

Your Challenge #2


How could you improve this code further to display the lyrics alongside the chords being played?

Text Based Animations

frame-based-animationIn this challenge we will use Python code to create text-based (ASCII) animations. Each of these animations is using a main loop that repeats the given code every 0.2 seconds and clear the screen between two iterations (frames).

Check our four animations below:

Flying RocketHello World AnimationRolling Die AnimationSpace Invader Animation

Flying Rocket Animation



Hello World Animation


This animation use string slicing to animate any piece of text!

Rolling Dice Animation


This animation uses the random library to simulate rolling a die:

Space Invader Animation


If you have ever played the game Space Invaders, you will remember the path that aliens follow, progressively coming down towards your spaceship.

Your Task


Create your own text-based animation using a similar approach. You can get started by tweaking any of the animations provided above.

Here are some ideas of text based animations you could recreate:
text-based-animations

unlock-access

Solution...

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

Splash Screen and Progress Bar

Adding a Splash Screen to your Python Projects

A splash screen usually appears for a few seconds while a game or program is launching. It can contain basic information such as the name of the game and its version number.

The following Python trinket shows how you can easily create a basic text-based splash screen to reuse in your existing projects:

Adding a Progress Bar to your Python Projects


A progress bar is a graphical control element used to visualise the progression of an extended computer operation, such as a download, file transfer or installation. Sometimes, the graphic is accompanied by a textual representation of the progress in a percent format.

progress-bar-visualisation

The following Python trinket shows how you can easily create a progress bar screen to reuse in your existing projects:


unlock-access

Solution...

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

Football Results Tracker

football-soccer-ballYou have been asked to create a program to keep track of the scores from the football Premier League.

Your program will store match results in a text file using the following format:

home team;away team;home score;away score;

For instance, after a few games your text file may contain the following information:

Chelsea;Everton;2;0;
Liverpool;Arsenal;4;0;
Crystal Palace;Swansea City;0;2;
Newcastle United;West Ham United;3;0;
Manchester United;Leicester City;2;0;
Manchester City;Everton;1;1;
Swansea City;Manchester United;0;4;
Liverpool;Crystal Palace;1;0;

To complete this challenge you will need to read more about how to read through a CSV file.

Task 1:


Your program should include:

  • An option to input and append a new line / match score to the text file. To do so the program will:
    • Ask the user to input the name of the Home team,
    • Ask the user to input the name of the Away team,
    • Ask the user to input the Home Score (number of goals scored by the home team.),
    • Ask the user to input the Away Score (number of goals scored by the away team.),
    • Append all this information at the end of the text file.

Task 2:


Create another option where the program will:

  • Ask the user to display all the scores on screen using the following format:

Home Team – Home Score:Away Score – Away Team

Task 3:


Create a third option where the program will:

  • Allow the user to enter a team name to display all the results of this team.
  • Calculate and display the number of points of a team; knowing that a team scores 3 points for a win, 1 point for a draw and 0 point for a loss.

Top-Down Modular Design


This diagram represents the main components of our system:
top-down-modular-design-football-tracker

Python Code


We have started the code for you by implementing a basic menu structure. You task is to implement the code for each one of the three options:

Solution

Task 1: View Solution
Check the following addScore() function and see how you could use it to solve task 1:

def addScore():
  print("--- Adding New Score ---")
  homeTeam = input("Type the name of the home team:")
  awayTeam = input("Type the name of the away team:")
  homeScore = input("How many goals for " + homeTeam + "?")
  awayScore = input("How many goals for " + awayTeam + "?")
  
  #Append data at the end of the text file
  file = open("results.txt","a")
  file.write("\n" + homeTeam + ";" + awayTeam + ";" + homeScore + ";" + awayScore + ";")
  file.close()
  print("Your match score has now been added.")
Task 2: View Solution
Check the following displayResults() function and see how you could use it to solve task 2:

def displayResults():
  #Output all scores stored in the text file
  print("--- All Scores ---")
  file = open("results.txt","r")
  for line in file:
    data = line.split(";")
    homeTeam = data[0]
    awayTeam = data[1]
    homeScore = data[2]
    awayScore = data[3]
    print(homeTeam + " - " + homeScore + ":" + awayScore + " - " + awayTeam)
  file.close()
Task 3.a: View Solution
Check the following displayTeamResults() function used to perform a linear search on the text file to find all the scores of a given team (task 3 part a):

def displayTeamResults():
  print("--- Team Scores ---")
  team = input("Type the name of a team:")
  
  #Display all the scores for the given team using a linear search
  file = open("results.txt","r")
  for line in file:
    data = line.split(";")
    homeTeam = data[0]
    awayTeam = data[1]
    if team == homeTeam or team==awayTeam:
      homeScore = data[2]
      awayScore = data[3]
      print(homeTeam + " - " + homeScore + ":" + awayScore + " - " + awayTeam)
  file.close() 
Task 3.b: View Solution
Check the following displayTeamPoints() function used to perform a linear search on the text file to find all the scores of a given team and calculate the total league table points for this team (task 3 part b):

def displayTeamPoints():
  print("--- Team Scores ---")
  team = input("Type the name of a team:")
  points = 0
  numberOfGamesPlayed = 0
  
  #Display all the scores for the given team using a linear search
  file = open("results.txt","r")
  for line in file:
    data = line.split(";")
    homeTeam = data[0]
    awayTeam = data[1]
    if team == homeTeam or team==awayTeam:
      numberOfGamesPlayed += 1
      homeScore = int(data[2])
      awayScore = int(data[3])
      print(homeTeam + " - " + str(homeScore) + ":" + str(awayScore) + " - " + awayTeam)
      if homeScore == awayScore: #It's a draw
        points += 1
      elif homeScore>awayScore and team == homeTeam: #It's a win at home!
        points += 3
      elif awayScore>homeScore and team == awayTeam: #It's a win against the home team!
       points += 3  
  file.close() 
  print(team + " played " + str(numberOfGamesPlayed) + " game(s).")
  print(team + " has " + str(points) + " point(s) so far.") 
unlock-access

Solution...

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

Page Rank Algorithm – Take the Quiz

Check your understanding of the page rank algorithm used by search engines such as Google to sort search results.

To find out more about this algorithm, read this blog post first:
Search Engine Indexing and Page Rank Algorithm

Quiz #1


QuestionSolution
Find the page rank score of web page B:
page-rank-a-quiz
Page Rank Score for web page B = 14
page-rank-a-solution

Quiz #2


QuestionSolution
Find the page rank score of web page B:
page-rank-b-quiz
Page Rank Score for web page B = 12
page-rank-b-solution

Quiz #3


QuestionSolution
Find the page rank score of web page A:
page-rank-c-quiz
Page Rank Score for web page A = 14
page-rank-c-solution

Search Engine Indexing and Page Rank Algorithm

Search Engines Indexing


Search engines like Google maintain huge databases called “indexes” of all the keywords and the web addresses of pages where these keywords appear.

When a web designer creates a new website they can contact the search engine to let them know they would like their web page to be scanned and added to the search engine index. They can do so by completing an online submission form. (e.g. https://www.google.com/webmasters/tools/submit-url)

Search engines also use “bots” (software robots) called web-bots or spider bots that constantly (24/7) crawl the web to scan webpages, update the index, follow hyperlinks to move from one page to the other. They can hence find new pages if these have been linked to existing pages that have already been indexed.

spider-bots

In their indexes, for each URL that has been indexed, a page rank score is also stored. This is a number that will be used to sort search results when displaying these to the end user.

Page Rank Algorithm


When a user uses a search engine (e.g. Google) the following steps take place:

  • A user submits a search query using Google’s search engine.
  • Google searches all of the pages/URLs it has indexed for relevant content. (based on keywords)
  • Google sorts the relevant pages/URLs based on PageRank scores.
  • Google displays a results page, placing those pages/URLs with the most PageRank (assumed importance) first.

So we can define the page rank score as a numerical value, calculated by a search engine for each page on the web to measure its degree of importance.

The page rank of a page is regularly updated when the spider bots of a search engine crawl the web.

Page Rank Formula?

Google does not disclose its exact PageRank formula. But it is a pretty safe bet that calculating PageRank is not easy math. The key concept of this formula though is as follows:

PageRank for a given page = Initial PageRank + (total ranking power of a page / number of outbound links of this page) + …

Where the total ranking power is calculated by adding the Page Rank score of all web pages that links to your own web page divided by the number of outbound links this page have. (“+…” means repeat this formula for each single page that links towards your page.)

Which means:

  • The more web pages link towards your web page, the higher the page rank score for your page.
  • The higher the page rank score of pages linking towards your web page, the higher the page rank score for your page.
  • If a webpage has a high page rank score but also have hundreds of outbound links it will not give you much page rank score. (e.g. This is to minimise the impact of “link sharing” to artificially boost your page rank score).

The following diagram shows how the page rank score of pages A to G is calculated. Each arrow on this diagram represents a hyperlink from one page to another page.

page-rank-algorithm

Page Rank Algorithm – Take the Quiz

Nowadays the Page Rank algorithm used by Google is based on a more complex formula that takes into consideration a wide range of other factors such as:

  • Is your website layout responsive / mobile friendly?
  • Is your website secure? (e.g. Using the https protocol)
  • Is your website regularly updated?
  • How long does it take for your web page to load on average?
  • etc.

SEO: Search Engine Optimisation


seo-search-engine-optimisation

SEO refers to a range of techniques used to increase your visibility on major search engines. When designing and editing websites, web designers and web authors try to:

  • Use keywords rich web addresses (domain names, files names for html pages and picture files).
  • Use meta tags in each html page (Header section, invisible to the user but used by search engines).
  • Use a lot of relevant keywords in the text of the web pages.
  • Increase their page rank score by getting other websites to include hyperlinks to their website:
    • Registering their website on business directories.
    • Offering link exchange/sharing with other websites.
    • Sharing links towards their website on social networks.

How many Bytes in…

binary-dataIn this challenge we will write a set of functions to calculate how many Bytes there are in a given number of kilobytes, megabytes, gigabytes, terabytes or petabytes.

First let’s investigate the link between these storage units:

how-many-bytes-in

BytesKilobytesMegabytesGigabytesTerabytesPetabytes
A Byte is a small storage unit that contains 8 bits. Here is what a Byte looks like:

01101110

A Byte can be used to store an integer between 0 and 255, or a single character (using the ASCII code).
A kilobyte (KB) contains 1024 Bytes.
1 KB = 1024 Bytes

A text file is often measured in Kilobytes as it would contain a few thousand characters.
A megabyte (MB) contains 1024 kilobytes.
1 MB = 1024 KB
= 1024 x 1024 Bytes

A digital photograph or an mp3 would typically take up a few megabytes of disk space.
A gigabyte (GB) contains 1024 megabytes.
1 GB = 1024 MB
= 1024 x 1024 KB
= 1024 x 1024 x 1024 Bytes

A high quality movie (DVD) would take up a few gigabytes. An SD card or USB key would contain a few GB of data.
A terabyte (TB) contains 1024 gigabytes.
1 TB = 1024 GB
= 1024 x 1024 MB
= 1024 x 1024 x 1024 KB
= 1024 x 1024 x 1024 x 1024 Bytes

A hard drive can contain a few Terabytes of data.
A petabyte (PB) contains 1024 terabytes.
1 PB = 1024 TB
= 1024 x 1024 GB
= 1024 x 1024 x 1024 MB
= 1024 x 1024 x 1024 x 1024 KB
= 1024 x 1024 x 1024 x 1024 x 1024 Bytes

Very large databases stored on web servers used by large websites (Google, Facebook, etc…) will contain a few Petabytes of data.

Subroutines?


By completing this challenge we will investigate how subroutines (functions/procedures) are used in Python to create sections of code that can be called/reused many times within a program. Subroutines mean that a section of code can be identified using a name (identifier). This enables us to add more instructions to the already existing functions used in Python such as print or input.

To create a new function in Python we have to declare it first using the keyword def in Python. Our first function will be called kilobytes_to_bytes() and will take one parameter: numberOfKilobytes: (integer value).

def kilobytes_to_bytes(numberOfKilobytes):

We will then add the code to calculate the number of bytes that this function should return:

def kilobytes_to_bytes(numberOfKilobytes):
      bytes = 1024 * numberOfKilobytes
      return bytes

Note how the code for the subroutine/function is indented to the right.

We will then be able to call our the kilobytes_to_bytes() function to perform any conversion. T

numberOfBytes = kilobytes_to_bytes(5)

Check the Python code below where we have implemented and used the kilobytes_to_bytes() function to convert a user input into bytes.

Your task consists of creating another set of functions as follows:

  • megabytes_to_bytes()
  • gigabytes_to_bytes()
  • terabytes_to_bytes()
  • petabytes_to_bytes()

Extension Task


hourglassCreate a new Python program that will:

  • Ask the user how old they are (age in years),
  • Convert this number in days knowing that there are 365.25 days in a year,
  • Output this number of days to the end-user.

Add more code to your program to calculate:

  • How old is the user in days,
  • How old is the user in hours,
  • How old is the user in minutes,
  • How old is the user in seconds.
unlock-access

Solution...

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

Four-in-a-row challenge!

connect4In this blog post you will use Python Code to complete this simulation of the game of connect 4. (Rules of the game)

You will first need to reverse-engineer the code provided. The code so far is used to:

  • Display the 6×7 grid using Python Turtle.
  • Randomly place tokens on the gird, taking turns (yellow and red).
  • Refresh the grid on the screen using the drawGrid() function.

The code provided uses a variable called connect4, use to store a two-dimensional array (6×7) of integer values. In Python, a 2D-array is a list of lists. Within this array, a 0 represents an empty place, a 1 represents a yellow token and a 2 represents a red token.

connect4-2d-array

Your Task:


Complete the checkIfWinner() function (from line 39) to check if after placing the token the game continues or if the player has aligned 4 tokens either in a row, column or diagonal. If so the function will return the color value of the winner (1 for Yellow, 2 for Red, 0 if no winner)

unlock-access

Solution...

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

Langton’s Ant

langton-antLangton’s Ant is a cellular automaton that models an ant moving on a grid of cells following some very basic rules.

At the start of the simulation, the ant is randomly positioned on a 2D-grid of white cells. The ant is also given a direction (either facing up, down, left or right).

The ant then moves according to the colour of the cell it is currently sitting in, with the following rules:

  1. If the cell is white, it changes to black and the ant turns right 90°.
  2. If the cell is black, it changes to white and the ant turns left 90°.
  3. The ant then moves forward to the next cell, and repeat from step 1.

These simple rules lead to complex behaviours. Three distinct modes of behaviour are apparent, when starting on a completely white grid:

  1. Simplicity: During the first few hundred moves it creates very simple patterns which are often symmetric.
  2. Chaos: After a few hundred moves, a big, irregular pattern of black and white squares appears. The ant traces a pseudo-random path until around 10,000 steps.
  3. Emergent order: Finally the ant starts building a recurrent “highway” pattern of 104 steps that repeats indefinitely.

All finite initial configurations tested eventually converge to the same repetitive pattern, suggesting that the “highway” is an attractor of Langton’s ant, but no one has been able to prove that this is true for all such initial configurations.

Source: wikipedia
LangtonsAntAnimation

Python Code (Using Python Turtle)


Below is our implementation of Langton’s Ant model using Python Turtle. Note that, on a fixed-size 2D grid, we have had to add one rule to the model:

  • On a fixed-size 2D-grid, the simulation stops when the ant reaches the edge of the grid.

Your Task


You can complete this code by adding multiple ants to this model or by starting with a random grid of black and white cells instead of an an empty grid of white cells only.

A more complex extension to this challenge is to add multiple colours to the model (not just black and white cells). See examples on this page.