Skip to content

Instantly share code, notes, and snippets.

@hrldcpr
Last active March 9, 2019 23:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hrldcpr/abd5747878d8d51c16f7b4af94de4749 to your computer and use it in GitHub Desktop.
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
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