I’m working on building the classic snake game where the snake eats an apple and grows longer. I’m not using a grid system since i don’t know how to. My question is, how do I make the tails follow the head as they’re appended/attached to the head. Thanks!
I once made a snake game, so I’ll share my solution, although it does require a grid system!
I had a grid, represented by an array of numbers, like so:
0 0 0 0 0 0 0 0 0 0 6 5 4 3 2 1 0 0 7 0 0 0 0 0 0 0 8 0 0 0 0 0 0 0 0 0 0 0 0 0
Here, the 8 represents the head of the snake, and each decreasing non-zero number is part of the tail. We draw the tail of the snake at every non-zero number.
When the head moves to the next position, we make that number an 8, and decrease the value of every non-zero number by 1. Then you can see that the 1 at the end will become 0, so the tail end of the snake will appear to follow the head.
If the snake eats something, then it should grow. In that case, we add 1 to every non-zero number. This means that when the snake next moves, it will be come 1 longer (as the lowest number is now 2). Now the head of the snake is 9, so all new squares will become 9, and reduce to zero from there.
The cool thing with this is that it also makes it easy to check for collisions. If the square you’re moving to is a non-zero number, then the snake has hit it’s tail.
Wow, never looked at it from this angle. Thanks a lot for your assistance. I think I’ll try using a grid and taking this approach.
[quote=“bankix123, post:3, topic:29833”]
I was going to ask exactly the same question and I like steveb’s idea even if I am trying to do that without a grid too.
In the grid it looks like when the snake changes his direction, 5 takes 6’s spot,6 takes 7’s spot …
maybe without the grid you’ll create a variable who gets the CGPoint and the direction of your snake’s head and then ,when each node who represent your tail gets to that CGPoint they change direction too
sorry if it doesn’t sound English , I am trying my best but that’s not my mother tongue