More results...

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

12-hour clock

clock

Did You Know?


The 12-hour clock is a time convention in which the 24 hours of the day are divided into two periods: a.m. (from the Latin ante meridiem, meaning “before midday”) and p.m. (post meridiem, “after midday”). Each period consists of 12 hours numbered: 12 (acting as zero), 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, and 11. The 24 hour/day cycle starts at 12 midnight (often indicated as 12 a.m.), runs through 12 noon (often indicated as 12 p.m.), and continues to the midnight at the end of the day.

24-hour to 12-hour clock convertor


Your challenge consists of writing a computer program that asks the end-user to enter a time in the 24-hour format (e.g. 18:36). The program will convert this time in the 12-hour format (e.g. 6:36 PM).

Solution


Extension


Amend this code to validate the user entry and make sure they enter a time between 00:00 and 23:59 and to display an error message if not.
unlock-access

Solution...

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

Minecraft Trampoline

trampolineIn this post we will use Python 2 and Minecraft to create a virtual trampoline for Minecraft. We will first build the trampoline using Minecraft blocks (in Python). Then we will write a routine to make the main player bounce up and down on the trampoline.

Step 1: Let’s connect to the Minecraft World via our Python script


For this challenge we are using a Raspberry Pi with Minecraft and Python 2 pre-installed.

from mcpi import minecraft, block
import time 

mc = minecraft.Minecraft.create()

msg = "Hello Minecraft World from 101 Computing"
mc.postToChat(msg)

Now try this, just to make sure it works! You should see a message appearing on your minecraft screen. If you are not sure how to do this you may want to check our first minecraft + python tutorial.

(x,y,z) coordinates?

minecraft-xyz-coordinatesBefore getting started you need to understand how the (x,y,z) coordinates are used to retrieve the position of the player in the minecraft world or to add blocks at the right position. As you can see on the picture to the left, it is slightly confusing as the vertical axis is not the z axis but the y axis.

Step 2: Building the trampoline


Our trampoline will be quite basic. It will consists of 4 posts (made of stone blocks) and a 6 by 6 bouncing area made of wood (ouch!).

Before we can build this trampoline we are going to find the position of the player so we can build this trampoline next to our main player (in fact just 5 blocks away on the x axis)

So let’s see how this all works:

from mcpi import minecraft, block
import time 

mc = minecraft.Minecraft.create()
msg = "Hello Minecraft World from 101 Computing"
mc.postToChat(msg)

def buildTrampoline(x , y, z, width):
    time.sleep(1)
    mc.setBlock(x, y, z, block.STONE)
    mc.setBlock(x, y, z+width, block.STONE)
    mc.setBlock(x + width, y, pos.z, block.STONE)
    mc.setBlock(x+width, y, z+width, block.STONE)
    mc.setBlocks(x, y+1, z, x + width, y+1, z + width, block.WOOD)


#Let's get the player's coordinates
pos=mc.player.getPos()

#We will build the trampoline 5 blocks away from the player
trampoline_xPos = pos.x + 5
trampoline_yPos = pos.y
trampoline_zPos = pos.z
trampoline_width = 6

buildTrampoline(trampoline_xPos,trampoline_yPos,trampoline_zPos,trampoline_width)

trampoline2

Step 3: Make it Bounce!


Let’s first create a new routine to make the player bounce up in the sky using a for loop.

def bounce():
    x, y, z = mc.player.getPos()
    for i in range(1,21):
        time.sleep(0.01)
        mc.player.setPos(x,y+i,z)

We don’t have to worry about getting the player to go down as it will do so automatically (there is gravity in the minecraft world!).

Then we will use an infinite loop to constantly check on the player’s position. If the player is on the trampoline then we will call our bounce() procedure.

while True:
    x, y, z = mc.player.getPos()
    if (x>=trampoline_xPos and x<=(trampoline_xPos+trampoline_width)) and (z>=trampoline_zPos and z<=(trampoline_zPos+trampoline_width)):
          block_beneath = mc.getBlock(x, y-1, z)
          if block_beneath==17: #17 is wood
            bounce()

Complete script:

from mcpi import minecraft, block
import time

def buildTrampoline(x , y, z, width):
    time.sleep(1)
    mc.setBlock(x, y, z, block.STONE)
    mc.setBlock(x, y, z+width, block.STONE)
    mc.setBlock(x + width, y, pos.z, block.STONE)
    mc.setBlock(x+width, y, z+width, block.STONE)
    mc.setBlocks(x, y+1, z, x + width, y+1, z + width, block.WOOD)

def bounce():
    x, y, z = mc.player.getPos()
    for i in range(1,21):
        time.sleep(0.01)
        mc.player.setPos(x,y+i,z)

mc = minecraft.Minecraft.create()

msg = "Hello Minecraft World from 101 Computing"
mc.postToChat(msg)

#Let's get the player's coordinates
pos=mc.player.getPos()

#We will build the trampoline 5 blocks away from the player
trampoline_xPos = pos.x + 5
trampoline_yPos = pos.y
trampoline_zPos = pos.z
trampoline_width = 6

buildTrampoline(trampoline_xPos,trampoline_yPos,trampoline_zPos,trampoline_width)

mc.postToChat("Climb on the trampoline next to you to start bouncing.")

while True:
    x, y, z = mc.player.getPos()
    if (x>=trampoline_xPos and x<=(trampoline_xPos+trampoline_width)) and (z>=trampoline_zPos and z<=(trampoline_zPos+trampoline_width)):
          block_beneath = mc.getBlock(x, y-1, z)
          if block_beneath==17: #17 is wood
            bounce()

Your Challenge


Use the above script to make your trampoline.

Once you have it working adapt this script to create an escalator. The escalator should be built using a Python script. As the soon as the main player goes on the escalator they should automatically move up the stairs, one step at a time.

Tagged with: , ,

Avatar Generator

avatars4In this challenge we will use Python Turtle to create avatars. (An avatar is an icon representing a particular person in a computer game, Internet forum, etc.)

Try the code below. This code is using a few computing concepts such as:

  • A list to store the different colour codes,
  • (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:

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] ?

In our avatar generator code we use three lists to store all the different colours for the skin, the hair and the eyes:

skinColors = ["#FCD09D","#FAC47A", "#DBA965", "#CC9D5E","#A3855B","#806645","#665135"]
eyeColors = ["#489CF0","#15A315", "#8C3303"]
hairColors = ["#000000","#8C3303","#F5D907","#580000","#E31E00","#636363","#FFFFFF"]

By using the random library we can access a random value of a list.

import random #Only use this instruction once at the very beginning of your code

hairColors = ["#000000","#8C3303","#F5D907","#580000","#E31E00","#636363","#FFFFFF"]
hairColorIndex = random.randint(0,6)

print(hairColors[hairColorIndex])



(x,y) coordinates using turtle


quadrant-coordinates
On this trinket widget the turtle screen is 400 pixels wide. So:

  • the top left corner coordinates are (-200,200)
  • the top right corner coordinates are (200,200)
  • the bottom left corner coordinates are (-200,-200)
  • the bottom right corner coordinates are (200,-200)
  • the centre of the screen coordinates are (0,0)



Look at the canvas below to understand how (x,y) coordinates work:


Avatar Generator




Your Challenge


Start customising the above script to add a random colour for the background. You can select colour codes using www.colorpicker.com.

Then add a T-shirt to your avatar, using random colours too.

Customise your avatar further by adding a beauty spot, different colours of lipstick, a mustache, a beard etc.

Tagged with: , , ,

Le Tour de France

cyclist

Learning Objectives


By completing this challenge we are learning how to open and extract data from a text file, reading the file line by line. We will then use our program to make some calculations such as calculating the total distance of the race over 21 stages.

The Race


Le Tour de France is a cycling race that takes place over 21 stages (23 days in total, including two rest days). The text file below contains a list of the 21 stages as follows (based on the 2015 route):

Stage Number;Distance in km;Starting from;Arriving at
TextFileletour.txt

The Code


Your Challenge


Adapt this code to answer the following questions:

  • What stage is the longest stage (in distance)?
  • What stage is the shortest stage (in distance)?
  • What is the average distance per stage?
  • What is the total distance of the race in miles?
  • Between stage 16 and stage 17, once in Gap, cyclists have a rest day. How many kilometres have they been cycling for? How many kilometres are left till the end of the race?
unlock-access

Solution...

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

Rainbow Challenge

rainbowIn this challenge we are going to use our coding skills to create some nice colour patterns. We will first look at the code given to create a rainbow effect to understand how it works. We will then adapt this script to create three other colour patterns.

Rainbow Effect


Try the code above. This code is using a few computing concetps such as:

  • A list to store the different colour codes,
  • Iteration using a for loop to loop through each colour in the list,
  • (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:

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)

In our rainbow code we use a list to store all the different colours of the rainbow as follows:

rainbowColors = ["#FF0000","#FFA600","#FFFF00", "#62FF00", "#1E56FC","#4800FF","#CC00FF","#69C5FF"]

(x,y) coordinates using turtle


quadrant-coordinates
On this trinket widget the turtle screen is 400 pixels wide. So:

  • the top left corner coordinates are (-200,200)
  • the top right corner coordinates are (200,200)
  • the bottom left corner coordinates are (-200,-200)
  • the bottom right corner coordinates are (200,-200)
  • the centre of the screen coordinates are (0,0)

Look at the canvas below to understand how (x,y) coordinates work:

Colour Pattern #1


Use and adapt the script above to recreate this colour pattern. The colour codes are given to you in the colour palette below.
color-pattern-1

Colour Hex RGB
#0099e6 (0,153,230)
#43e0ef (67,224,239)
#c3e970 (195,233,112)
#ffa9c2 (255,169,194)
#d297d9 (210,151,217)

Colour Pattern #2


Use and adapt your script to recreate this colour pattern. The colour codes are given to you in the colour palette below.
color-pattern-2

Colour Hex RGB
#ff0000 (255,0,0)
#d61a1a (214,26,26)
#a50000 (165,0,0)
#ddb200 (221,178,0)
#e7e497 (231,228,151)

Colour Pattern #3: Using a Random pattern


Use and adapt your script to recreate this colour pattern. The colour codes are given to you in the colour palette below.

However there is no colour pattern here. Each circle uses a random colour from the colour palette.

Check the code below used to randomly pick a colour from:

import random #Only use this statement once, at the top of your Python program.

rainbowColors = ["#FF0000","#FFA600","#FFFF00", "#62FF00", "#1E56FC","#4800FF","#CC00FF","#69C5FF"]
randomColor = random.choice(rainbowColors)

color-pattern-3

Colour Hex RGB
#ECECEC (236,236,236)
#2198d5 (33,152,213)
#0f8975 (15,137,117)
#0f6089 (15,96,137)
#000000 (0,0,0)

Tagged with: , , ,

Turtle Maze Challenge

maze
Your challenge is to guide the turtle through the maze. To do so you will need to use the following instructions:

  • myPen.forward(100) to move forward by 100 pixels,
  • myPen.right(90) to turn right by 90 degrees,
  • myPen.left(90) to turn left by 90 degrees.

Complete the code


Using a for loop


Note that, as you progress through the maze you may also decide to use a for loop to repeat a set of instructions several times.
For instance:

for i in range(0,3):
   myPen.forward(100)
   myPen.left(90)

Video Tutorial:



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: How to control your sprite?

arrowKeysThis tutorial is the third tutorial in a series of five Pygame tutorials:

For this third tutorial we will complete the code from the previous tutorial:

Remember the aim is to create a car racing game. In the first tutorial we looked at how to create the background for our game (The road). In the second tutorial we added our first sprite called playerCar which is an instance of the Car class.

In this third tutorial we will add methods to our Car class to move the car to the left, right, forward, and backward.

We will then add event handlers to the main program loop to respond to keystroke events. When the player uses the arrow keys on the keyboard we will call our methods to move the playerCar on the screen.

Step 1: Adding Methods to the Car class.


Open the file car.py and add the lines 26 to 30 as follows:

import pygame
WHITE = (255, 255, 255)

class Car(pygame.sprite.Sprite):
    #This class represents a car. It derives from the "Sprite" class in Pygame.
    
    def __init__(self, color, width, height):
        # Call the parent class (Sprite) constructor
        super().__init__()
        
        # Pass in the color of the car, and its x and y position, width and height.
        # Set the background color and set it to be transparent
        self.image = pygame.Surface([width, height])
        self.image.fill(WHITE)
        self.image.set_colorkey(WHITE)
 
        # Draw the car (a rectangle!)
        pygame.draw.rect(self.image, color, [0, 0, width, height])
        
        # Instead we could load a proper pciture of a car...
        # self.image = pygame.image.load("car.png").convert_alpha()
 
        # Fetch the rectangle object that has the dimensions of the image.
        self.rect = self.image.get_rect()

    def moveRight(self, pixels):
        self.rect.x += pixels

    def moveLeft(self, pixels):
        self.rect.x -= pixels

As you can see we have added two procedures to our class. In OOP (Object Orientated Programming) we call these procedures: methods. A method is a procedure or function associated to a class. Let’s look at the moveRight() method.

def moveRight(self, pixels):
   self.rect.x += pixels

The moveRight() method takes two arguments. The first one is implicit and is called self. It refers to the current object. The second one is called pixels and refers to the number of pixels we will use to move the car.

The body of our method only contains one line: self.rect.x += pixels
It is basically adding pixels to the current x coordinate of the object.

Step 2: Responding to keystroke events


arrowKeysLet’s look at the code for our main program. You may remember that in the first tutorial we talked about the main program loop. The first section of this loop is to respond to events such as user interactions when the user uses the mouse or the keyboard.

So let’s add two event handlers, one moving left and one for moving right using the left and right arrow keys of the keyboard. Each event handler will call the relevant method from the Car class. Check the code below with the new event handlers from line 37 to 45.

import pygame, random
#Let's import the Car Class
from car import Car
pygame.init()

GREEN = (20, 255, 140)
GREY = (210, 210 ,210)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
PURPLE = (255, 0, 255)
        
SCREENWIDTH=400
SCREENHEIGHT=500

size = (SCREENWIDTH, SCREENHEIGHT)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Car Racing")

#This will be a list that will contain all the sprites we intend to use in our game.
all_sprites_list = pygame.sprite.Group()

playerCar = Car(RED, 20, 30)
playerCar.rect.x = 200
playerCar.rect.y = 300

# Add the car to the list of objects
all_sprites_list.add(playerCar)

#Allowing the user to close the window...
carryOn = True
clock=pygame.time.Clock()

while carryOn:
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            carryOn=False
        elif event.type==pygame.KEYDOWN:
            if event.key==pygame.K_x: #Pressing the x Key will quit the game
               carryOn=False

    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT]:
        playerCar.moveLeft(5)
    if keys[pygame.K_RIGHT]:
        playerCar.moveRight(5)
        
    #Game Logic
    all_sprites_list.update()

    #Drawing on Screen
    screen.fill(GREEN)
    #Draw The Road
    pygame.draw.rect(screen, GREY, [40,0, 200,300])
    #Draw Line painting on the road
    pygame.draw.line(screen, WHITE, [140,0],[140,300],5)
        
    #Now let's draw all the sprites in one go. (For now we only have 1 sprite!)
    all_sprites_list.draw(screen)

    #Refresh Screen
    pygame.display.flip()

    #Number of frames per secong e.g. 60
    clock.tick(60)

pygame.quit() 

All done… Save your files and try your code. You should now be able to control your car using the arrow keys!

Tagged with: , , ,

Captain Redbeard’s Treasure

pirateWe need your coding skills to locate the treasure of Captain Redbeard. The legend holds that Redbeard was a great pirate who sailed the Caribbean Sea, fiercely attacking any vessels from the British Navy he would encounter.

Redbeard was killed in battle with the British Navy in 1743. Legend holds that he received 20 stab wounds and five gunshot wounds before finally succumbing.

But the legend also tells us that he buried his treasure before his final battle on Paradise Island, in the Caribbean waters. On his ship the British Navy found a treasure map with a set of instructions that they have not been able to decode yet.

Will you be able to help them locate Captain Redbeard treasure?

Map of Paradise Island:


treasure-map

Captain Redbeard’s Instructions:

START
GOTO E7
POINT North

FOR step FROM 1 to 4
    MOVE FORWARD BY 1
END FOR

POINT West

REPEAT
    MOVE FORWARD BY 1
UNTIL FoundKey == True

TURN 180 Degrees

WHILE StillOnMap == True
    MOVE FORWARD BY 1
    IF FoundSpider == TRUE THEN
           CRUSH spider
           EXIT WHILE LOOP
    END IF
END WHILE 	

POINT South
MOVE FORWARD BY 2
DIG FOR TREASURE

Can you tell where Captain Redbeard’s treasure has been buried for all these years?

Tagged with:

3D Printing Programming

3DPrinting-101Computing
Using a “scratch like” programming language you can create your own 3D models and export them in a format recognised by 3D Printers.

Click on the picture above to access the BeetleBlocks project:

3DPrinting-Programming

Tagged with: , ,

Murder Mystery

Murder-MysteryDoctor Black has just been found dead in his bedroom. He has been knocked down by a heavy metallic object, most likely the candlestick that was found on the floor next to Doctor Black. When falling down, Doctor Black broke his watch which stopped at 8:14 PM. We can assume that this is the time of death.

Doctor Black’s bedroom is the master bedroom and is located on the first floor.

Our crime scene investigator took some notes to recap the key facts:

cluedo-clipboard

At this time of the day there were only four guests in Doctor Black’s mansion. They are the prime suspects:

  • Miss Scarlett
  • Reverend Green
  • Colonel Mustard
  • Professor Plum

do-not-cross

Our crime scene investigator interviewed all four suspects and gathered some facts about their whereabouts around the time of death.

He has decided to create an algorithm based on these facts to help him solve this murder mystery. To do so he has translated each fact into pseudo code as follows:

Fact:

Miss Scarlett and Professor Plum were playing tennis between 6 and 8PM, so if the murder took place between 6 and 8PM they would both be innocent.

Pseudocode:

IF TimeOfMurder >= 6:00PM AND TimeOfMurder <= 8:00PM THEN
    MissScarlett = "Innocent"
    ProfessorPlum = "Innocent"
END IF

do-not-cross

Below is our crime scene investigator’s full algorithm:

Will it help you solve this crime?

IF TimeOfMurder >= 6:00PM AND TimeOfMurder <= 8:00PM THEN
    MissScarlett = "Innocent"
    ProfessorPlum = "Innocent"
END IF

SELECT CASE LocationOfMurder:
    CASE "1st Floor":
        ReverendGreen = "Innocent"
    CASE "Ground Level":
        MissScarlett = "Innocent"
        ColonelMustard = "Innocent"
    CASE "Garden"
        ProfessorPlum = "Innocent"

IF (MurderRoom == "Kitchen" OR MuderRoom == "Master Bedroom")  AND timeOfMurder >= 8:00PM THEN
    ProfessorPlum = "Innocent"
ELIF MurderRoom == "Bathroom" AND (timeOfMurder >= 8:00PM AND timeOfMurder <= 8:30PM) THEN
    MissScarlett = "Guilty"
END IF

IF MurderWeapon == "Candlestick" OR MurderWeapon == "Rope" THEN
    MurdererGender = "Male"
END IF

And the murderer is …

do-not-cross

Tagged with: ,