Prerequisites
This project assumes you are familiar with the following
Setup
All you need for this project is the Getting Started Kit.
What is pynput?
pynput is a Python library that makes it incredibly easy to control and monitor input devices such as your mouse and keyboard. With pynput, you can press keys on your keyboard, or move your mouse, all from your Python program!
Install pynput
In order to use pynput, 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 pynput and press install!
PyCharm
If you're using PyCharm, select File > Settings > Python Interpreter and use the + symbol to install pynput.
PyScripter
If you're using PyScripter, select Tools > Tools > Install Packages with pip and enter pynput.
Write code (Python)
Copy the code below into a new Python project. If you need a reminder of how to do this, revisit the Getting Started Course.
#Add Phidgets Library
from Phidget22.Phidget import *
from Phidget22.Devices.DigitalInput import *
from pynput.keyboard import Key, Controller
import time
#Event
def onRedButton_StateChange(self, state):
#If the button is pushed, simulate a spacebar press to make the dino jump!
if(state):
keyboard.press(Key.space)
keyboard.release(Key.space)
#Create
keyboard = Controller() #this is from the pynput library
redButton = DigitalInput()
#Address
redButton.setIsHubPortDevice(True)
redButton.setHubPort(0)
#Subscribe to Events
redButton.setOnStateChangeHandler(onRedButton_StateChange)
#Open
redButton.openWaitForAttachment(1000)
#Keep program running
while(True):
time.sleep(0.15)
Run Your Program
Navigate to the dinogame, you can do this in a few ways:
- Go to https://chromedino.com/
- If you're using Chrome, paste chrome://dino into your search bar and press enter
Click on the dinosaur and then use your red button to start playing!
Practice
- Try using a different Phidget to control the game. For example, you could use a distance sensing Phidget and jump when your hand is hovering over the sensor at a certain height.
- Try controlling your mouse with pynput and Phidgets. Get started here