Last active
March 9, 2019 23:15
-
-
Save hrldcpr/abd5747878d8d51c16f7b4af94de4749 to your computer and use it in GitHub Desktop.
read from a joystick device that blocks when held in the same direction, to control a character walking, using asyncio
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import asyncio | |
import aiofiles # third party package, install from pip | |
# bytes outputted by the imaginary joystick device: | |
CENTER = b'x' | |
NORTH = b'n' | |
EAST = b'e' | |
SOUTH = b's' | |
WEST = b'w' | |
VELOCITIES = { | |
CENTER: (0, 0), | |
NORTH: (0, 1), | |
EAST: (1, 0), | |
SOUTH: (0, -1), | |
WEST: (-1, 0) | |
} | |
DT = 0.1 # timestep | |
class Walker: | |
def __init__(self): | |
self.direction = CENTER | |
self.x = 0 | |
self.y = 0 | |
walker = Walker() | |
async def read_joystick(): | |
async with aiofiles.open('/dev/input/joystick', 'rb') as f: | |
while True: | |
walker.direction = await f.read(1) | |
async def walk(): | |
while True: | |
print('I’m at x={} y={}'.format(walker.x, walker.y)) | |
vx, vy = VELOCITIES[walker.direction] | |
walker.x += vx * DT | |
walker.y += vy * DT | |
await asyncio.sleep(DT) | |
async def main(): | |
await asyncio.gather( | |
read_joystick(), | |
walk() | |
) | |
loop = asyncio.get_event_loop() # in python ≥3.7, just use asyncio.run(main()) | |
loop.run_until_complete(main()) | |
loop.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment