In this activity, we are going to build a two player Ping Pong like game using Scratch on the Raspberry Pi. There will be two paddles and a ball. The paddles will be user controlled to try to hit the ball back the other direction to the other player. A LED will light up when either player scores.
To begin, open Scratch and delete the Cat sprite on the right hand side.
NOTE: To interact with the GPIO pins from the Raspberry Pi, you must install “nuscratch” if not already. To do this, open a terminal and type “sudo apt-get install nuscratch” (no quotes) and answer “y” to any questions. If the sudo password is needed, ask your facilitator.
To create the backdrop, click the “Stage” section in the bottom right hand portion of the window.
Then, in the main window, click the Backgrounds tab.
Then, click the edit button, and choose your background of choice. I chose the brick wall background
Next, we're going to create the paddles. In the bottom right hand window, click the "Paint New Sprite" button beside the text "New Sprite."
Choose the line tool and draw a vertical line in the middle of the grid then click OK.
Then, rename the line to Paddle1 at the top of the main window.
Next, under the scripts tab, drop each instruction below into the window. These instructions are found by clicking the buttons in the upper left portion of the window that have the color corresponding to the color of the instruction. For instance, the “When <FLAG> clicked” button is under the “Control” button because it has an orange bar on the left hand side of it.
Fill in the values as seen and select the buttons to move the paddle up and down. I used “W” and “S” for player 1.
Next, right click on paddle1 in the lower right window and select duplicate. Name the new sprite paddle2.
This will create the paddle for player 2. Change the values in script as seen below. I used the up arrow and down arrow to move the paddle for player 2.
Next, we're going to create our variables for the score. Click the Variables button in the upper left windows.
Then, click the “Make a variable” button and name it Score1. Leave “For all Sprites” selected.
Repeat this and create another variable named Score2.
In the bottom right window, click the "Choose a new sprite file" button to import a ball sprite. I chose a beach ball, but you can choose any ball you'd like.
Next, insert the script parts seen below. Take your time and make sure you get everything!
Also, go to “EDIT>Start GPIO Server” to allow the interaction with the GPIO pins.
First, place a jumper from GPIO 14 to a spot on the breadboard.
Then do the same from GPIO 15.
Next, place a jumper from the ground pin on the Raspberry Pi to the “-” rail on the breadboard.
Next, add your two LEDs with the “hot” leg connected to the GPIO jumpers and the negative leg connected to the ground rail. The “hot” leg is the longer leg on the LED.
GET IN TOUCH