In this lab, we will review Python concepts by building a simple Sense HAT arcade game.
In this lab, we will be using all of the Python skills and game logic we learned in the previous term to make a simple arcade game.
In this game, the user will be controlling a player that will be catching berries that are falling from the top of the screen.
Details:
Based on Egg Drop
Player must use the joystick to catch the falling berries
Failure to catch the berry results in game over.
Each berry awards one point.
A player must move the catcher, represented by a single pixel, left or right with the joystick
The catcher can only move left to right, on the last row
When the joystick detects a movement left or right, we change the x position + or - 1.
We need to make sure the catcher doesn’t run off the board.
Initialing and calling functions in Python
Programming the SenseHat to detect user input
Displaying content on the SenseHAT LED matrix
Generate a berry at a random position on the top row of the matrix
Each time the loop runs, the berry should fall down a row
Repeat the first two steps for a new berry after the current one reaches the bottom of the matrix
Incrementing variables in Python
Implementing conditionals to control the flow of the game
Check if the catcher and the berry collides
If they do, increase the score of the player
If they don't, the game is over and alert the player of the score
Unlike other programming languages, there is no keyword in Python to declare variables. Instead, a variable is created when you assign a value to it.
myAge = 16
The value within the variable can be reassigned using the assignment (=) operator and concatenated with other variables using the (+) operator.
In Python, functions are decclared using the keyword def followed by the function name, any parameters, and a colon (:). See example below:
def say_hello(name):
return "Hello " + name
It is important to note the indentation. Any code that belongs within a function needs to be indented for Python to recognize it as being a part of that function.
In order to set the color of a LED on the matrix, you need to call the set_pixel function on the SenseHat object. The set_pixel() takes an x and y value which corresponds to its location on the matrix and the color value that it should be displaying.
sense.set_pixel(x, y, colour)
Loops can be used to iterate through sets of data. It will access each element in a data set and you can use them in combination with conditional statements.
>>> bob = "Bob"
>>> for c in contacts:
... if c == bob:
... print("Bob is a contact")
... else:
... print("No match")
Another way to write them in combination is:
>>> if "Bob" in contacts:
... print("Bob is a contact")
Bob is a contact
Resources: