C++ has the Standard Template Library. I'm not too experienced with it myself, but I am pretty sure it includes a class to implement a queue.
as for the direction, I would just use an enum for the directions (up, down, left, right), and update the head's new position based on the state of a flag that keeps track of the current direction.
(if flag is set to up, subtract from X, etc). I would then copy the positions down the queue and redraw for each cycle, with each position in the queue representing a segment of the snake's body.
When the snake increases its length, I would push a container onto the queue that is initialized to the new position of the head.
As for collision detection, I would check for a condition where the position of the head is equal to the position of any other part of the snake's body.
This is all off the top of my head, so some of it might not make sense. If you need any further help, I can try my best to clarify.
*Edit* heh, looks like my help isn't needed after all.
Snake game
Quote:Original post by Extrarius
A queue is a data structure that would make such operations easy. I believe C++ has one but I'm not sure on the details.
You're absolutely right, it's inside queue, and it's called std::queue.
Personally I would do this by storing the coordinates at which the snake exists. And since you (presumably) want the snake to die when it touches itself I would store in each tile a bool which indicates whether the snake is there; flag it as true when the snake enters the tile and flag it as false when the snake enters the tile.
So roughly you might have:
class Snake {std::queue<Tile> mTiles;void UpdatePosition(Tile nextTile){ Tile t; mTiles.pop(t); t.UnflagSnake(); if(nextTile.FlaggedForSnake()) CrashBurnAndDie(); else { nextTile.FlagSnake(); mTiles.push(nextTile); }}}
Don't you have to include a header file to use the queue class?
I know you have to include the vector header when using vectors.
I just looked, and there is a header for queue.
I know you have to include the vector header when using vectors.
I just looked, and there is a header for queue.
He might as well just use a queue, since it's perfect for the task and there's on in the standard library. Oh, and you're quite right, KingFred -- you have to #include<queue> to use a queue (intuitive, ain't it?).
yeah, I could see how queue would be perfect for the task. push the head, pop the tail. Yes, it is intuitive if you've used STL before. If you haven't you may not be aware you need to include a header.
[Edited by - KindFred on November 24, 2004 1:34:38 PM]
[Edited by - KindFred on November 24, 2004 1:34:38 PM]
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement