Snake game problem

Hello guys! I want to make snake game but i dont know how to make the body to follow the head so if anyone can explain me or give me example it will be good.
Thank you very much!
you could set the body positions from back to front and then move the head.
Now, I don't know how you store your data but I would have something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
struct Position {
    int x, y;

    Position& operator=(const Position& other) { 
        this->x = other.x;
        this->y = other.y;
        return *this;
    }
};

// snake stores the position of each part of the snake
// snake[0] is the head, the rest are tails
std::vector<Position> snake;

enum Direction { UP, DOWN, LEFT, RIGHT };
void move(Direction dir)
{
    for(int i = snake.size() - 1; i != 0; --i)
        snake[i - 1] = snake[i];
    
    switch(dir)
    {
    case UP: snake[0].y -= 1; break;
    case DOWN: snake[0].y += 1; break;
    case LEFT: snake[0].x -= 1; break;
    case RIGHT: snake[0].x += 1; break;
    }
}


Edit: renamed struct to "Position"
Last edited on
Just in case you are unfamiliar with vector math, Vector2 in Gamer2015's code is just used to store a position. It has nothing to do with std::vector despite the name similarities.
Last edited on
Ok thank you very much for the example. But can you explain more about the code that you showed. Thank you!
P.S Where is vector2 I cant find it?
Last edited on
BadAssPanda wrote:
P.S Where is vector2 I cant find it?

Gamer2015 had originally named the class Vector2 but he later changed the name to Position.
Topic archived. No new replies allowed.