• Create Account

## [C++] Snake movement problem

Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

8 replies to this topic

### #1TickingHands  Members

152
Like
0Likes
Like

Posted 19 February 2013 - 06:49 PM

Okay I feel really stupid... I've been trying to create a Snake clone. Right now I'm just doing it in the console with a number grid - though it'll be easily be turned to graphics with SFML. Just trying to get the basics done before graphics.

Anyway...okay I was trying to do the snake with a linked list(Which I've never used before). Moves around just fine. Except I must be creating it incorrectly or something. Because I cannot seem to grab the end of the snake's coordinates. It continually thinks it's the same - and I want them in order to make it empty when the end moves.

I know I'm sure I'm doing plenty of unnecessary things. My brains just been fried and I think I know what it is, but just can't solve it. Ready for a brain replacement.

Code:

snake.h

#include <iostream>

#include "grid.h"

class Snake
{
public:
Snake();

enum Direction
{
UP,
DOWN,
LEFT,
RIGHT,
};

void createSnake(Grid &grid);
void move( Direction direct );
void grow();

int getPosX();
int getPosY();

...

private:

int mPosX;
int mPosY;
int mDirection;
int mEndX;
int mEndY;

int getEndX();
int getEndY();

void moveNode( Snake *link, int x, int y );

Snake *next;
...
};


snake.cpp

void Snake::createSnake(Grid &grid)
{
mGrid = &grid;

for( int i = 0; i < 2; i++ )
{
{
}
}

}

int Snake::getEndX()
{
while ( this->link->next != 0 )
{
std::cout << "X: " << this->link->mPosX << std::endl;
}
}

int Snake::getEndY()
{
while ( this->link->next != 0 )
{
}
}

void Snake::move( Direction direct )
{
{
}
else if( head->mDirection == RIGHT )
else if( head->mDirection == UP )
else if( head->mDirection == DOWN )

}

void Snake::moveNode( Snake *link, int x, int y )
{
int tempX, tempY = 0;
mEndX = getEndX();
mEndY = getEndY();
std::cout << std::endl << std::endl << "EndX: " << mEndX << " EndY: " << mEndY << std::endl << std::endl;

//{
mGrid->setCell(mGrid->EMPTY, mEndX, mEndY);
{
}
//}
}


In Console:

http://imgur.com/DhN8kiv

http://imgur.com/8bLSoHw

### #2Khatharr  Members

7718
Like
0Likes
Like

Posted 19 February 2013 - 08:11 PM

This is difficult to understand. May I suggest that you either make use of the dequeue STL class or else implement a dequeue class of your own? The class name 'Snake' suggests a class that will manage the snake but it seems to be a class for managing a single segment of the snake.

The way I would do this, avoiding STL:

A 'SnakeNode' POD struct, implementing a doubly linked node for storing the snake's body segments. The members would be two node pointers, prev and next, and a pointer to a payload struct or class.

A SnakeNode root_node and SnakeNode tail_node. Neither of these would hold a payload. At start the root's next would point to the tail and the tail's prev would point to the root.

A 'Snake' class, containing the mentioned nodes and methods for acting on the snake as a whole.

Node insertion:

SnakeNode* node = new SnakeNode;
node->prev = &root_node;
node->next = root_node.next;
root_node.next->prev = node;
root_node.next = node;

First node retrieval:

SnakeNode* node = root_node.next;
if(node == &tail_node) {node = NULL;}
return node;

Last node retrieval:

SnakeNode* node = tail_node.prev;
if(node == &root_node) {node = NULL;}
return node;

//get node using retrieval function
node->prev->next = node->next;
node->next->prev = node->prev;
node->next = NULL;
node->prev = NULL;
//if destroying node then delete payload and then delete node

It's not clear how you're drawing but it may be worth considering that your problem may be from drawing rather than your snake. Does 'Grid' simulate and draw the board?

Edited by Khatharr, 19 February 2013 - 08:15 PM.

void hurrrrrrrr() {__asm sub [ebp+4],5;}

There are ten kinds of people in this world: those who understand binary and those who don't.

### #3TickingHands  Members

152
Like
0Likes
Like

Posted 19 February 2013 - 08:50 PM

I had never heard of the deque class, but it does sound interesting.
And yeah, my code does look a tad confusing huh? I didn't originally intend for the snake class to just be one node or look like that...accidentally evolved into it, err devolved.

As to a the Node's, what do you mean a payload? To hold what sort of information, the coordinates and things like that? How would it retrieve it - I'm sorry just a tad confused about it. I'll try to puzzle it out, like I said brain isn't working.
And I've never done a doubly linked list, just single. Hence further confusion.

And in your instance, the snake will grow from the inside out ( inserting in the middle ) ?

So the SnakeNode struct would simply be:

struct SnakeNode
{
SnakeNode *prev;
SnakeNode *next;
}
SnakeNode *root_node = new SnakeNode;
SnakeNode *tail_node = new SnakeNode;

Most of my confusion was how to correctly pass the head's( or root ) coordinates to the rest of the list, and the tail knowing where it was in order to delete behind it AND either save the node next to last or save the coordinates for where the head turns.

Also yes, Grid is the class that draws the board - it isn't an error in the drawing. ( Also fyi, the snake starts off with 3 nodes, first move to the left it's still 3, second move to the left it starts growing, etc )

Edited by TickingHands, 19 February 2013 - 09:07 PM.

### #4Khatharr  Members

7718
Like
0Likes
Like

Posted 20 February 2013 - 12:39 AM

As to a the Node's, what do you mean a payload? To hold what sort of information, the coordinates and things like that? How would it retrieve it - I'm sorry just a tad confused about it. I'll try to puzzle it out, like I said brain isn't working.
And I've never done a doubly linked list, just single. Hence further confusion.

A dequeue is the STL version of a doubly linked list. It can be traversed in either direction. The payload is simply a pointer to whatever you want to store, organized into a struct or class. Whatever information a segment needs, make a struct to hold it all, then create an instance of that to act as the payload for a new node. For instance, if you're storing an x coordinate in your payload you could refer to it as node->payload->x.

And in your instance, the snake will grow from the inside out ( inserting in the middle ) ?

The head and tail are 'bookend' nodes. They do not store payloads, they only serve as entry points to the list stored between them.
struct SnakeNode {
SnakeNode *prev;
SnakeNode *next;
SnakeSegment* segment; //this is the payload
}
SnakeNode root_node; //using stack objects will give you an error to alert you if you do something wrong and delete a bookend.
SnakeNode tail_node;

Most of my confusion was how to correctly pass the head's( or root ) coordinates to the rest of the list, and the tail knowing where it was in order to delete behind it AND either save the node next to last or save the coordinates for where the head turns.

You may want to simply unlink the last node and insert it to the front of the list and change its coordinates. If your snake segments are interchangeable this will save you some fiddly work.

Also yes, Grid is the class that draws the board - it isn't an error in the drawing. ( Also fyi, the snake starts off with 3 nodes, first move to the left it's still 3, second move to the left it starts growing, etc )

Hmm... Have you run it through the debugger to see what's happening differently on in the second movement?
void hurrrrrrrr() {__asm sub [ebp+4],5;}

There are ten kinds of people in this world: those who understand binary and those who don't.

### #5TickingHands  Members

152
Like
0Likes
Like

Posted 20 February 2013 - 01:11 AM

Ohhh, well I'll see if I can puzzle the deque out. Oh okay, the payload isn't the SnakeNode, it's a SnakeSegment - that makes more sense now.

Hm, didn't think about that - that'd probably be easier if I figure it out. Definitely less fiddly work heh.

No I haven't run it through. I mean you see my getEndX() and getEndY() which grab the last node's X and Y - or at least it should. But in the program it stays the same, and I don't know why. Only works the first time, after that it stays the same.

Thanks.

### #6King Mir  Members

2391
Like
0Likes
Like

Posted 20 February 2013 - 01:16 AM

A dequeue is the STL version of a doubly linked list. It can be traversed in either direction. The payload is simply a pointer to whatever you want to store, organized into a struct or class.

That's incorrect. std::list is a doubly linked list. std::deque is a list of arrays.

But yeah,  std::deque is the best way to go here. or just use std::queue, since that's what you really need. std::queue is a container wrapper that uses deque by default, under the hood.

Edited by King Mir, 20 February 2013 - 01:23 AM.

### #7Khatharr  Members

7718
Like
0Likes
Like

Posted 20 February 2013 - 08:08 PM

That's incorrect. std::list is a doubly linked list. std::deque is a list of arrays.

My bad. That being the case, wouldn't std::list or even std::forward_list be the appropriate container? Random access isn't really necessary for this.
void hurrrrrrrr() {__asm sub [ebp+4],5;}

There are ten kinds of people in this world: those who understand binary and those who don't.

### #8King Mir  Members

2391
Like
2Likes
Like

Posted 20 February 2013 - 09:19 PM

That's incorrect. std::list is a doubly linked list. std::deque is a list of arrays.

My bad. That being the case, wouldn't std::list or even std::forward_list be the appropriate container? Random access isn't really necessary for this.

No for two reasons:

1) List has high overhead for creating and deleting nodes. Each list member in a list has an associated node data, and for relatively small containers, this is a large cost.

2) linked lists have poor cache performance. Nodes can be anywhere in memory, and unlike containers built on arrays, the processor cannot pre-fetch the next or previous node. Traversing a list is very slow. For this reason, even use cases that involve removing an element from the middle of a container can be faster for array based containers, despite the need to do a lot of copying, because the const of finding the element to remove is so high.

Therefore unless there is a need to maintain references to container members when an element is inserted and removed, linked lists should not be used without profiling. They can be slow even on large datasets.

### #9Yrjö P.  Members

1416
Like
0Likes
Like

Posted 21 February 2013 - 12:56 AM

Like King Mir says, this is really easy to handle with a dequeue. Something like this:
// initialize a 4-length snake to these coordinates
dequeue<pair<int,int>> snake{{3,3},{3,4},(4,4},{5,4}};
// possible directions 0-up, 1-right, 2-down, 3-left
unsigned char snake_direction = 0;
// to move the snake one cell forward in current direction
snake.emplace_back(snake.back().first+{0,1,0,-1}[snake_direction],
snake.back().second+{1,0,-1,0}[snake_direction]);
snake.pop_front();
And since we're using a standard container, it's convenient to use standard algorithms. Stuff like checking collisions against the snake's own body only takes a line or two of code. I think about 20 more lines of code would take care of both wall and self-collisions, randomly spawning pellets for the snake to eat, and growing the snake.

Edited by Stroppy Katamari, 21 February 2013 - 01:08 AM.

Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.