I'm trying to automatically detect any sequence that is being formed by joystick but I am not able to do so. Let me try explaining what I mean to say - suppose with the joystick i perform following operatings (left, right, forward, right) then I only do right , after that I perform safe operation like (left, right, forward, right) and again this (left, right, forward, right) so I have repeated that 3 time and two times consecutively. SO I want that my code should detect it automatically if any pattern is getting performed and print the "Repetitive task".
import pygame
# initialize pygame library
pygame.init()
# initialize joystick
pygame.joystick.init()
# get number of joysticks
joystick_count = pygame.joystick.get_count()
# check if any joysticks are available
if joystick_count == 0:
print("No joysticks found")
pygame.quit()
quit()
else:
# initialize the first joystick
joystick = pygame.joystick.Joystick(0)
joystick.init()
# set the previous positions to an empty list
prev_positions = [(joystick.get_axis(0), joystick.get_axis(1))]
# define the maximum length of the sequence
max_length = 10
# define the minimum movement threshold
threshold = 0.1
# main loop
while True:
# get current position of joystick
position = (joystick.get_axis(0), joystick.get_axis(1))
# check if current position is different from previous position
if abs(position[0] - prev_positions[-1][0]) > threshold or abs(position[1] - prev_positions[-1][1]) > threshold:
#print("Joystick moved:", position)
# add the current position to the list of previous positions
prev_positions.append(position)
# check if the list of previous positions is longer than the maximum length
if len(prev_positions) > max_length:
prev_positions.pop(0)
# check if the current sequence of positions is repeating
repeat_length = 1
for i in range(len(prev_positions) - 2, -1, -1):
if prev_positions[i:i + repeat_length] == prev_positions[-repeat_length:]:
repeat_length += 1
else:
break
if repeat_length >= 4:
print("It is a repetitive task.")
# check if the quit event is triggered
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()