• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
TickingHands

[C++] Snake movement problem

8 posts in this topic

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

 

0

Share this post


Link to post
Share on other sites
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? Edited by Khatharr
0

Share this post


Link to post
Share on other sites

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.

Edited by TickingHands
0

Share this post


Link to post
Share on other sites

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?
0

Share this post


Link to post
Share on other sites

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.

0

Share this post


Link to post
Share on other sites

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
0

Share this post


Link to post
Share on other sites

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.
0

Share this post


Link to post
Share on other sites

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.

2

Share this post


Link to post
Share on other sites
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
0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0