More results...

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

Cake Sale

cakesaleYou are organising a cake sale and want to predict how much money you will raise.

During this cake sale you will be selling the following three types of cakes:
cakesale-cakes

Input


You decide to write a python script that asks the user three questions:

  • How many cupcakes do you plan to sell?
  • How many macarons do you plan to sell?
  • How many cheesecake do you plan to sell?

Process


The python script will then calculate the total money raised using the three user inputs and the prices as follows:

  • Cupcakes: 40p per cupcake,
  • macarons: 50p per macaron,
  • cheesecake: 70p per slice.

Output


The script will finally display this information (total money raised) to the end-user.

Complete the code


Complete your code in the trinket below.

Testing


Once your code is done, complete the following tests to check that your code is working as it should:

Test # Input Values Expected Output Actual Output
#1 Cupcakes: 10
Macarons: 10
Cheesecake: 5
£12.50
#2 Cupcakes: 20
Macarons: 30
Cheesecake: 20
£37
#3 Cupcakes: 40
Macarons: 10
Cheesecake: 10
£28
#4 Cupcakes: 20
Macarons: 20
Cheesecake: 20
£32
#5 Cupcakes: 0
Macarons: 0
Cheesecake: 0
£0

ingredients

Video Tutorial


Extension Task


It did cost ÂŁ12 pounds to buy all the ingredients to bake all the cakes.

Adapt your program to calculate and display the profit knowing that:


profit = money raised – expenses

Then use an If statement to check whether you have made a profit (profit > 0) or a loss (profit < 0) or whether you did break even (profit == 0).

unlock-access

Solution...

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

BBC micro:bit – Ukulele Chord Reader

Ukulele
For this challenge we are going to build a Ukulele Chord Reader for Eric Clapton’s version of the song: “Knock on Heaven’s Door” (Original Author Bob Dylan).

You may want to listen to the song first on youtube

The idea is to use the 25 LEDs of the micro:bit to display each chord of the song to assist a Ukulele player.

First let’s see how a chord works when using a Ukulele:
Ukulele-F-Chord

This is how we will represent the F chord on the BBC micro:bit:
micro-bit-F-chord

Knock on Heaven’s Door


Now let’s look at the full music sheet for “Knock on Heaven’s Door” by Eric Clapton:
Ukulele-Music-Sheet

Challenge


Your task consists of coding your BBC micro:bit (www.microbit.co.k) to represent each chord using the 25 LEDs.

Solution


If you are not sure how to get started, we have started the code for you:
Ukulele-Micro-bit-Solution

Your Task


Use the BBC micro:bit website to code the song. You will need to complete the code provided above to implement the full verse as provided on the above music sheet.

Extension Task 1:


Could you amend your code so that the song restart from the beginning whenever the user presses the A button of the micro:bit.

Extension Task 2:


Could you amend your code further so that the user can use the B button to pause and/or resume the song at any time.

Tagged with: ,

BBC micro:bit – Simon Game

simon-gameIn this blog post we are looking at recreating a fully working Simon Game using the BBC micro:bit.

If you are not sure what a Simon Game is you can check it on this wikipedia page.

You can watch the following two video clips to see the game in action, and understand the Python code used to implement it.

You will notice that our version of the game is simpler as we only use the two inputs from the micro:bit (A and B buttons) whereas the real Simon game is a bit more complex as it has four lights/buttons. The logic of the game remains the same though.

simon-game-vs-microbit

Python Code


If you have a micro:bit yoyu can use the micro:bit website and reuse the code provided below, ready to download to your micro:bit. You will have to use the Python code editor option.

# Simon Game - by 101Computing - www.101computing.net/microbit-simon-game
from microbit import *
import random

left = Image("96300:"
             "96300:"
             "96300:"
             "96300:"
             "96300")
             
right = Image("00369:"
             "00369:"
             "00369:"
             "00369:"
             "00369")

plus = Image("00000:"
             "00900:"
             "09990:"
             "00900:"
             "00000")

AB = ["A", "B"]

#Let's start with a sequence of three characters
sequence = random.choice(AB) + random.choice(AB) + random.choice(AB)

            
correct = True
sleep(1000)

while correct == True:
  #Let's start by displaying the sequence
  for character in sequence:
        if character=="A":
            display.show(left)
        elif character=="B":
            display.show(right)
        sleep(1000)
        display.show(plus)
        sleep(500)
   
  display.scroll("?")
   
  #Capture user input
  #The numbers of time the user will need to press the buttons depends on the length of the sequence
  maxInputs = len(sequence)
  capturedInputs = 0
  while capturedInputs < maxInputs and correct == True:
     if button_a.is_pressed():
        display.show(left)
        #Did the user guess it wrong? 
        if sequence[capturedInputs] == "B":
            correct = False
        sleep(500)    
        display.show(plus)        
        capturedInputs += 1
     if button_b.is_pressed():
        display.show(right)
       #Did the user guess it wrong? 
        if sequence[capturedInputs] == "A":
            correct = False
        sleep(500)
        display.show(plus)
        capturedInputs += 1
        
  #Add an extra character to the sequence
  if correct==True:
        sequence = sequence + random.choice(AB)
        display.show(Image.HAPPY)
        sleep(1000)

#Display Game Over  + final score
if len(sequence)>3:    
    display.scroll("Game Over: Score: " + str(len(sequence))) 
else:
    display.scroll("Game Over: Score: 0")
Tagged with:

BBC micro:bit – Stopwatch

stopwatch-micro-bitIn this challenge we are going to create a Stopwatch (Countdown timer) using the BBC micro:bit.

You do no need a micro:bit to complete this challenge as you can use the online block editor and emulator (www.microbit.co.uk) to code and test your program.

Our program will use both input buttons A and B and the LEDs for as an output:

  • Button A will be used to initialised the stopwatch. Per default the stopwatch will be set at 3 seconds. By pressing button A, the user should be able to increment this value by 1 second at a time.
  • Button B will be used to start the count down. Once this button is pressed the stopwatch should automatically decrement by 1 every second and it should stop when it reaches the value 0 (zero).
  • The LEDs should be used to display the countdown value.

micro-bit-3

Step by Step Solution


Watch this step by step video tutorial to complete the code of your stopwatch.

Extension Task


Option 1:
Can you update this code further so that when both buttons A and B are pressed at the same time, the timer is paused.

Option 2:
Can you update this code so that when the timer reaches zero (0), it displays the text “Happy New Year!”.

Tagged with:

BBC micro:bit – Traffic Light

lego-traffic-light-frontIn this challenge we are going to create and program a traffic light using lego bricks, leds and the BBC micro:bit.

Check this video clip of the complete traffic light in operation:

Step 1: Building the traffic light:

Use a few lego bricks to build the traffic light. Include your LEDs within your blocks and connect their pins to the red and black electric wires.

Make sure that you always connect the cathode of the LED (short leg, flat edge of the LED) to a black wire and use a blue or red wire for the other pin (anode).

lego-traffic-light-frontlego-traffic-light-backlego-led

Step 2: Connecting the traffic light to the BBC micro:bit


We recommend using crocodile clips for this step. Check the diagram below to make the right connections:
traffic-light-leds

Step 3: Programming the micro:bit


Our aim is to reproduce the following traffic light sequence:
traffic-light-sequence

Check below for the recommended code:

Solution 1: BasicSolution 2: Advanced
micro-bit-traffic-lights-blocks-1
In this solution we are adding a countdown when the green or the red light is on to inform the drivers who are waiting for the number of seconds redmaining before the traffic light changes.
micro-bit-traffic-lights-blocks-2

Electronic Circuit


bbc-microbit-traffic-light-circuit

Tagged with: ,

Youtube Channel: Video Tutorials

Python Tutorials: Less than 3 minutes series


video-python-3-min-for-loops

Python Tutorials: Getting Started with Python


video-python-tutorial-1-gettign-started video-python-tutorial-2-sequencing

Python Challenges: Solved!


video-python-challenge-turtle-maze video-python-challenge-discount-price-calculator video-python-challenge-window-cleaner

BBC micro:bit


video-micro-bit-car-racing

Find more videos on our YouTube channel:

101ComputingYouTubeChannel

BBC micro:bit – Car Racing Game

In this challenge you will recreate a fully working game using the BBC micro:bit. You can complete the code online on the BBC micro:bit website.

First check this video to see how this game will work:

Building the game step by step:


Step 1: Initialising the game
yellow-carLet’s initialise a few variables (score, gameOn) as well as our main sprite, the player’s car.

This code will then loop indefinitely while the game carries on. At the end once the game will be over it will display a game over message with the final score.
micro-bit-car-racing-step-1

Step 2: Controlling the main sprite
We are now going to add two event handlers to respond to the user interaction, when the user presses the button A or B. We will use code to move the car to the left or to the right by changing its X coordinate.
micro-bit-car-racing-step-2
Step 3: Adding the first car
The first car called car0 will be positioned at the top of the screen on lane 0. It will then move downwards (by changing the Y coordinate of the car) till it reaches the bottom of the grid. Once at the bottom of the screen we can check if it is colliding with the player’s car. If not we reposition the car at the top of the screen and give it a randomised delay.

The purpose of the randomised delay is to make sure that all 5 cars do not all come down at the same time.
micro-bit-car-racing-step-3

Step 4: Duplicating the code for each car
For this final step we can copy the code from step 3 and paste it for the other 4 cars (car1 to car4).
micro-bit-car-racing-step-4
That’s it the code is complete. You can test the game.

Extension Task


Option 1:
Tweak this code so that the game cars go faster and faster as the user’s score increases.

Option 2:
Change this game into a “Catch the fruit” game, where instead of avoiding the falling sprites the player should try to catch them and score a point each time they do so.

Tagged with:

Pygame Tutorial – Adding More Sprites

car-racingThis tutorial is the fourth tutorial in a series of five Pygame tutorials:

For our car racing game we will add a few more cars.

Each car is an object that will be instantiated from the Car Class.

Looking at the code from our previous tutorial we are adding a few properties and methods to our Car class. This is to allow for the coming cars to have different sizes (width and height), colors and different speed. See the changes on the car.py file.

Then, in our main program, we are going to create four extra cars and we will add these to a list called all_comming_cars. Each car will be given a different color, a speed and a different starting position (x & y coordinates). This is what the code on the main.py file does on lines 34 to 62.

The four cars will be moving down (starting at the top of the screen). When they reach the bottom of the screen they will be given a new color, speed and starting position towards the top of the screen. This is what the code on the main.py file does on lines 89 to 94.

The overall speed of the game will be stored in a variable called speed initialised on line 15 of the main.py file. New event handlers will detect when the user presses the UP or DOWN keys on the keyboard. These will increment or decrement the speed variable by 0.05. See lines 82 to 85 of the main.py file.

Here is the code for our latest Car class and for our main program:

car.pymain.py
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, speed):
        # 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)

        #Initialise attributes of the car.
        self.width=width
        self.height=height
        self.color = color
        self.speed = speed

        # Draw the car (a rectangle!)
        pygame.draw.rect(self.image, self.color, [0, 0, self.width, self.height])

        # Instead we could load a proper picture 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

    def moveForward(self, speed):
        self.rect.y += self.speed * speed / 20

    def moveBackward(self, speed):
        self.rect.y -= self.speed * speed / 20

    def changeSpeed(self, speed):
        self.speed = speed

    def repaint(self, color):
        self.color = color
       pygame.draw.rect(self.image, self.color, [0, 0, self.width, self.height])
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)
YELLOW = (255, 255, 0)
CYAN = (0, 255, 255)
BLUE = (100, 100, 255)

speed = 1
colorList = (RED, GREEN, PURPLE, YELLOW, CYAN, BLUE)


SCREENWIDTH=800
SCREENHEIGHT=600

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, 60, 80, 70)
playerCar.rect.x = 160
playerCar.rect.y = SCREENHEIGHT - 100

car1 = Car(PURPLE, 60, 80, random.randint(50,100))
car1.rect.x = 60
car1.rect.y = -100

car2 = Car(YELLOW, 60, 80, random.randint(50,100))
car2.rect.x = 160
car2.rect.y = -600

car3 = Car(CYAN, 60, 80, random.randint(50,100))
car3.rect.x = 260
car3.rect.y = -300

car4 = Car(BLUE, 60, 80, random.randint(50,100))
car4.rect.x = 360
car4.rect.y = -900


# Add the car to the list of objects
all_sprites_list.add(playerCar)
all_sprites_list.add(car1)
all_sprites_list.add(car2)
all_sprites_list.add(car3)
all_sprites_list.add(car4)

all_coming_cars = pygame.sprite.Group()
all_coming_cars.add(car1)
all_coming_cars.add(car2)
all_coming_cars.add(car3)
all_coming_cars.add(car4)


#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:
                playerCar.moveRight(10)

    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT]:
        playerCar.moveLeft(5)
    if keys[pygame.K_RIGHT]:
        playerCar.moveRight(5)
    if keys[pygame.K_UP]:
        speed += 0.05
    if keys[pygame.K_DOWN]:
        speed -= 0.05


    #Game Logic
    for car in all_coming_cars:
        car.moveForward(speed)
        if car.rect.y > SCREENHEIGHT:
            car.changeSpeed(random.randint(50,100))
            car.repaint(random.choice(colorList))
            car.rect.y = -200

    all_sprites_list.update()

    #Drawing on Screen
    screen.fill(GREEN)
    #Draw The Road
    pygame.draw.rect(screen, GREY, [40,0, 400,SCREENHEIGHT])
    #Draw Line painting on the road
    pygame.draw.line(screen, WHITE, [140,0],[140,SCREENHEIGHT],5)
    #Draw Line painting on the road
    pygame.draw.line(screen, WHITE, [240,0],[240,SCREENHEIGHT],5)
    #Draw Line painting on the road
    pygame.draw.line(screen, WHITE, [340,0],[340,SCREENHEIGHT],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()

Detecting Collision

The next addition to our game is used on most 2D arcade games: The aim is to check when a sprite (e.g. playerCar) is colliding with other sprites (in this case cars stored in the all_coming_cars list).

You would need to add these lines of code in the “game logic” section of your main program loop. For instance you could add these lines on line 95 of the code provided above (main.py).

    #Check if there is a car collision
    car_collision_list = pygame.sprite.spritecollide(playerCar,all_coming_cars,False)
    for car in car_collision_list:
        print("Car crash!")
        #End Of Game
        carryOn=False
Tagged with: , ,

Pygame: How To’s?

This tutorial is the fifth tutorial in a series of five Pygame tutorials:

Now that you have completed your first game you may want to customise it further of or add extra functionalities. The following How-To’s tutorials may become quiet useful.

Also remember that a Pygame game will be based around the main program loop. Make sure you fully understand the structure of your main.py file:

pygame-main-program-loop-flowchart

To gain a better understanding of the Pygame library you should familiarise yourself with its main modules and classes.
View Pygame Framework

How to Add a Background Picture to the game
This would work for background picture or any other pictures that you want to display on the screen.

Before the main program loop add the following code:

background = pygame.image.load("images/background.png")

In your main program loop add the following code:

screen.blit(background, (0, 0))

In the above code (0,0) represents the (x,y) coordinates of where you would like your picture to appear.

The background has to be saved in your “images” folder.

How to use the transparency of a PNG file
When loading a picture use the convert_alpha() method as follows:

myPicture = pygame.image.load("images/myPicture.png").convert_alpha()
How to display text on the screen
To display text on the screen, use the following code:

font = pygame.font.Font(None, 36)
text = font.render("Hello World!", 1, (10, 10, 10))
screen.blit(text, (50,50))
How to flip your sprite
To flip your sprite horizontally:

mySprite.image = pygame.transform.flip(mySprite.image, True, False)

To flip your sprite vertically:

mySprite.image = pygame.transform.flip(mySprite.image, False, True)
How to find out if a key is pressed
In your “event handling loop” of the main program loop add the following code:

for event in pygame.event.get():
  if event.type == KEYDOWN:
    if event.key == K_RIGHT:
        #do_something_here!
    elif event.key == K_LEFT:
        #do_something_here!
    elif event.key == K_UP:
        #do_something_here!
    elif event.key == K_DOWN:
        #do_something_here!
How to create textboxes
The following code uses a class called TextBox and instantiates two textboxes (objects) called username and password.

import pygame
pygame.init()

#Set the pygame window
screen = pygame.display.set_mode((600, 400))

class TextBox:
    #Constructor
    def __init__(self, x, y, w, h, fontSize=24, maxLength=100, resizable=True, text='', textColor=(0,0,0), borderColor=(40,120,180), activeBorderColor=(200,0,0)):
        self.rect = pygame.Rect(x, y, w, h)
        self.color = borderColor
        self.inactiveColor = borderColor
        self.textColor = textColor
        self.activeColor = activeBorderColor
        self.maxLength = maxLength
        self.resizable = resizable
        self.text = text
        self.fontSize= fontSize
        FONT = pygame.font.Font(None, self.fontSize)
        self.txt_surface = FONT.render(text, True, self.color)
        self.active = False


    def handle_event(self, event):
        if event.type == pygame.MOUSEBUTTONDOWN:
            #Detects when the user clicks on the textbox
            if self.rect.collidepoint(event.pos):
                self.active = True
                self.color = self.activeColor
            else:
                self.active = False
                self.color = self.inactiveColor



        if event.type == pygame.KEYDOWN:
            if self.active:
                if event.key == pygame.K_RETURN:
                    #Clear text box
                    self.text = ''
                elif event.key == pygame.K_BACKSPACE:
                    #Remove last character
                    self.text = self.text[:-1]
                elif event.key in [pygame.K_TAB,pygame.K_ESCAPE]:
                    #Ignore = do nothing
                    pass
                else:
                    #Append character
                    if len(self.text) < self.maxLength:
                        self.text += event.unicode
                #Display text
                FONT = pygame.font.Font(None, self.fontSize)
                self.txt_surface = FONT.render(self.text, True, self.textColor)

    def update(self):
        # Resize the box if the text is too long.
        if self.resizable:
            width = max(200, self.txt_surface.get_width()+10)
            self.rect.w = width

    def draw(self, screen):
        screen.blit(self.txt_surface, (self.rect.x+5, self.rect.y+5))
        pygame.draw.rect(screen, self.color, self.rect, 2)



#Main program starts here

#Textbox (x, y , width, height, fontSize, maxLength, resizeable, text, textColor, borderColor, activeBorderColor)
username = TextBox(200, 96, 200, 24, 24, 20, False)
password = TextBox(200, 146, 200, 24, 24, 20, False)
textboxes = [username, password]

font = pygame.font.Font(None, 24)
labelUsername = font.render("Username:", 1, (10, 10, 10))
labelPassword = font.render("Password:", 1, (10, 10, 10))


clock = pygame.time.Clock()
carryOn = True
#Main program loop
while carryOn:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            carryOn = False

        for textbox in textboxes:
            textbox.handle_event(event)

    screen.fill((255, 255, 255))

    screen.blit(labelUsername, (80,100))
    screen.blit(labelPassword, (80,150))

    for textbox in textboxes:
        textbox.update()
        textbox.draw(screen)

    #print(username.text)
    #print(password.text)

    pygame.display.flip()
    clock.tick(30)

pygame.quit()
How to create a popup input box
pop_up_box_pygame
In your main program, at the very top, just after the import pygame statement add the following code:

from pygame.locals import *

def getKey():
  while 1:
    event = pygame.event.poll()
    if event.type == KEYDOWN:
      return event.key
    else:
      pass

def popup(screen, message, width, height,x , y, bgcolor, textColor):
  #Display a popup box in the middle of the screen
  #This popup will only disappear when the user presses the Return key

  fontobject = pygame.font.Font(None,18)
  pygame.draw.rect(screen, bgcolor,
                   (x - width/2 +2,
                    y - height/2 +2,
                    300,36), 0)
  pygame.draw.rect(screen, (255,255,255),
                   (x - width/2,
                    y - height/2,
                    304,40), 1)
  if len(message) != 0:
    screen.blit(fontobject.render(message, 1, textColor),
                (x - width/2 + 10, y - height/2 + 14))
  pygame.display.flip()

def askQuestion(screen, question, width=300, height=40, x=-1, y=-1, bgColor=(255,0,0), textColor=(255,255,255)):
  #width, height, x, y, bgColor and textColor are optional arguments
  #When x and y are omitted, use the centre of the screen
  if x==-1:
    x = screen.get_width() / 2
  if y==-1:
    y = screen.get_height() / 2

  pygame.font.init()
  current_string = []
  popup(screen, question + ": " + "".join(current_string), width, height, x, y, bgColor, textColor)
  upperCase=False
  while 1:
    inkey = getKey()
    if inkey == K_BACKSPACE:
      current_string = current_string[0:-1]
    elif inkey == K_RETURN:
      break
    elif inkey == K_LSHIFT or inkey == K_RSHIFT:
        upperCase=not upperCase #Switch between lowercase and uppercase when the shift key is pressed
    elif inkey <= 255:
      if (inkey>=97 and inkey<=122) and upperCase==True:
        inkey-=32 #Convert to UPPERCASE
      current_string.append(chr(inkey))
    popup(screen, question + ": " + "".join(current_string), width, height, x, y, bgColor, textColor)

  return "".join(current_string)

Then in your main program, whenever you want a new popup box use the following code:

answer = askQuestion(screen, "Type a question...")

Some arguments can be added:

answer = askQuestion(screen, "Login name?", width=300, height=40, x=100, y=100, bgColor=(255,0,0), textColor=(255,255,255))
How to drag a sprite on the screen using the mouse
Want to create a drag and drop game? Add the following code inside the main programme loop and replace playerCar with the name of your sprite.

if pygame.mouse.get_pressed()[0]:
     mousex,mousey = event.pos
     if playerCar.rect.collidepoint(mousex,mousey):
         playerCar.rect.x=mousex-playerCar.rect.width/2
         playerCar.rect.y=mousey-playerCar.rect.height/2
How to check the color of a pixel at a given position
For instance you may want to check if your sprite is walking on the road or on grass. In this case you could use the get_at(x,y) method which returns the color of a pixel at position x, y.
e.g.

GREEN == (0,255,0)
x=100
y=100
if screen.get_at((x, y)) == GREEN:
    print("This pixel is green")
How to pause the game when the player presses a key (e.g. space bar)
You may want to allow the user to pause the game using a shortcut key (e.g. Space Bar). To do so add the following code in the for loop where you catch user events (for event in pygame.event.get():)
Code to add:

        if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
            while True: #Infinite loop that will be broken when the user press the space bar again
                event = pygame.event.wait()
                if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
                    break #Exit infinite loop
How to detect if the user clicks on a sprite
You can detect if the player has clicked on a Sprite by adding the following code to the for loop where you catch user events (for event in pygame.event.get():):

if event.type == MOUSEMOTION: 
     x,y = event.pos

     if playerCar.rect.collidepoint(x,y):
            print "You clicked on the player's car"

     for srite in all_comming_cars:
           if sprite.rect.collidepoint(x,y): 
                 print "You clicked on a car"
How to use a mask on a sprite for more accurate collision detection
The default collision detection in Pygame uses the rect attribute of the sprites to detect if two sprites are overlapping. This approach works well if your sprites are plain rectangles. However, as you start using graphics for your sprite, you will want the collision detection to use the edges of your graphics. You can do so by creating a mask on all your sprites.

To do so, go in your sprite class (e.g. Car Class) and add the following line of code in the constructor (__init__() of the class):

self.mask = pygame.mask.from_surface(self.image)

For instance:

class Car(pygame.sprite.Sprite):
    #This class represents a car. It derives from the "Sprite" class in Pygame.

    def __init__(self, color, width, height, speed):
        # Call the parent class (Sprite) constructor
        super().__init__()

        ...
       
        self.image = pygame.image.load("car.png").convert_alpha()
        self.mask = pygame.mask.from_surface(self.image)

        ...

In your main code, use the following code to detect collisions:

#Check if there is a car collision
        car_collision_list = pygame.sprite.spritecollide(playerCar,all_coming_cars,False,pygame.sprite.collide_mask)
        for car in car_collision_list:
            print("Car crash!")
            #End Of Game
            carryOn=False
Adding Background Music
To add a background soundtrack, download a wav file or mp3 file into a folder called “Sounds”.

At the start of your code (main.py), after importing the pygame library, add the following lines of code:

pygame.mixer.pre_init(frequency=44100, size=-16, channels=2, buffer=4096)
pygame.mixer.music.load('Sounds/soundtrack.mp3')
pygame.mixer.music.play(-1) #-1 means loops for ever, 0 means play just once)

Note that you can stop the music at any time using the following instruction:

pygame.mixer.music.stop()

You may prefer to pause the music:

pygame.mixer.music.pause()

… or unpause the music:

pygame.mixer.music.unpause()
Adding Sound Effects
To add sound effects, download some wav files into a folder called “Sounds” and add the following code when you want to play the sound effect:

effect = pygame.mixer.Sound('Sounds/beep.wav')
effect.play()
Tagged with:

3D Traffic Lights

Did you know?

Traffic Lights
An embedded system is a computer system with a dedicated function within a larger mechanical or electrical system, often with real-time computing constraints.

A burglar alarm, an in-car cruise control system, a speedometer on a bike, a traffic lights control system are all examples of embedded system.

One application of computing is to create the algorithms used by these control systems. For this challenge we will focus on a traffic lights system.

Our Traffic Lights


Our system consists of two traffic lights used at a crossing.

The diagram below describes the sequence that these traffic lights have to follow:
traffic-light-sequence

We have started the code to control the first traffic light, through we have only completed the sequence to animate the first traffic light..

Method #1: Using Selection (If Statements)


(Use Google Chrome to preview this animation)


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

Method #2: Using Iteration (For Loops)


Your Challenge


Tweak this code to control change the pattern both traffic lights. The traffic lights sequences should match the sequences described in the diagram above. However both traffic lights cannot be green at the same time!

Find out more…


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

Extension


Check this article to see how “smart” traffic lights help control the flow of traffic more effectively.

Tagged with: , , ,
Privacy Overview

This website will store some information about your preferences on your own computer inside a tiny file called a cookie. A cookie is a small piece of data that a website asks your browser to store on your computer or mobile device. The cookie allows the website to remember your actions or preferences over time.

You can delete all cookies that are already on your computer, and you can set most browsers to prevent them from being placed. However, if you do this, you may have to manually adjust some preferences every time you visit a site, and some services and functionalities may not work.

Most browsers support cookies, but you can set your browser to decline them and can delete them whenever you like. You can find instructions here for how you can do that on various browsers.

This website uses cookies to:

  1. Identify you as a returning user and to count your visits in traffic statistics analysis
  2. Remember your custom display preferences (such as light/dark theme option)
  3. Provide other usability features, including tracking whether you have already given your consent to cookies

Enabling cookies is not strictly necessary for the website to work but it will provide you with a better browsing experience.

The cookie-related information is not used to identify you personally and is not used for any purpose other than those described here.

There may also be other types of cookies created after you have visited this website. This site uses Google Analytics, a popular web analytics service that uses cookies to help to analyse how users use the site. The information generated by the cookie about your use of this website (including your IP address) will be transmitted to and stored by Google on servers in the United States. Google will use this information for the purpose of evaluating your use of other website, compiling reports on website activity, and providing other services relating to website activity and internet usage. Google may also transfer this information to third parties where required to do so by law, or where such third parties process the information on Google’s behalf. Google undertakes not to associate your IP address with any other data held by Google.