1

ok so i have been playing around with pygame and python and I have already build snake but that was a very weird system and i want to build like a pathfinder for it that can path find around obstacles (the snake body) to the apple but the movement of the body is wonky and i know that sounds stupid since i cant even make snake how am I gonna make a pathfinder but i have done it before so here goes:

the snake will look like this: snake = [[1,0],[0,0]]

the direction is just stored in a tuple: direction = (xmov = 1,ymov = 0)

time += 1
if time > 30:
    time = 0
    snakeindex = len(snake)-1
    snakeindex will be one
    while snakeindex > 0:
        this activates once and as far as it know it works
        snake[snakeindex] = snake[snakeindex-1]
        snakeindex -= 1
        the snake will end up like  this: [[1,0],[1,0]]
    but then here:
    snake[0][0] += direction[0]
    snake[0][1] += direction[1]
    the snake will then look like this: [[2,0],[2,0]]
ludo
  • 11
  • 2

1 Answers1

1

Python optimization is messy sometimes for mutable objects like lists,dictionaries etc. Your snake parts is just one part, and references to this part. You shouldn't do thing like:

a = [1,2]
b = a
# Now you might think there's to arrays
# But it's one array, and b is just a reference to a.
# If you change b or a both changes.
a[0] = 9
print(a, b)
# This will print out [9,2] and [9,2]

Use .copy() to actually copy list:

snake[snakeindex] = snake[snakeindex-1].copy()
LazyBum Q
  • 257
  • 4
  • 12