Debian Codegraph @

examples/input/joystick.py

raw symbols SCIP
1 import pyglet
2
3 joysticks = pyglet.input.get_joysticks()
4 assert joysticks, 'No joystick device is connected'
5 joystick = joysticks[0]
6 joystick.open()
7
8 window = pyglet.window.Window(width=800, height=800)
9 batch = pyglet.graphics.Batch()
10
11 # Labels
12 pyglet.text.Label("Buttons:", x=15, y=window.height - 25, font_size=14, batch=batch)
13 pyglet.text.Label("D Pad:", x=window.width - 125, y=window.height - 25, font_size=14, batch=batch)
14
15
16 button_labels = []
17 button_shapes = []
18
19 for i in range(len(joystick.buttons)):
20 rows = len(joystick.buttons) // 2
21 y = window.height - 50 - 25 * (i % rows)
22 x = 35 + 60 * (i // rows)
23 label = pyglet.text.Label(f"{i}:", x=x, y=y, font_size=14, anchor_x='right', batch=batch)
24 button_labels.append(label)
25 shape = pyglet.shapes.Rectangle(x + 10, y + 1, 10, 10, color=(255, 0, 0), batch=batch)
26 button_shapes.append(shape)
27
28
29 joystick_rect = pyglet.shapes.Rectangle(window.width // 2, window.height // 2, 10, 10, color=(255, 0, 255), batch=batch)
30 joystick_rect.anchor_position = joystick_rect.width // 2, joystick_rect.height // 2
31 d_pad_rect = pyglet.shapes.Rectangle(window.width - 75, window.height - 100, 10, 10, color=(0, 0, 255), batch=batch)
32
33
34 @window.event
35 def on_draw():
36 window.clear()
37 batch.draw()
38 x = round((.5 * joystick.x + 1), 2) * window.width / 2
39 y = round((-.5 * joystick.y + 1), 2) * window.height / 2
40 rx = (.5 * joystick.rx + 1) * 60
41 ry = (-.5 * joystick.ry + 1) * 60
42 z = joystick.z * 50
43
44 # Axes
45 joystick_rect.position = x, y
46 joystick_rect.anchor_position = joystick_rect.width // 2, joystick_rect.height // 2
47 joystick_rect.width = 10 + rx + z
48 joystick_rect.height = 10 + ry + z
49
50 # Buttons
51 for i in range(len(joystick.buttons)):
52 rect = button_shapes[i]
53 rect.color = (0, 255, 0) if joystick.buttons[i] else (255, 0, 0)
54
55 # Hat
56 d_pad_x = window.width - 100 + joystick.hat_x * 50
57 d_pad_y = window.height - 100 + joystick.hat_y * 50
58 d_pad_rect.position = d_pad_x, d_pad_y
59
60
61 pyglet.app.run()