1
\$\begingroup\$

I've recently been trying to make a better version of my previous remake of the classic snake game by implementing data encapsulation and abstraction. I also decided to replace my horrible choice of a linked list for holding the snake's tail co-ordinates with the more sensible choice of a deque. Since I am a beginner and I have honestly no clue what is going on (I'd be worried if I did know what I was doing), I would appreciate some assistance with helping me understand what is wrong with my usage of the deque and how I can fix it.

From what I can gather I believe it has something to do with improper usage of constructors, yet I still have not fully grasped the concept of constructors to be able to properly debug it.

SnakePart.h

#ifndef SNAKEPART_H_
#define SNAKEPART_H_

#include <deque>

class SnakePart {
public:
    void advance(int x, int y, bool loose_tail = true);
};

extern std::deque<SnakePart> parts;


#endif /* SNAKEPART_H_ */

SnakePart.cpp

#include "SnakePart.h"

void SnakePart::advance(int x, int y, bool loose_tail) {
        std::deque<SnakePart> parts;
        parts.emplace_front(x, y);

        if(loose_tail)
            parts.pop_back();
}
\$\endgroup\$

1 Answer 1

0
\$\begingroup\$

It looks like you're not referencing the right parts instance. When you do std::deque<SnakePart> parts; in SnakePart::advance you're creating a new instance of the deque. The exported deque you declare in the header file isn't used at all.

You might want to consider the advance being part of the Snake instead of the SnakePart;

Snake.h

#ifndef SNAKE_H_
#define SNAKE_H_

#include<deque>
#include"SnakePart.h"

class Snake
{
private: 
    std::deque<SnakePart> parts;
public:
    Snake(int startX, int startY); 
    void advance(int x, int y, bool loose_tail = true);
};

#endif SNAKE_H_

Snake.cpp

#include "Snake.h"

Snake::Snake(int startX, int startY) {
    advance(startX, startY, false);
}

void Snake::advance(int x, int y, bool loose_tail) {
    parts.push_front(SnakePart(x, y));
    if (loose_tail)
        parts.pop_back();
}

SnakePart.h

#ifndef SNAKEPART_H_
#define SNAKEPART_H_

class SnakePart
{
public:
    const int x;
    const int y;
    SnakePart(int x, int y);
};

#endif SNAKEPART_H_

SnakePart.cpp

#include "SnakePart.h"

SnakePart::SnakePart(int px, int py)
    : x(px), y(py) {
}

That way the SnakePart represents only a part of the snake, and there's no actions on it. The Snake on the other hand is a list of parts, and it can grow by calling advance.

\$\endgroup\$

Not the answer you're looking for? Browse other questions tagged .