[C++] Snake movement problem

Started by
7 comments, last by Stroppy Katamari 11 years, 2 months ago

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 *head;
	Snake *link;
        ...
};


snake.cpp


void Snake::createSnake(Grid &grid)
{
	mGrid = &grid;
	head = new Snake;
	head->next = 0;
	head->mPosX = 10;
	head->mPosY = 10;
	mGrid->setCell(grid.SNAKE, head->mPosX, head->mPosY);

	for( int i = 0; i < 2; i++ )
	{
		this->link = head;
		if( this->link != 0 )
		{
			this->link->next = new Snake;
			this->link = this->link->next;
			this->link->next = 0;
			this->link->mPosX = 11 + i;
			this->link->mPosY = 10;
			mGrid->setCell(mGrid->SNAKE, this->link->mPosX, this->link->mPosY);
		}
	}
	
}

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

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

void Snake::move( Direction direct )
{
	head->mDirection = direct;
	int origX = head->getPosX();
	int origY = head->getPosY();
	if( head->mDirection == LEFT )
	{
		head->mPosX -= 1;
	}
	else if( head->mDirection == RIGHT )
		head->mPosX += 1;
	else if( head->mDirection == UP )
		head->mPosY -= 1;
	else if( head->mDirection == DOWN )
		head->mPosY += 1;

	mGrid->setCell(mGrid->SNAKE, head->mPosX, head->mPosY);

	this->link = head;
	this->link = this->link->next;

	moveNode( this->link, origX, origY );
}

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;

	//if( this->link->next != 0 )
	//{
		tempX = this->link->mPosX;
		tempY = this->link->mPosY;
		this->link->mPosX = x;
		this->link->mPosY = y;
		mGrid->setCell(mGrid->SNAKE, this->link->mPosX, link->mPosY);
		mGrid->setCell(mGrid->EMPTY, mEndX, mEndY);
		if( this->link->next != 0 )
		{
			this->link = this->link->next;
			moveNode( this->link, tempX, tempY );
		}
	//}
	this->link->mPosX = tempX;
	this->link->mPosY = tempY;
	mGrid->setCell(mGrid->SNAKE, this->link->mPosX, link->mPosY);
}

In Console:

http://imgur.com/DhN8kiv

http://imgur.com/8bLSoHw

Advertisement
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->payload = whatever;
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;

Node unlink:

//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?
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.

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;
    //Payload? To a Snake class?
}
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 )

Thanks for the reply.

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.

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.

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.

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.

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.

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.

This topic is closed to new replies.

Advertisement