Reputation: 67474
I've looked at some examples that build a snake game in javascript and they seem to move the snake with this algorithm:
This gives the effect of the snake moving around. But this only works if the snake is one solid color. I'm trying to make a snake game where each part of the snake is going to be visually different like so:
Pretend the black color is the head and the blue is the tail. The above algorithm wouldn't work for this snake because removing the tail would change the order/color of your "parts". EG: Your tail would no longer be blue, it would become teal.
What algorithm could I use to to move this snake so that its head says black, its tail stays blue, and all the colors in between stay the same order, too?
Upvotes: 2
Views: 1089
Reputation: 17213
You can still use the previous algorithm but store colors separately to the pixels.
Assuming you have a list pixel[0..n]
which contains the x,y coordinates.
You can create another list color[0..n]
.
Lets say the original algorithm adds a first pixel and then removes the last pixel.
your display function might have looked like this:
for i in 0..n:
draw(pixel[i], "red")
Now you simply go:
for i in 0..n:
draw(pixel[i], color[i])
assuming you have a draw
function that takes a pixel
and a color
.
Upvotes: 2
Reputation: 490499
You would use the existing algorithm, but iterate over all cells, filling the cell with the next cell's colour, to give the impression the snake is moving.
You probably have some code that looks like this...
if (this.body.length > this.length) {
var oldPosition = this.body.shift();
World.setCellAt(oldPosition.x, oldPosition.y, 0);
}
this.body.push({
x: this.x,
y: this.y
});
Your loop would look something like...
this.body.forEach(function(piece, index) {
var nextPiece = this.body[index + 1];
if (nextPiece) {
piece.color = nextPiece.color;
}
});
Upvotes: 2