-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontrols.py
98 lines (78 loc) · 2.41 KB
/
controls.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#!/usr/bin/env python3
# ========================================================================
# controls.py
#
# Description:
#
# pip3 install pygame
#
# Author: Jim Ing
# Date: 2024-09-03
# ========================================================================
import os
import pygame
import time
from config import sense
pygame.init()
# Initialize the joystick
pygame.joystick.init()
# Check for a connected joystick
if pygame.joystick.get_count() > 0:
joystick = pygame.joystick.Joystick(0)
joystick.init()
else:
raise Exception("No joystick found!")
def print_at(x, y, text):
# Move the cursor to the specified position, clear the line, and print the text
print(f"\033[{y};{x}H\033[2K{text}")
def move_pixel(joystick, pos, rotation):
x, y = pos
axis_x = joystick.get_axis(0)
axis_y = joystick.get_axis(1)
# Deadzone to prevent unwanted movements
if abs(axis_x) < 0.1:
axis_x = 0
if abs(axis_y) < 0.1:
axis_y = 0
# Movement based on joystick input
dx = int(round(axis_x))
dy = int(round(axis_y))
print_at(1, 3, f"(dx, dy) = ({dx}, {dy})")
# Update the position
x = (x + dx) % 8
y = (y + dy) % 8
print_at(1, 4, f"(x, y) = ({x}, {y})")
return x, y
# Starting position of the pixel
pos = [4, 4]
# Initial color of the pixel (red)
colors = [[255, 0, 0], [0, 255, 0], [0, 0, 255]]
color_index = 0
color = colors[color_index]
try:
# Clear the screen
os.system('clear')
# Get the current rotation
rotation = sense.rotation
print_at(1, 1, f"Current rotation: {rotation}°")
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
raise KeyboardInterrupt
elif event.type == pygame.JOYBUTTONDOWN:
if event.button == 2: # B button pressed
# Toggle through the colors
color_index = (color_index + 1) % len(colors)
color = colors[color_index]
print_at(1, 2, f"Color changed to: {color}")
# Move the pixel based on joystick input
pos = move_pixel(joystick, pos, rotation)
# Clear the LED matrix
sense.clear()
# Draw the pixel at the new position
sense.set_pixel(pos[0], pos[1], color)
# Delay to make the movement smoother
time.sleep(0.1)
except KeyboardInterrupt:
pygame.quit()
sense.clear()