https://www.raspberrypi.org/learning/as ... oystick.md
to work. It crashed at
if event.key == K_DOWN and y < 7:
with the following error:
AttributeError: ‘Event’ object has no attribute ‘key’
I’ve not used pygame before, only the GPIO pins, so thought I would investigate and learn about pygame.
There appeared to be two problems:
1) Each instance of “if event.key ==” needs “pygame.” before the K_name.
2) The whole “if event.key” block of code needs further indentation.
I’ve added quitting via the centre joystick button, turned off the LEDs on quitting and drastically reduced the size the pygame.display black window, which kept getting in the way.
The modified code is below.
It works on my sense HAT driven by a Pi2B and I now know more than I did about pygame.
Code: Select all
# Modified from Astro Pi Guide for Teachers # raspberrypi.org/resources # Tony Goodhew 26 Sept 2015 import pygame from pygame.locals import * from sense_hat import SenseHat pygame.init() pygame.display.set_mode((90,5))#Big enough sense = SenseHat() sense.clear() print("Steer the BLOB with the joystick") print(" * Up, Down, Left or Right *\n") print("Quit with Joystick Centre Button, RETURN or ESC\n") running = True x = 0 y = 0 sense.set_pixel(x, y, 255, 255, 255) while running: for event in pygame.event.get(): if event.type == KEYDOWN: sense.set_pixel(x, y, 0, 0, 0) # Black 0,0,0 means OFF if event.key == pygame.K_DOWN and y < 7: y = y + 1 elif event.key == pygame.K_UP and y > 0: y = y - 1 elif event.key == pygame.K_RIGHT and x < 7: x = x + 1 elif event.key == pygame.K_LEFT and x > 0: x = x - 1 elif event.key == pygame.K_RETURN: running = False sense.clear() print("** BYE from Joystick **") if running: sense.set_pixel(x, y, 255, 255, 255) if event.type == QUIT: running = False sense.clear() print(" ++ BYE from mouse QUIT ++")