Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: Can't get snake to grow  (Read 1154 times)

0 Members and 1 Guest are viewing this topic.

lukap295

  • Newbie
  • *
  • Posts: 3
    • View Profile
Can't get snake to grow
« on: January 13, 2024, 11:35:59 am »
This question was probably asked here a 1000 times, but I don't really know how would I implement it. I made a circleShape head and a vector of circleShape for a body. I don't understand how would I position them behind the head or how could they follow the head.
#ifndef SNAKE_HPP
#define SNAKE_HPP
#include <SFML/Graphics.hpp>
#include <iostream>
#include <vector>
using namespace std;

class Snake : public sf::Drawable {
public:
        sf::CircleShape head;
        vector<sf::CircleShape> body;
        sf::Vector2f pos;
        sf::Vector2f bodyPos;
        Snake();
        ~Snake();
        virtual void draw(sf::RenderTarget& target, sf::RenderStates states) const;
        void drawSnake();
        void move();
        void grow();
};


#endif
#include "Snake.hpp"
Snake::Snake() {
        pos = sf::Vector2f(0, 0);
}

Snake::~Snake() {

}

void Snake::drawSnake() {
        head.setRadius(12);
        head.setFillColor(sf::Color::Black);
        head.setPosition(400, 300);
}

void Snake::draw(sf::RenderTarget& target, sf::RenderStates states) const {
        target.draw(head);
       
}

void Snake::move() {
        head.move(pos);
   
}

void Snake::grow() {
    sf::CircleShape part;
}
If anyone has some advice I would appreciate it. This is my first time using SFML.

Hapax

  • Hero Member
  • *****
  • Posts: 3379
  • My number of posts is shown in hexadecimal.
    • View Profile
    • Links
Re: Can't get snake to grow
« Reply #1 on: January 13, 2024, 10:47:45 pm »
I will assume the body has the part nearest the head first in the vector but you can do it in the other direction as well but this would need to be adjusted to fit.

To move the body:
remove the last item in the vector,
copy head's and insert it at the front of the vector.

You can do this before updating the head to its new position.

If there is no body, don't try to move it.

If the body grows, just don't remove the last item when moving.
Selba Ward -SFML drawables
Cheese Map -Drawable Layered Tile Map
Kairos -Timing Library
Grambol
 *Hapaxia Links*