0

I have been trying to recreate snake in pygame for fun but the list won't update for the rectangle positions, anyone know what I'm doing wrong with this code???

I passed in a list within a list (snake_body) to a function with this code however the list within a list doesn't change its integer values

if event.key == pygame.K_UP or pygame.K_w:
    snake_body[0][1] -= 50

if event.key == pygame.K_DOWN or pygame.K_s:
    snake_body[0][1] += 50

if event.key == pygame.K_RIGHT or pygame.K_d:
    snake_body[0][0] += 50

if event.key == pygame.K_LEFT or pygame.K_a:
    snake_body[0][0] -= 50

    print(snake_body)

>>> [[370, 50, 30, 30]]

but the up output should be >>> [[320, 50, 30, 30]]

anything would be helpful as I have been stuck on this for a day and it is no longer fun.

  • 4
    There's not enough here for us to tell what is wrong. What happens when you run your code.. do the if statements get triggered? Is snake_body being printed? Do you get any errors? What is [[int, int, int, int]]? Why do you have a list of types? – JeffUK Jan 29 '22 at 20:45
  • 2
    might wanna take a look at how to ask a good question: [How to ask](https://stackoverflow.com/help/how-to-ask) and more specifically [create a minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) – AntiMatterDynamite Jan 29 '22 at 20:51
  • Maybe it can be useful to give us a real sample of the list and what you expect as the code's output. – Happy Ahmad Jan 29 '22 at 20:58

1 Answers1

2

See How to test multiple variables for equality against a single value?. A condition like

if event.key == pygame.K_UP or pygame.K_w:

does not do what you expect. It always evaluates to True. The correct syntax is:

if event.key == pygame.K_UP or event.key == pygame.K_w:
Rabbid76
  • 202,892
  • 27
  • 131
  • 174