Use an analog sensor as a video game controller

Game Loop

The main game loop (lines 137 to 158) starts by calling to check and see if the paddle has moved (line 140); and then runs a bunch of tests to see what the ball has hit, if anything at all.

You test to see if it hit a wall on line 145, a brick on line 149 (if so you delete the brick on line 151), and if it hit the paddle on line 154.

On line 142 we check to see if the ball is lower down in the screen than the paddle. If that is the case it means the player has missed the ball and lost the game. You break out of the loop and the game ends.

On line 156 you re-draw the screen so you can see the changes each cycle of the loop brings.

Line 158 establishes the speed of the game. Make the number smaller for faster game play.


To play the game, make sure you have the library in the same directory as the file, or in a Python library directory as explained above.


$ python

Remember the ball will not start moving until you twiddle the potentiometer and hit the mid-point.

For simplicity's sake, this is a very bare bones version of Breakout. There is no scoreboard; only one level; if you miss the ball, the program ends. When you destroy the last brick, you will have to continue playing in an empty court until exhaustion, boredom, or the unwillingness to continue living compels you to miss.

Perhaps the biggest sin of this game is that it is predictable. The ball will always hit the same bricks in the same place. The ball will bounce off every object in the same way.

You can easily change the program to figure out where the ball hits a brick or the paddle and change its trajectory, but that is an exercise I leave to you, the patient reader. I look forward to your variations.

Buy this article as PDF

Express-Checkout as PDF

Pages: 6

Price $2.95
(incl. VAT)

Buy Raspberry Pi Geek

Get it on Google Play

US / Canada

Get it on Google Play

UK / Australia

Related content