๐ฏ
Goal for this step Give the snake a body using the perfect container for the job.
1 The body is a std::deque<Cell> , a list that is fast at BOTH ends.
2 The movement trick that powers every Snake ever: each tick push_front(new head) and pop_back() .
3 The middle never moves! Only the ends change, that is why deque (double-ended queue) is the right tool.
4 Draw every segment; make the head brighter.
std::deque<Cell> snake = { {12,12}, {11,12}, {10,12} };
// each tick:
Cell newHead{ snake.front().x + dir.x,
snake.front().y + dir.y };
snake.push_front(newHead);
snake.pop_back(); // remove the tail
// drawing:
sf::RectangleShape seg(sf::Vector2f(18, 18));
for (auto& c : snake) {
seg.setPosition(c.x * 20.f + 1, c.y * 20.f + 1);
seg.setFillColor(&c == &snake.front()
? sf::Color(6, 214, 160) : sf::Color(4, 160, 120));
window.draw(seg);
}
๐ก
Choosing the right container IS the skill here: vector (end-only), deque (both ends), map (lookups). Snake naturally teaches deque.
Move the snake one step using the two-ended trick:
โถ Check My Code
๐ก Hint: The new head is added at the front; the tail is removed from the back.
What happens if you push_front WITHOUT pop_back?
A The snake teleports
B The snake grows by one segment, which is exactly how eating will work!
C A compile error
Check Answer
โ
Correct! Next Step โ