New coder here & still learning, but moving along well enough to ask a question here I have been unable to locate an answer to on my own or searching this & other forums.
I am making a snake like game in PyGame, but instead of up, down, left, right, you will be steering the snake kind of like a car where UP += speed increase, DOWN -= speed decrease, and left, right will turn the head left/right == the actual facing direction of the snake head. So far it works quite well, but after running the speed up and tapping the left/right arrows quickly, then slowing down some and again still tapping the arrows apparently too quickly the snake head will reverse into it's own body instead of turning twice quickly around and running reverse parallel to it's original direction.
I did discover buffering the input by running it through a set(), which helps a little.
Also, I am using a mechanical gaming keyboard, so not sure if that is part of the blame.
Hoping someone else may have experienced this or can suggest an alternative buffering setup?
Here's a code snippet for review;
`scr_x, scr_y = 800, 600
screen = pygame.display.set_mode((scr_x, scr_y))
clock = pygame.time.Clock()
key_press_buffer = set()
snake_speed = 3
while running:
if direction == '':
calc_dir()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
elif event.type == pygame.KEYDOWN:
if event.key in valid_keys:
key_press_buffer.add(event.key)
if pygame.K_UP in key_press_buffer:
snake_speed = min(snake_speed + 3, 15)
elif pygame.K_DOWN in key_press_buffer:
snake_speed = max(snake_speed - 3, 3)
elif pygame.K_LEFT in key_press_buffer:
if direction == 'UP':
direction = 'LEFT'
elif direction == 'DOWN':
direction = 'RIGHT'
elif direction == 'RIGHT':
direction = 'UP'
elif direction == 'LEFT':
direction = 'DOWN'
elif pygame.K_RIGHT in key_press_buffer:
if direction == 'UP':
direction = 'RIGHT'
elif direction == 'DOWN':
direction = 'LEFT'
elif direction == 'LEFT':
direction = 'UP'
elif direction == 'RIGHT':
direction = 'DOWN'
elif event.type == pygame.KEYUP:
key_press_buffer.discard(event.key)
if direction == 'UP':
snake_position[1] -= 20
if direction == 'DOWN':
snake_position[1] += 20
if direction == 'LEFT':
snake_position[0] -= 20
if direction == 'RIGHT':
snake_position[0] += 20
# (other code here ...)
pygame.display.flip()
clock.tick(snake_speed)
pygame.quit()
exit()`
I tried using the key_press_buffer.add(event.key) to store the key inputs in a set, then checking the set before returning the response, which did help a little bit, and there was another option to setup a delay_counter of 1 through an if statement: then immediately followed by delay_conter -=1 but that was sooooo slow I had to remove it due to a crazy amount of input lag. Other than that I spent over an hour searching forums and even resorted to asking the Bing CoPilot ... but I'm still stuck with slowing myself down instead of finding a new coding way to prevent my snake from eating its self.