Prerequisites
You should review the following before moving on:
Setup
All you need for this project is the Getting Started Kit.
Install Pygame Zero
In order to use Pygame Zero, you first have to install it. You do this in the same way you previously installed the Phidget22 library. Simply navigate to your package manager, search for pgzero and press install!
PyCharm
If you're using PyCharm, select File > Settings > Python Interpreter and use the + symbol to install pgzero.
PyScripter
If you're using PyScripter, select Tools > Tools > Install Packages with pip and enter pgzero.
Create Project Structure
Create the following project structure on your computer in the location of your choice.
Download the following files and place them in the appropriate location.
Finally, create a new python file named phidgets_pygame.py and save it in the same location
Write Code (Python)
Copy the code below into phidgets_pygame.py.
#Add Phidgets Library
from Phidget22.Phidget import *
from Phidget22.Devices.DigitalInput import *
import pgzrun
alien = Actor('alien')
alien.pos = 100, 56
WIDTH = 500
HEIGHT = alien.height + 20
def draw():
screen.clear()
alien.draw()
def update():
alien.left += 2
if alien.left > WIDTH:
alien.right = 0
def set_alien_hurt():
alien.image = 'alien_hurt'
sounds.eep.play()
def set_alien_normal():
alien.image = 'alien'
#Phidgets Code Start
#Button Event
def onRedButton_StateChange(self, state):
if(state):
set_alien_hurt()
else:
set_alien_normal()
#Create, Address, Subscribe to Events and Open
redButton = DigitalInput()
redButton.setIsHubPortDevice(True)
redButton.setHubPort(0)
redButton.setOnStateChangeHandler(onRedButton_StateChange)
redButton.openWaitForAttachment(1000)
#Phidgets Code End
pgzrun.go()
Run Your Program
When you press the red button, you will hear a sound and the alien sprite will change to an unhappy alien.
Code Review
As you may have noticed, the program above is based on the program from the Introduction to Pygame Zero. The main difference is that the code to handle mouse clicks has been removed. To replace mouse clicks, buttons from your Getting Started Kit are used.
When using buttons with Pygame Zero, it's a good idea to use events. Events will allow you to easily determine when a button has been pushed or released. Polling can also be used, however, extra code will be required.
Practice
- Add new functionality to your program using the green button. When the green button is pressed, the alien should move across the screen twice as fast as normal.