More results...

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

BBC micro:bit – Pong (1 Player)

BBC-microbit-PongIn this tutorial, we will create a simplified version of Pong for 1 player to play using a micro:bit.

The challenge is to create the game considering that the micro:bit screen consists of a 2D grid of 25 LEDs (5 by 5 grid).

As opposed to the real game of Pong, we will only use one paddle, located at the bottom of the screen. The player will control the paddle using the A button (to move the paddle to the left) and the B button (to move the paddle to the right).

A sprite will be used to represent the ball which will be bouncing against the top, left and right edges of the screen and against the paddle. If the use fails to catch the ball, the ball will reach the bottom edge of the screen which will trigger a game over message.

To implement this game you will need to use the micro:bit website to create the code using the JavaScript Block Editor.

micro-bit-logo

Step 1: Initialising the game


First we will initialise the main sprites:
BBC-microbit-pong-onstart
The main sprites are:

  • The ball sprite will start on the top row (y = 0) at a random x position (between 0 and 4). The ball will also be given a direction using two variables: directionX and directionY. The following diagram represents the 6 different directions of the ball sprite on the 2D grid.
    bbc-microbit-pong-directions
    When we first initialise the ball and position it at the top of the screen, we also set a direction where the ball is aiming downwards (direction 4, 5 or 6 from the diagram above).
  • The paddle consists of 2 sprites, paddleA and paddleB, as a sprite only consists of 1 LED, we used two sprites next to each other to create a wider paddle (as wide as 2 LEDs). The paddle is located on the bottom row (y = 4) and can be moved horizontally by pressing the left and right buttons of the micro:bit using the following code:
  • BBC-microbit-pong-onbutton-pressed

    Step 2: Bouncing ball algorithm


    The most complex part of the game is to control the movement of the ball sprite. Every 500ms, the ball moves in the direction set by the (directionX,directionY) vector. Based on its new position the code provided below detects different possible scenarios:

    • The ball should bounce against the left, top, and right edges of the screen. Each bounce will affect its direction.
    • The ball should bounce against the paddle. Once again, a bounce will affect the direction of the ball.
    • If the ball reaches the bottom edge of the screen, a game over message should be displayed.

    BBC-microbit-pong-forever

    The code is now complete. You can recreate the game and then customise it further by adding a scoring system, or by making the ball move faster (using a shorter delay/pause) every time the ball hits the paddle.

Tagged with:

Breakout Tutorial using Pygame: Adding a Brick Wall

break-out-gameThis tutorial is the second tutorial in a series of five Pygame tutorials:

The final stage of our tutorial focuses on adding a brick wall and a scoring system to our Breakout game:

  • The player will score a point if the ball bounces against a brick.
  • The player will lose a life if the ball bounces against the bottom edge of the screen.
  • Both the score and number of lives will be displayed at the top of the screen.
  • A “Level Complete” message will be displayed if all bricks have been removed.
  • A “Game Over” message will be displayed if the number of lives reaches zero.
  • The final code for the main.py is provided below. We made several changes to the code as follows:

    • On line 6 we import the Brick class. (Code provided in the brick.py tab)
    • On lines 39 to 57 we create three rows of bricks and add them to a group called all_bricks.
    • On lines 93 to 103 we take a life away when the ball hit the bottom edge of the screen. If the number of lives reaches zero, we display a “Game Over” message..
    • On lines 114 to 129 we detect if the ball hits a brick. If so we remove the brick (using the kill() method) and increment the score by one.
    main.pypaddle.pyball.pybrick.py
    #Import the pygame library and initialise the game engine
    import pygame
    #Let's import the Paddle Class & the Ball Class
    from paddle import Paddle
    from ball import Ball
    from brick import Brick
    
    pygame.init()
    
    # Define some colors
    WHITE = (255,255,255)
    DARKBLUE = (36,90,190)
    LIGHTBLUE = (0,176,240)
    RED = (255,0,0)
    ORANGE = (255,100,0)
    YELLOW = (255,255,0)
    
    score = 0
    lives = 3
    
    # Open a new window
    size = (800, 600)
    screen = pygame.display.set_mode(size)
    pygame.display.set_caption("Breakout Game")
    
    #This will be a list that will contain all the sprites we intend to use in our game.
    all_sprites_list = pygame.sprite.Group()
    
    #Create the Paddle
    paddle = Paddle(LIGHTBLUE, 100, 10)
    paddle.rect.x = 350
    paddle.rect.y = 560
    
    #Create the ball sprite
    ball = Ball(WHITE,10,10)
    ball.rect.x = 345
    ball.rect.y = 195
    
    all_bricks = pygame.sprite.Group()
    for i in range(7):
        brick = Brick(RED,80,30)
        brick.rect.x = 60 + i* 100
        brick.rect.y = 60
        all_sprites_list.add(brick)
        all_bricks.add(brick)
    for i in range(7):
        brick = Brick(ORANGE,80,30)
        brick.rect.x = 60 + i* 100
        brick.rect.y = 100
        all_sprites_list.add(brick)
        all_bricks.add(brick)
    for i in range(7):
        brick = Brick(YELLOW,80,30)
        brick.rect.x = 60 + i* 100
        brick.rect.y = 140
        all_sprites_list.add(brick)
        all_bricks.add(brick)
    
    # Add the paddle and the ball to the list of sprites
    all_sprites_list.add(paddle)
    all_sprites_list.add(ball)
    
    # The loop will carry on until the user exits the game (e.g. clicks the close button).
    carryOn = True
    
    # The clock will be used to control how fast the screen updates
    clock = pygame.time.Clock()
    
    # -------- Main Program Loop -----------
    while carryOn:
        # --- Main event loop
        for event in pygame.event.get(): # User did something
            if event.type == pygame.QUIT: # If user clicked close
                  carryOn = False # Flag that we are done so we exit this loop
    
        #Moving the paddle when the use uses the arrow keys
        keys = pygame.key.get_pressed()
        if keys[pygame.K_LEFT]:
            paddle.moveLeft(5)
        if keys[pygame.K_RIGHT]:
            paddle.moveRight(5)
    
        # --- Game logic should go here
        all_sprites_list.update()
    
        #Check if the ball is bouncing against any of the 4 walls:
        if ball.rect.x>=790:
            ball.velocity[0] = -ball.velocity[0]
        if ball.rect.x<=0:
            ball.velocity[0] = -ball.velocity[0]
        if ball.rect.y>590:
            ball.velocity[1] = -ball.velocity[1]
            lives -= 1
            if lives == 0:
                #Display Game Over Message for 3 seconds
                font = pygame.font.Font(None, 74)
                text = font.render("GAME OVER", 1, WHITE)
                screen.blit(text, (250,300))
                pygame.display.flip()
                pygame.time.wait(3000)
    
                #Stop the Game
                carryOn=False
    
        if ball.rect.y<40:
            ball.velocity[1] = -ball.velocity[1]
    
        #Detect collisions between the ball and the paddles
        if pygame.sprite.collide_mask(ball, paddle):
          ball.rect.x -= ball.velocity[0]
          ball.rect.y -= ball.velocity[1]
          ball.bounce()
    
        #Check if there is the ball collides with any of bricks
        brick_collision_list = pygame.sprite.spritecollide(ball,all_bricks,False)
        for brick in brick_collision_list:
          ball.bounce()
          score += 1
          brick.kill()
          if len(all_bricks)==0:
               #Display Level Complete Message for 3 seconds
                font = pygame.font.Font(None, 74)
                text = font.render("LEVEL COMPLETE", 1, WHITE)
                screen.blit(text, (200,300))
                pygame.display.flip()
                pygame.time.wait(3000)
    
                #Stop the Game
                carryOn=False
    
        # --- Drawing code should go here
        # First, clear the screen to dark blue.
        screen.fill(DARKBLUE)
        pygame.draw.line(screen, WHITE, [0, 38], [800, 38], 2)
    
        #Display the score and the number of lives at the top of the screen
        font = pygame.font.Font(None, 34)
        text = font.render("Score: " + str(score), 1, WHITE)
        screen.blit(text, (20,10))
        text = font.render("Lives: " + str(lives), 1, WHITE)
        screen.blit(text, (650,10))
    
        #Now let's draw all the sprites in one go. (For now we only have 2 sprites!)
        all_sprites_list.draw(screen)
    
        # --- Go ahead and update the screen with what we've drawn.
        pygame.display.flip()
    
        # --- Limit to 60 frames per second
        clock.tick(60)
    
    #Once we have exited the main program loop we can stop the game engine:
    pygame.quit()
    The code for the Paddle class remains unchanged.

    import pygame
    BLACK = (0,0,0)
    
    class Paddle(pygame.sprite.Sprite):
        #This class represents a paddle. 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 paddle, its width and height.
            # Set the background color and set it to be transparent
            self.image = pygame.Surface([width, height])
            self.image.fill(BLACK)
            self.image.set_colorkey(BLACK)
    
            # Draw the paddle (a rectangle!)
            pygame.draw.rect(self.image, color, [0, 0, width, height])
    
            # Fetch the rectangle object that has the dimensions of the image.
            self.rect = self.image.get_rect()
    
    
        def moveLeft(self, pixels):
            self.rect.x -= pixels
    	    #Check that you are not going too far (off the screen)
            if self.rect.x < 0:
              self.rect.x = 0
    
        def moveRight(self, pixels):
            self.rect.x += pixels
            #Check that you are not going too far (off the screen)
            if self.rect.x > 700:
              self.rect.x = 700
    
    The code for the Ball class remains unchanged.

    import pygame
    from random import randint
    
    BLACK = (0, 0, 0)
     
    class Ball(pygame.sprite.Sprite):
        #This class represents a ball. 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 ball, its width and height.
            # Set the background color and set it to be transparent
            self.image = pygame.Surface([width, height])
            self.image.fill(BLACK)
            self.image.set_colorkey(BLACK)
     
            # Draw the ball (a rectangle!)
            pygame.draw.rect(self.image, color, [0, 0, width, height])
            
            self.velocity = [randint(4,8),randint(-8,8)]
            
            # Fetch the rectangle object that has the dimensions of the image.
            self.rect = self.image.get_rect()
            
        def update(self):
            self.rect.x += self.velocity[0]
            self.rect.y += self.velocity[1]
              
        def bounce(self):
            self.velocity[0] = -self.velocity[0]
            self.velocity[1] = randint(-8,8)
    
    This is the code for the new Brick class, to be saved in a new file called brick.py.

    import pygame
    BLACK = (0,0,0)
    
    class Brick(pygame.sprite.Sprite):
        #This class represents a brick. 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 brick, 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(BLACK)
            self.image.set_colorkey(BLACK)
    
            # Draw the brick (a rectangle!)
            pygame.draw.rect(self.image, color, [0, 0, width, height])
    
            # Fetch the rectangle object that has the dimensions of the image.
            self.rect = self.image.get_rect()
    
    Tagged with:

    Breakout Tutorial using Pygame: Adding a Bouncing Ball

    break-out-gameThis tutorial is the second tutorial in a series of five Pygame tutorials:

    Our aim is to add the bouncing ball to our Breakout game. To do so we will create a new class called Ball.

    Bouncing Algorithm


    To understand how to implement a bouncing algorithm, it is essential to understand how the computer controls the trajectory of a sprite (e.g. ball) on the screen. Arcade games are based on a frame based animation where the screen is refreshed every x milliseconds. Moving sprites are positionned using (x,y) coordinates and have a velocity vector (Vx,Vy) which specifies the delta in pixels to apply to the (x,y) coordinates of a sprite between two frames:

    • frame n: Sprite Coordinates: (x,y)
    • frame n+1: Sprite Coordinates: (x+Vx,y+Vy)

    velocity-vector

    As the sprite moves across the screen, it may need to bounce against another sprite or against the edge of the screen.

    Let’s investigate how the velocity vector is affected when the sprite bounces against vertical and horizontal walls/edges.

    Right Wall/EdgeLeft Wall/EdgeTop Wall/EdgeBottom Wall/Edge
    bouncing-algorithm-right
    bouncing-algorithm-left
    bouncing-algorithm-top
    bouncing-algorithm-bottom

    Ball Class


    Below is the code for the Ball class. You will need to copy this code in a new Python file called ball.py. The update() method of this class will be called for each frame of the main program loop. It moves (changes the (x,y) coordinates of) the ball using its velocity vector.

    import pygame
    from random import randint
    BLACK = (0,0,0)
    
    class Ball(pygame.sprite.Sprite):
        #This class represents a ball. 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 ball, its width and height.
            # Set the background color and set it to be transparent
            self.image = pygame.Surface([width, height])
            self.image.fill(BLACK)
            self.image.set_colorkey(BLACK)
     
            # Draw the ball (a rectangle!)
            pygame.draw.rect(self.image, color, [0, 0, width, height])
            
            self.velocity = [randint(4,8),randint(-8,8)]
            
            # Fetch the rectangle object that has the dimensions of the image.
            self.rect = self.image.get_rect()
            
        def update(self):
            self.rect.x += self.velocity[0]
            self.rect.y += self.velocity[1]
    

    Adding the ball to the game


    In the main.py file, we will first import the Ball class. (See line 5) We will then create an object called ball using the Ball class. (See lines 33 to 36) We will add this object to the all_sprites_list group of sprites. (See line 40)

    We will also apply the bouncing algorithm to check if it needs to bounce against any of the four walls. (See lines 65 to 73)

    #Import the pygame library and initialise the game engine
    import pygame
    #Let's import the Paddle Class & the Ball Class
    from paddle import Paddle
    from ball import Ball
    
    pygame.init()
    
    # Define some colors
    WHITE = (255,255,255)
    DARKBLUE = (36,90,190)
    LIGHTBLUE = (0,176,240)
    RED = (255,0,0)
    ORANGE = (255,100,0)
    YELLOW = (255,255,0)
    
    score = 0
    lives = 3
    
    # Open a new window
    size = (800, 600)
    screen = pygame.display.set_mode(size)
    pygame.display.set_caption("Breakout Game")
    
    #This will be a list that will contain all the sprites we intend to use in our game.
    all_sprites_list = pygame.sprite.Group()
    
    #Create the Paddle
    paddle = Paddle(LIGHTBLUE, 100, 10)
    paddle.rect.x = 350
    paddle.rect.y = 560
    
    #Create the ball sprite
    ball = Ball(WHITE,10,10)
    ball.rect.x = 345
    ball.rect.y = 195
    
    # Add the paddle to the list of sprites
    all_sprites_list.add(paddle)
    all_sprites_list.add(ball)
    
    # The loop will carry on until the user exits the game (e.g. clicks the close button).
    carryOn = True
    
    # The clock will be used to control how fast the screen updates
    clock = pygame.time.Clock()
    
    # -------- Main Program Loop -----------
    while carryOn:
        # --- Main event loop
        for event in pygame.event.get(): # User did something
            if event.type == pygame.QUIT: # If user clicked close
                  carryOn = False # Flag that we are done so we exit this loop
    
        #Moving the paddle when the use uses the arrow keys
        keys = pygame.key.get_pressed()
        if keys[pygame.K_LEFT]:
            paddle.moveLeft(5)
        if keys[pygame.K_RIGHT]:
            paddle.moveRight(5)
    
        # --- Game logic should go here
        all_sprites_list.update()
    
        #Check if the ball is bouncing against any of the 4 walls:
        if ball.rect.x>=790:
            ball.velocity[0] = -ball.velocity[0]
        if ball.rect.x<=0:
            ball.velocity[0] = -ball.velocity[0]
        if ball.rect.y>590:
            ball.velocity[1] = -ball.velocity[1]
        if ball.rect.y<40:
            ball.velocity[1] = -ball.velocity[1]
    
        # --- Drawing code should go here
        # First, clear the screen to dark blue.
        screen.fill(DARKBLUE)
        pygame.draw.line(screen, WHITE, [0, 38], [800, 38], 2)
    
        #Display the score and the number of lives at the top of the screen
        font = pygame.font.Font(None, 34)
        text = font.render("Score: " + str(score), 1, WHITE)
        screen.blit(text, (20,10))
        text = font.render("Lives: " + str(lives), 1, WHITE)
        screen.blit(text, (650,10))
    
        #Now let's draw all the sprites in one go. (For now we only have 2 sprites!)
        all_sprites_list.draw(screen)
    
        # --- Go ahead and update the screen with what we've drawn.
        pygame.display.flip()
    
        # --- Limit to 60 frames per second
        clock.tick(60)
    
    #Once we have exited the main program loop we can stop the game engine:
    pygame.quit()
    

    Collision Detection


    The next addition to our game is to detect when the ball hits/collides with one the two paddles. If it does, we will make it bounce using a random new direction.

    So first, let’s add a new method called bounce() to our Ball class.

    Then, in the main program loop, let’s add some code to detect if the ball sprite collides with the paddleA or paddleB sprites. If it does we will call the bounce() method of the Ball class.

    ball.pymain.py
    We have added the bounce() method on lines 30 to 32.

    import pygame
    from random import randint
    BLACK = (0, 0, 0)
    
    class Ball(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(BLACK)
            self.image.set_colorkey(BLACK)
     
            # Draw the ball (a rectangle!)
            pygame.draw.rect(self.image, color, [0, 0, width, height])
            
            self.velocity = [randint(4,8),randint(-8,8)]
            
            # Fetch the rectangle object that has the dimensions of the image.
            self.rect = self.image.get_rect()
            
        def update(self):
            self.rect.x += self.velocity[0]
            self.rect.y += self.velocity[1]
            
        def bounce(self):
            self.velocity[0] = -self.velocity[0]
            self.velocity[1] = randint(-8,8)
    
    We have added on lines 75 to 79 the code to detect a collision between the ball and the paddles.

    # Import the pygame library and initialise the game engine
    import pygame
    #Let's import the Paddle Class & the Ball Class
    from paddle import Paddle
    from ball import Ball
    
    pygame.init()
    
    # Define some colors
    WHITE = (255,255,255)
    DARKBLUE = (36,90,190)
    LIGHTBLUE = (0,176,240)
    RED = (255,0,0)
    ORANGE = (255,100,0)
    YELLOW = (255,255,0)
    
    score = 0
    lives = 3
    
    # Open a new window
    size = (800, 600)
    screen = pygame.display.set_mode(size)
    pygame.display.set_caption("Breakout Game")
    
    #This will be a list that will contain all the sprites we intend to use in our game.
    all_sprites_list = pygame.sprite.Group()
    
    #Create the Paddle
    paddle = Paddle(LIGHTBLUE, 100, 10)
    paddle.rect.x = 350
    paddle.rect.y = 560
    
    #Create the ball sprite
    ball = Ball(WHITE,10,10)
    ball.rect.x = 345
    ball.rect.y = 195
    
    # Add the paddle and the ball to the list of sprites
    all_sprites_list.add(paddle)
    all_sprites_list.add(ball)
    
    # The loop will carry on until the user exit the game (e.g. clicks the close button).
    carryOn = True
    
    # The clock will be used to control how fast the screen updates
    clock = pygame.time.Clock()
    
    # -------- Main Program Loop -----------
    while carryOn:
        # --- Main event loop
        for event in pygame.event.get(): # User did something
            if event.type == pygame.QUIT: # If user clicked close
                  carryOn = False # Flag that we are done so we exit this loop
    
        #Moving the paddle when the use uses the arrow keys
        keys = pygame.key.get_pressed()
        if keys[pygame.K_LEFT]:
            paddle.moveLeft(5)
        if keys[pygame.K_RIGHT]:
            paddle.moveRight(5)
    
        # --- Game logic should go here
        all_sprites_list.update()
    
        #Check if the ball is bouncing against any of the 4 walls:
        if ball.rect.x>=790:
            ball.velocity[0] = -ball.velocity[0]
        if ball.rect.x<=0:
            ball.velocity[0] = -ball.velocity[0]
        if ball.rect.y>590:
            ball.velocity[1] = -ball.velocity[1]
        if ball.rect.y<40:
            ball.velocity[1] = -ball.velocity[1]
    
        #Detect collisions between the ball and the paddles
        if pygame.sprite.collide_mask(ball, paddle):
          ball.rect.x -= ball.velocity[0]
          ball.rect.y -= ball.velocity[1]
          ball.bounce()
    
        # --- Drawing code should go here
        # First, clear the screen to dark blue.
        screen.fill(DARKBLUE)
        pygame.draw.line(screen, WHITE, [0, 38], [800, 38], 2)
    
        #Display the score and the number of lives at the top of the screen
        font = pygame.font.Font(None, 34)
        text = font.render("Score: " + str(score), 1, WHITE)
        screen.blit(text, (20,10))
        text = font.render("Lives: " + str(lives), 1, WHITE)
        screen.blit(text, (650,10))
    
        #Now let's draw all the sprites in one go. (For now we only have 2 sprites!)
        all_sprites_list.draw(screen)
    
        # --- Go ahead and update the screen with what we've drawn.
        pygame.display.flip()
    
        # --- Limit to 60 frames per second
        clock.tick(60)
    
    #Once we have exited the main program loop we can stop the game engine:
    pygame.quit()
    

    Next Step?


    The final touch consists of adding a scoring system:
    Breakout Tutorial using Pygame:Adding a Brick Wall
    Tagged with:

    Breakout Tutorial using Pygame: Controlling the Paddle

    break-out-gameThis tutorial is the second 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 game of Breakout. In the first tutorial we looked at how to create the background for our game. In the second tutorial we added our first sprite called paddle which is an instance of the Paddle class.

    In this third tutorial we will add methods to our Paddle class to move the paddle left and right when player uses the left and right arrow keys.

    We will then add event handlers to the main program loop to respond to keystroke events. When the players use the relevant keys on the keyboard we will call our methods to move their paddle on the screen.

    Step 1: Adding Methods to the Paddle class.


    Open the file paddle.py and add the lines 23 to 33 as follows:

    import pygame
    BLACK = (0,0,0)
    
    class Paddle(pygame.sprite.Sprite):
        #This class represents a paddle. 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 paddle, its width and height.
            # Set the background color and set it to be transparent
            self.image = pygame.Surface([width, height])
            self.image.fill(BLACK)
            self.image.set_colorkey(BLACK)
     
            # Draw the paddle (a rectangle!)
            pygame.draw.rect(self.image, color, [0, 0, width, height])
            
            # Fetch the rectangle object that has the dimensions of the image.
            self.rect = self.image.get_rect()
            
        def moveLeft(self, pixels):
            self.rect.x -= pixels
            #Check that you are not going too far (off the screen)
            if self.rect.x < 0:
              self.rect.x = 0
              
        def moveRight(self, pixels):
            self.rect.x += pixels
            #Check that you are not going too far (off the screen)
            if self.rect.x > 700:
              self.rect.x = 700
    

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

    def moveLeft(self, pixels):
        self.rect.x -= pixels
        #Check that you are not going too far (off the screen)
        if self.rect.x < 0:
           self.rect.x = 0
    

    The moveLeft() 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 paddle.

    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 four event handlers, to move the paddle up or down when the user presses the the left and right arrow keys. Each event handler will call the relevant method from the Paddle class. Check the code below with the new event handlers from line 47 to 52.

    #Import the pygame library and initialise the game engine
    import pygame
    #Let's import the Paddle Class
    from paddle import Paddle
    pygame.init()
    # Define some colors
    WHITE = (255,255,255)
    DARKBLUE = (36,90,190)
    LIGHTBLUE = (0,176,240)
    RED = (255,0,0)
    ORANGE = (255,100,0)
    YELLOW = (255,255,0)
    score = 0
    lives = 3
    # Open a new window
    size = (800, 600)
    screen = pygame.display.set_mode(size)
    pygame.display.set_caption("Breakout Game")
    #This will be a list that will contain all the sprites we intend to use in our game.
    all_sprites_list = pygame.sprite.Group()
    #Create the Paddle
    paddle = Paddle(LIGHTBLUE, 100, 10)
    paddle.rect.x = 350
    paddle.rect.y = 560
    # Add the paddle to the list of sprites
    all_sprites_list.add(paddle)
    # The loop will carry on until the user exits the game (e.g. clicks the close button).
    carryOn = True
    # The clock will be used to control how fast the screen updates
    clock = pygame.time.Clock()
    # -------- Main Program Loop -----------
    while carryOn:
        # --- Main event loop
        for event in pygame.event.get(): # User did something
            if event.type == pygame.QUIT: # If user clicked close
                  carryOn = False # Flag that we are done so we exit this loop
     
        #Moving the paddle when the use uses the arrow keys 
        keys = pygame.key.get_pressed()
        if keys[pygame.K_LEFT]:
            paddle.moveLeft(5)
        if keys[pygame.K_RIGHT]:
            paddle.moveRight(5)  
    
        # --- Game logic should go here
        all_sprites_list.update()
    
        # --- Drawing code should go here
        # First, clear the screen to dark blue.
        screen.fill(DARKBLUE)
        pygame.draw.line(screen, WHITE, [0, 38], [800, 38], 2)
        #Display the score and the number of lives at the top of the screen
        font = pygame.font.Font(None, 34)
        text = font.render("Score: " + str(score), 1, WHITE)
        screen.blit(text, (20,10))
        text = font.render("Lives: " + str(lives), 1, WHITE)
        screen.blit(text, (650,10))
        #Now let's draw all the sprites in one go. (For now we only have 2 sprites!)
        all_sprites_list.draw(screen)
        # --- Go ahead and update the screen with what we've drawn.
        pygame.display.flip()
        # --- Limit to 60 frames per second
        clock.tick(60)
    #Once we have exited the main program loop we can stop the game engine:
    pygame.quit()
    

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

    Next Step?


    It’s now time to add a bouncing ball to our game:
    Breakout Tutorial using Pygame:Adding a Bouncing Ball
    Tagged with:

    Breakout Tutorial using Pygame: Adding the Paddle

    break-out-gameThis tutorial is the second tutorial in a series of five Pygame tutorials:

    Learning Objectives


    In this second tutorial on how to create the retro arcade game Breakout using PyGame, we are looking at creating our first sprite.
    definition-sprite

    Consider a sprite as an object. An object can have different properties (e.g. width, height, colour, etc.) and methods (e.g. jump(), hide(), moveForward(), etc.). Like in the industry an object is built from a mould. In computing the mould/template is called a Class.

    So, by creating our first sprite we will implement OOP (Object Orientated Programming). We will create our first Class called Paddle and derive our first object from this class.

    Our first Class


    So let’s look at the code for our Paddle Class:
    To start with the first method we will need in our class is the __init__() method. It’s called a constructor. It is used when the object is first created to initalise the main properties of the object (e.g. its x and y position, dimensions, colour, etc.)

    import pygame
    BLACK = (0,0,0)
    
    class Paddle(pygame.sprite.Sprite):
        #This class represents a paddle. 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 paddle, its width and height.
            # Set the background color and set it to be transparent
            self.image = pygame.Surface([width, height])
            self.image.fill(BLACK)
            self.image.set_colorkey(BLACK)
     
            # Draw the paddle (a rectangle!)
            pygame.draw.rect(self.image, color, [0, 0, width, height])
            
            # Fetch the rectangle object that has the dimensions of the image.
            self.rect = self.image.get_rect()
    

    Later on we will add more properties and methods to this class. But before doing so we will look at how we can use it to create our first object: the pladdle.

    So let’s save our class as a python file called paddle.py.

    Our first Object


    Now that we have a Class we can create/instantiate an object from this Class. (Remember a Class is like a mould. It enables you to create as many objects as you need using the same mould.)

    Let’s go back to our main.py file (from previous tutorial) to edit its content.

    First let’s add at the top of the code an import statement to import our Paddle class.

    #Let's import the Paddle Class
    from paddle import Paddle
    

    Then we need to create and position our paddle in our main program using the following lines of code:

    paddle = Paddle(LIGHTBLUE, 100, 10)
    paddle.rect.x = 350
    paddle.rect.y = 560
    

    Let’s reuse the code from the first tutorial.

    On lines 3/4 notice how we are using the import command to link to our Paddle Class python file (paddle.py).

    On line 25 we are declaring a list called all_sprites_list that will store all the sprites we will create in our game. (For now just one sprite, the paddle)

    On lines 27 to 30, we are instantiating an paddle object using the Paddle class. Notice how when declaring our first object we use the parameters from its constructor (__init__()), in this case, the colour, width and height of the paddle we want to create.

    Now that we have created our first sprite we need to add it to our list of spites: all_sprites_list. This is what happens on line 33.

    Finally, within the main program loop, on line 64 we are refreshing the screen and drawing all the sprites from our list: all_sprites_list.

    Here is the full code:

    #Import the pygame library and initialise the game engine
    import pygame
    #Let's import the Paddle Class
    from paddle import Paddle
    
    pygame.init()
    
    # Define some colors
    WHITE = (255,255,255)
    DARKBLUE = (36,90,190)
    LIGHTBLUE = (0,176,240)
    RED = (255,0,0)
    ORANGE = (255,100,0)
    YELLOW = (255,255,0)
    
    score = 0
    lives = 3
    
    # Open a new window
    size = (800, 600)
    screen = pygame.display.set_mode(size)
    pygame.display.set_caption("Breakout Game")
    
    #This will be a list that will contain all the sprites we intend to use in our game.
    all_sprites_list = pygame.sprite.Group()
    
    #Create the Paddle
    paddle = Paddle(LIGHTBLUE, 100, 10)
    paddle.rect.x = 350
    paddle.rect.y = 560
    
    # Add the paddle to the list of sprites
    all_sprites_list.add(paddle)
    
    # The loop will carry on until the user exits the game (e.g. clicks the close button).
    carryOn = True
    
    # The clock will be used to control how fast the screen updates
    clock = pygame.time.Clock()
    
    # -------- Main Program Loop -----------
    while carryOn:
        # --- Main event loop
        for event in pygame.event.get(): # User did something
            if event.type == pygame.QUIT: # If user clicked close
                  carryOn = False # Flag that we are done so we exit this loop
    
        # --- Game logic should go here
        all_sprites_list.update()
    
        # --- Drawing code should go here
        # First, clear the screen to dark blue.
        screen.fill(DARKBLUE)
        pygame.draw.line(screen, WHITE, [0, 38], [800, 38], 2)
    
        #Display the score and the number of lives at the top of the screen
        font = pygame.font.Font(None, 34)
        text = font.render("Score: " + str(score), 1, WHITE)
        screen.blit(text, (20,10))
        text = font.render("Lives: " + str(lives), 1, WHITE)
        screen.blit(text, (650,10))
    
        #Now let's draw all the sprites in one go. (For now we only have 2 sprites!)
        all_sprites_list.draw(screen)
    
        # --- Go ahead and update the screen with what we've drawn.
        pygame.display.flip()
    
        # --- Limit to 60 frames per second
        clock.tick(60)
    
    #Once we have exited the main program loop we can stop the game engine:
    pygame.quit()
    

    That’s it… You are now ready to move to our third tutorial to learn how to control your sprites using the arrow keys.
    Breakout Tutorial using PygameControlling the paddle

    Tagged with:

    Breakout Tutorial using Pygame – Getting Started

    break-out-gameThis tutorial is the first tutorial in a series of five Pygame tutorials:

    Breakout is one of the earliest arcade video games, first released in 1976 by Atari. It was derived from the game Pong (released by Atari in 1972). This one-player game features simple 2D graphics. It consists of one paddle (in more recent version the paddle was replaced by a spaceship) used to return a bouncing ball back and forth across the screen. The aim of the game is to break the bricks of a brick wall by getting the ball to hit/bounce on the bricks. The score correspond to the number of bricks being hit.

    In this tutorial we are going to recreate a game of Breakout using Python and the Pygame library. The Pygame library is the perfect library to build basic 2D arcade games and to start developing your OOP skills. (Object-Oriented Programming)

    Step 1: Importing and initialising the Pygame library


    Your Python code will need to start with the following two lines of code:

    #Import the pygame library and initialise the game engine
    import pygame
    pygame.init()

    Note that you will first need to install the Pygame library on your computer. Alternatively you can complete this challenge online using the following Trinket/Pygame IDE

    Step 2: Defining the colours you will use in your game


    You will have to declare a constant for each of the main colours used within your game. To help you identify colour codes you may use a colour picker. We will also initialise two global variables, score and lives that we will use later on in the game.

    # Define some colors
    WHITE = (255,255,255)
    DARKBLUE = (36,90,190)
    LIGHTBLUE = (0,176,240)
    RED = (255,0,0)
    ORANGE = (255,100,0)
    YELLOW = (255,255,0)
    
    score = 0
    lives = 3
    

    Step 3: Open a new window


    Your game will run in its own window, for which you can decide of a title, a width and a height.

    # Open a new window
    size = (800, 600)
    screen = pygame.display.set_mode(size)
    pygame.display.set_caption("Breakout Game")

    Step 4: The main program loop


    The main program loop is the key wrapper for your game.

    The main program loop will contain 3 main sections:

    • Capturing Events: Used to constantly “listen” to user inputs and react to these. It could be when the user uses the keyboard or the mouse.
    • Implementing the Game Logic. What happens when the game is running? Are cars moving forward, aliens falling from the sky, ghosts chasing you, etc.
    • Refreshing the screen by redrawing the stage and the sprites.

    The main program loop will also use a frame rate to decide how often should the program complete the loop (& refresh the screen) per second. To implement this we will use the clock object from the pygame library.

    The main program loop will use a timer to decide how many times it will be executed per second.

    # Import the pygame library and initialise the game engine
    import pygame
    pygame.init()
    
    # Define some colors
    WHITE = (255,255,255)
    DARKBLUE = (36,90,190)
    LIGHTBLUE = (0,176,240)
    RED = (255,0,0)
    ORANGE = (255,100,0)
    YELLOW = (255,255,0)
    
    score = 0
    lives = 3
    
    # Open a new window
    size = (800, 600)
    screen = pygame.display.set_mode(size)
    pygame.display.set_caption("Breakout Game")
    
    # The loop will carry on until the user exits the game (e.g. clicks the close button).
    carryOn = True
     
    # The clock will be used to control how fast the screen updates
    clock = pygame.time.Clock()
     
    # -------- Main Program Loop -----------
    while carryOn:
        # --- Main event loop
        for event in pygame.event.get(): # User did something
            if event.type == pygame.QUIT: # If user clicked close
                  carryOn = False # Flag that we are done so we exit this loop
     
        # --- Game logic should go here
     
     
        # --- Drawing code should go here
        # First, clear the screen to dark blue. 
        screen.fill(DARKBLUE)
        pygame.draw.line(screen, WHITE, [0, 38], [800, 38], 2)
    
        #Display the score and the number of lives at the top of the screen
        font = pygame.font.Font(None, 34)
        text = font.render("Score: " + str(score), 1, WHITE)
        screen.blit(text, (20,10))
        text = font.render("Lives: " + str(lives), 1, WHITE)
        screen.blit(text, (650,10))
     
        # --- Go ahead and update the screen with what we've drawn.
        pygame.display.flip()
         
        # --- Limit to 60 frames per second
        clock.tick(60)
     
    #Once we have exited the main program loop we can stop the game engine:
    pygame.quit()
    

    Next Step?


    Your background is ready? Let’s add the first sprite to your project by completing the next tutorial:
    Breakout Tutorial using Pygame:Adding the Paddle
    Tagged with:

    How many lines of output?

    Take the Quiz! (open full screen)


    RGB Colour Guessing Game


    Play the RGB Colour GameOpen in new window

    RGB Colour Code?


    rgb-coloursEvery colour on the screen can be represented using an RGB code (Red, Green, Blue) code. This code consists of three numbers between 0 and 255, indicating how much red, green and blue are used to recreate the colour. For instance the RGB code for:

    • Red is (255,0,0)
    • Green is (0,255,0)
    • Blue is (0,0,255)
    • Yellow is (255,255,0)
    • Orange is (255,165,0)

    Using the RGB colour code we can identify 224 colours: that’s 16,777,216 unique colours!

    Graphic designer and software programmer sometimes prefer to use another notation based on hexadecimal RGB code where each of the three decimal values are converted into a two-digit hexadecimal code, resulting in a 6-digit hexadecimal code. For instance:

    • Red is #FF000
    • Green is #00FF00
    • Blue is #0000FF
    • Yellow is #FFFF00
    • Orange is #FFA500

    Check the following RGB Color picker to see how RGB codes work:

    CMYK to RGB Conversion Algorithm

    CMYK-ColoursCMYK and RGB are two different colour models. The CMYK model is used in the publishing/printing industry as it is based on the four basic colours used for printing colour images on white paper. The four colours of the CMYK model are Cyan, Magenta, Yellow and Black. The CMYK colours are subtractive. This means the colours get darker as you blend them together. This is what happens when you print a colour image on paper as the more ink/pigments you add, the darker the colour gets.

    The RGB model on the other hand is base don the opposite effect. Using the RGB model, the colours get brighter as you increase their Red, Green or Blue values. RGB colours are used to represent colours on a computer screen and are hence used for light emission, not pigments. The colours grow brighter as you blend them or increase their intensity.

    CMYK values are given either as percentages or values between 0 and 1 (e.g. 50% = 0.5), whereas RGB values are given using an integer value between 0 and 255.

    Colour Colour Name (R,G,B) (C,M,Y,K)
    Cyan (0,255,255) (100%,0%,0%,0%)
    Magenta (255,0,255) (0%,100%,0%,0%)
    Yellow (255,255,0) (0%,0%,100%,0%)
    Black (0,0,0) (0%,0%,0%,100%)
    Red (255,0,0) (0%,100%,100%,0%)
    Green (0,255,0) (100%,0%,100%,0%)
    Blue (0,0,255) (100%,100%,0%,0%)
    White (255,255,255) (0%,0%,0%,0%)
    Turquoise (48,213,200) (77%,0%,6%,16%)
    Metallic Gold (212,175,55) (0%,17.45%,74.06%,16.86%)

    It his possible to convert RGB code into CMYK code and vice versa using the formulas provided below.
    rgb-to-cmyk

    CMYK to RGB Conversion Formulas


    CMYK-to-RGB-Conversion-Formulas

    RGB to CMYK Conversion Formulas


    RGB-to-CMYK-Conversion-Formulas

    Programming Task


    Using a programming language of your choice, create a computer program that:

    1. Asks the user to choose between two options:
      • RGB to CMYK conversion
      • CMYK to RGB conversion
    2. Retrieve the RGB or CMYK values based on the option selected
    3. Apply the conversion formulas to calculate the matching CMYK or RGB values
    4. Output the resulting CMYK or RGB values

    Python Code


    We have started the code for you, though you still need to complete the main two functions: RGB_to_CMYK() and CMYK_to_RGB()

    unlock-access

    Solution...

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

    Four Corners Javascript Challenge

    four-corners-compassFour corners is a children’s game, often played in primary/elementary schools. The game can be played in a classroom. One player stand in the middle of the room with a blindfold. All the other participants choose one of the four corners of the room. For the purpose of this game we will call the four corners of the room North, East, South and West. The central player, “it”, designates one corner of the room. All the participants standing in this corner are out of the game. The remaining participants then move to a different corner of their choice and the game carries on until all participants have been caught.

    The aim of this challenge is to recreate the game of four corners using HTML, CSS and JavaScript. The names of all participants will be stored in a JavaScript array called names as follows:

    var names = ["Kacy", "Lucas", "Ali", "Cheung", "Leila"];
    

    You can then access a value within an array using the appropriate index. i.e.

    var player = names[0];
    

    You can find out the number of items in an array using the length property:

    var numberOfPlayers = names.length;
    

    You can sort the values of an array using the sort() method:

    names.sort();
    

    You can use the push() method to append a new value in the array.

    names.push("Jeff");
    

    You can use the pop() method to remove the last value in the array.

    var player = names.pop();
    

    You can reset/empty an array:

    names = [];
    

    You can join two or more arrays together using the concat() method:
    For instance you can join two arrays together:

    var team1 = ["Kacy", "Lucas", "Ali", "Cheung", "Leila"];
    var team2 = ["Jeff", "Fran", "Noah", "Eldece", "Marwan"];
    var allPlayers = team1.concat(team2);
    

    You can join three arrays together (an so on):

    var team1 = ["Kacy", "Lucas", "Ali", "Cheung", "Leila"];
    var team2 = ["Jeff", "Fran", "Noah", "Eldece", "Marwan"];
    var team3 = ["Laura", "Harry", "Tim", "Jess", "Keziah"];
    var allPlayers = team1.concat(team2, team3);
    

    Four Corners Game


    Using some of the techniques mentioned above, review the code for the four corners game. The JavaScript code is incomplete. Add some code in the clickCorner() to complete the game.

    Press the “Edit on Codepen” button to access the code in full screen mode.

    See the Pen
    Four Corners
    by 101 Computing (@101Computing)
    on CodePen.

    unlock-access

    Solution...

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