I have the following problem in my snake game: If the snake is headed right and the player presses keys UP and LEFT in a quick succession, the snake turns left, overruns its body and the game ends, taking it as a collision. How can I prevent the game from taking two commands for changing a direction before the snake moves?
The code where I check which key is pressed follows:
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT and left == False:
right = True
up = False
down = False
elif event.key == pygame.K_LEFT and right == False:
left = True
up = False
down = False
elif event.key == pygame.K_DOWN and up == False:
down = True
right = False
left = False
elif event.key == pygame.K_UP and down == False:
up = True
right = False
left = False
Full code of the project can be found in this Git repository.
To run the code, you need to install the pygame package via pip.