Skip to content
← Back to Community
Strange bug
Profile icon
Nathcat

Hi,
I am writing a program that allows you to play Snake in a Tkinter window, however I have encountered an error.
When I try to update the Snakes position by setting every body parts position to the position of the next body part in the list, where the end of the list is the head of the snake, and then update the position of the head based on the direction the snake is going, the position of the body part behind the head becomes identical to the head, even after the head's position has been changed.
I may not have explained that very well, so heres an example to clarify what I mean.

the positions of the snake's body parts are:
[[0, 0], [1, 0], [2, 0]]
and the list of the snake's body parts is:
["-", "-", "O"]
where "O" is the head.

When the program updates the snakes position, it updates the position of all body parts EXCEPT THE HEAD:
[[1, 0], [2, 0], [2, 0]]

If the direction is "E", add 1 to head[0]:
[[1, 0], [2, 0], [3, 0]]
If the direction is "N", subtract 1 from head[1]:
[[1, 0], [2, 0], [2, -1]]
And so on...

However, when the program changes the position of the head, the position of the body part behind the head becomes identical to the head:

body parts updated EXCEPT FOR THE HEAD:
[[1, 0], [2, 0], [2, 0]]
Head updated (direction="E"):
[[1, 0], [3, 0], [3, 0]]

This results in the body part behind the head disappearing as it is replaced by the head, the last body part then suffers the same fate, although I think that is a result of this problem occurring and will be fixed along with this problem.

Here is the code for the snake object:

class Snake: def __init__(self): self.body = ["-", "-", "O"] # [x, y] self.positions = [[0, 0], [1, 0], [2, 0]] self.direction = "E" def update_positions(self): head_index = len(self.positions) - 1 print(self.positions) for x in range(0, len(self.positions) - 1): self.positions[x] = self.positions[x + 1] print(self.positions) if self.direction == "E": self.positions[head_index][0] += 1 elif self.direction == "W": self.positions[head_index][0] -= 1 elif self.direction == "N": self.positions[head_index][1] -= 1 else: self.positions[head_index][1] += 1 print(self.positions)

And the output:

[[0, 0], [1, 0], [2, 0]] [[1, 0], [2, 0], [2, 0]] [[1, 0], [3, 0], [3, 0]]

Thanks for any help you can give me! :P

Voters
Profile icon
Nathcat
Comments
hotnewtop
Profile icon
Nathcat

Just in case anyone finds this helpful, I think the issue was that the pieces became object references, so when the head updated, the piece before it changed as well, because they referenced the same object.

Profile icon
InvisibleOne

Couldn't you use a for loop to remove one from every part of the list?

Profile icon
Nathcat

@InvisibleOne Yeah I just tried pretty much the same thing and somehow it managed to remove one from the head position rather than the one behind the head. The other parts of the list are fine, it's the second to last item thats the problem.