Public Group

# Snake Type Game SDL

This topic is 2335 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hello,

I am just starting out trying to make games in C++. I have some experience with the language but I have never made games or used SDL too much. As a start I took a motion tutorial from http://lazyfoo.net/SDL_tutorials/ and made it into a two player game where random red dots appear and the players race to collect 10. It has collision detection and such which I figure out how to do. After doing this I'm trying to expand it into snakes now not just dots. However I am having problems get the snakes to move correctly. I was able to hack it together somewhat but when changing direction from say right to up the whole snake flips at once instead of moving a section at a time. I think I am missing something conceptually about this. I could do it on a matrix but I dont want to restrict motion to a square matrix

snake.cpp
 Snake::Snake() { pieces.push_back(Dot()); headX = pieces.at(0).getX(); headY = pieces.at(0).getY(); length = 1; }; void Snake::show() { int curX; int curY; for( int i =0; i < length; i++) { curX = pieces.at(i).getX(); curY = pieces.at(i).getY(); apply_surface( curX, curY, dot, screen ); } }; void Snake::handle_input() { pieces.at(0).handle_input(0); for( int i =1; i < length; i++) { int xVel = pieces.at(i-1).getXVelocity(); int yVel = pieces.at(i-1).getYVelocity(); if(yVel < 0 && xVel ==0) pieces.at(i-1).setDirection(0); if(yVel > 0 && xVel ==0) pieces.at(i-1).setDirection(1); if(yVel == 0 && xVel < 0) pieces.at(i-1).setDirection(2); if(yVel == 0 && xVel >0) pieces.at(i-1).setDirection(3); } }; void Snake::move() { pieces.at(0).move(); int previous_x; int previous_y; int previous_xVel; int previous_yVel; for( int i=1; i < length; i++) { previous_x = pieces.at(i-1).getX(); previous_y = pieces.at(i-1).getY(); previous_xVel = pieces.at(i-1).getXVelocity(); previous_yVel = pieces.at(i-1).getYVelocity(); if(previous_xVel != 0 || previous_yVel != 0) { pieces.at(i).setX(previous_x-(2*previous_xVel)); pieces.at(i).setY(previous_y-(2*previous_yVel)); } else { if(pieces.at(i-1).getDirection() == 0) { pieces.at(i).setX(previous_x); pieces.at(i).setY(previous_y+(DOT_HEIGHT)); } else if(pieces.at(i-1).getDirection() ==1) { pieces.at(i).setX(previous_x); pieces.at(i).setY(previous_y-(DOT_HEIGHT)); } else if(pieces.at(i-1).getDirection() ==2) { pieces.at(i).setX(previous_x+DOT_WIDTH); pieces.at(i).setY(previous_y); } else if(pieces.at(i-1).getDirection() ==3) { pieces.at(i).setX(previous_x-DOT_WIDTH); pieces.at(i).setY(previous_y); } else { pieces.at(i).setX(previous_x-(DOT_WIDTH)); pieces.at(i).setY(previous_y-(DOT_HEIGHT)); } } pieces.at(i).setXVelocity(previous_xVel); pieces.at(i).setYVelocity(previous_yVel); } }; Dot Snake::getHead() { return pieces.at(0); }; void Snake::addToSnake() { int x = pieces.at(length-1).getX(); int y = pieces.at(length-1).getY(); int xv = pieces.at(length-1).getXVelocity(); int yv = pieces.at(length-1).getYVelocity(); pieces.push_back(Dot(x-DOT_WIDTH,y,xv,yv)); length++; };

dot.cpp
 Dot::Dot() { //Initialize the offsets x = 0; y = 0; //Initialize the velocity xVel = 0; yVel = 0; radius = DOT_WIDTH/2; } Dot::Dot(int xStart, int yStart) { //Initialize the offsets x = xStart; y = yStart; //Initialize the velocity xVel = 0; yVel = 0; radius = DOT_WIDTH/2; } Dot::Dot(int xStart, int yStart, int xvel, int yvel) { //Initialize the offsets x = xStart; y = yStart; //Initialize the velocity xVel = xvel; yVel = yvel; radius = DOT_WIDTH/2; } void Dot::handle_input(int player) { if(player == 0) { //If a key was pressed if( event.type == SDL_KEYDOWN ) { //Adjust the velocity switch( event.key.keysym.sym ) { case SDLK_UP: yVel -= DOT_HEIGHT / 2; break; case SDLK_DOWN: yVel += DOT_HEIGHT / 2; break; case SDLK_LEFT: xVel -= DOT_WIDTH / 2; break; case SDLK_RIGHT: xVel += DOT_WIDTH / 2; break; } } //If a key was released else if( event.type == SDL_KEYUP ) { //Adjust the velocity switch( event.key.keysym.sym ) { case SDLK_UP: yVel += DOT_HEIGHT / 2; break; case SDLK_DOWN: yVel -= DOT_HEIGHT / 2; break; case SDLK_LEFT: xVel += DOT_WIDTH / 2; break; case SDLK_RIGHT: xVel -= DOT_WIDTH / 2; break; } } } //other color stuff ommitted } void Dot::move() { //Move the dot left or right x+=xVel; //If the dot went too far to the left or right if(x + DOT_WIDTH > SCREEN_WIDTH) x = 0; if(x < 0) x = SCREEN_WIDTH-DOT_WIDTH; //Move the dot up or down y += yVel; //If the dot went too far up or down if(y + DOT_HEIGHT > SCREEN_HEIGHT) y = 0; if(y < 0) y = SCREEN_HEIGHT-DOT_HEIGHT; } void Dot::move(int x_velocity, int y_velocity) { //Move the dot left or right xVel = x_velocity; x+=x_velocity; //If the dot went too far to the left or right if(x + DOT_WIDTH > SCREEN_WIDTH) x = 0; if(x < 0) x = SCREEN_WIDTH-DOT_WIDTH; //Move the dot up or down yVel = y_velocity; y += y_velocity; //If the dot went too far up or down if(y + DOT_HEIGHT > SCREEN_HEIGHT) y = 0; if(y < 0) y = SCREEN_HEIGHT-DOT_HEIGHT; } void Dot::show(int color) { //Show the dot if(color == 0) apply_surface( x, y, dot, screen ); else apply_surface( x, y, blueDot, screen ); } 

main.cpp
 int main( int argc, char* args[] ) { //declarations are ommited //While the user hasn't quit while( quit == false ) { if(gameState == 0) { //Start the frame timer fps.start(); //While there's events to handle while( SDL_PollEvent( &event ) ) { //Handle events for the dot snake1.handle_input(); dotTwo.handle_input(1); //If the user has Xed out the window if( event.type == SDL_QUIT ) { //Quit the program quit = true; } } //collison vector<smallDot> temp = pointDots; for(unsigned int i = 0; i < temp.size();i++) { if(temp.at(i).checkCollision(snake1.getHead())) { temp.erase(temp.begin()+i); snake1.addToSnake(); player1score += DOT_VALUE; } } pointDots = temp; temp.clear(); temp = pointDots; for(unsigned int i = 0; i < temp.size();i++) { if(temp.at(i).checkCollision(dotTwo)) { temp.erase(temp.begin()+i); player2score += DOT_VALUE; } } pointDots = temp; temp.clear(); //status //Move the dot snake1.move(); dotTwo.move(); //Add point dot dotsTimer.update(); if(dotsTimer.check()) { pointDots.push_back(smallDot()); } //Fill the screen white SDL_FillRect( screen, &screen->clip_rect, SDL_MapRGB( screen->format, 0xFF, 0xFF, 0xFF ) ); displayScores(player1score,player2score); //Show the dot on the screen for (unsigned int i = 0; i < pointDots.size(); i++) { //if (pointDots.at(i) == NULL) // continue; // skip NULL objects pointDots.at(i).show(); } snake1.show(); dotTwo.show(1); //Update the screen if( SDL_Flip( screen ) == -1 ) return 1; if( gameOver(player1score,player2score)) gameState = 1; //Cap the frame rate } else if (gameState == 1) { //stuff for winner omitted for length SDL_Flip(screen); } } //Clean up clean_up(); return 0; }

I had to omit stuff for length but the full code and everything if you would like to look at it all is at https://github.com/b...st/Snake%20Game along with all the other file and the visual studio solution

Any help or advice will be greatly appreciated

##### Share on other sites
Try this for moving the snake:

1) Determine the speed the snake moves at: float speed = sqrt(xvel*xvel + yvel*yvel) (This is probably a constant unless the speed can change)
2) For each segment of the snake, starting from the back:
2.1) Get the normalized direction to the next segment : float dx = previous.x - current.x; float dy = previous.y - current.y; dx/=sqrt(dx*dx+dy*dy); dy/=sqrt(dx*dx+dy*dy);
2.2) multiply the direction with the snakes speed: dx*=speed; dy*=speed;
2.3) update the position: current.x+=dx; currenty+=dy
3) For the head do the same as for the previous segments except you use the snakes movement direction rather than the direction to the previous segment.

If you only allow axis aligned movement then you can skip alot of the calculations and use fixed values in some places. (if either dx or dy is 0 then the you can divide the one that isn't 0 with itself to get it normalized rather than doing the sqrt);

##### Share on other sites
Thanks for the quick response! I got a chance to play with it today and see if i could get it working. I limited motion to up down left and right to simplify it to make it work then I will make it more complicated. However, I discovered that it works perfectly only when the velocity is equal to the size of the dot image. The snake segments are twenty pixels by twenty pixels and if the speed is fixed to anything other than 20 such as 10 or 30 the snake displays erratically. In the vertical direction it will look ok expect it will squish together or expand and in the x direction the pieces wobble all over like a fishing lure. Im not sure why this is and am having a hard time figuring it out. Im thinking at has something to do with the way the snake pieces are displayed.

new snake.cpp
//The headers #include "SDL.h" #include "SDL_image.h" #include "constants.h" #include "Dot.h" #include "Snake.h" #include <vector> #include "functions.h" #include "globals.h" Snake::Snake() { pieces.push_back(Dot()); headX = pieces.at(0).getX(); headY = pieces.at(0).getY(); length = 1; }; void Snake::show() { int curX; int curY; for( int i =0; i < length; i++) { curX = pieces.at(i).getX(); curY = pieces.at(i).getY(); apply_surface( curX, curY, dot, screen ); } }; void Snake::handle_input() { pieces.at(0).handle_input(0); }; void Snake::move() { float previous_x; float previous_y; float previous_xVel; float previous_yVel; float dx, dy; float speed; float x ,y; for( int i=(length-1); i >= 1; i--) { previous_x = pieces.at(i-1).getX(); previous_y = pieces.at(i-1).getY(); previous_xVel = pieces.at(i-1).getXVelocity(); previous_yVel = pieces.at(i-1).getYVelocity(); speed = sqrt(previous_xVel*previous_xVel + previous_yVel* previous_yVel); dx = previous_x - pieces.at(i).getX(); dy = previous_y - pieces.at(i).getY(); dx /= sqrt(dx*dx + dy*dy); dy /= sqrt(dx*dx + dy*dy); dx *= speed; dy *= speed; x = pieces.at(i).getX(); pieces.at(i).setX( x+ dx); y = pieces.at(i).getY(); pieces.at(i).setY( y+ dy); pieces.at(i).setXVelocity(previous_xVel); pieces.at(i).setYVelocity(previous_yVel); } pieces.at(0).move(); }; Dot Snake::getHead() { return pieces.at(0); }; void Snake::addToSnake() { int x = pieces.at(length-1).getX(); int y = pieces.at(length-1).getY(); int xv = pieces.at(length-1).getXVelocity(); int yv = pieces.at(length-1).getYVelocity(); pieces.push_back(Dot(x-DOT_WIDTH,y,xv,yv)); length++; };

new dot.cpp
//The headers #include "SDL.h" #include "SDL_image.h" #include "constants.h" #include "Dot.h" #include "functions.h" #include "globals.h" Dot::Dot() { //Initialize the offsets x = 0; y = 0; //Initialize the velocity xVel = 20; yVel = 0; radius = DOT_WIDTH/2; } Dot::Dot(float xStart, float yStart) { //Initialize the offsets x = xStart; y = yStart; //Initialize the velocity xVel = 20; yVel = 0; radius = DOT_WIDTH/2; } Dot::Dot(float xStart, float yStart, float xvel, float yvel) { //Initialize the offsets x = xStart; y = yStart; //Initialize the velocity xVel = xvel; yVel = yvel; radius = DOT_WIDTH/2; } void Dot::handle_input(int player) { if(player == 0) { //If a key was pressed if( event.type == SDL_KEYDOWN ) { //Adjust the velocity switch( event.key.keysym.sym ) { case SDLK_UP: yVel = -20; xVel = 0; break; case SDLK_DOWN: yVel = 20; xVel = 0; break; case SDLK_LEFT: xVel = -20; yVel = 0; break; case SDLK_RIGHT: xVel = 20; yVel = 0; break; } } //If a key was released else if( event.type == SDL_KEYUP ) { ////Adjust the velocity //switch( event.key.keysym.sym ) //{ //case SDLK_UP: yVel += DOT_HEIGHT / 2; break; //case SDLK_DOWN: yVel -= DOT_HEIGHT / 2; break; //case SDLK_LEFT: xVel += DOT_WIDTH / 2; break; //case SDLK_RIGHT: xVel -= DOT_WIDTH / 2; break; //} } } if(player == 1) { //If a key was pressed if( event.type == SDL_KEYDOWN ) { //Adjust the velocity switch( event.key.keysym.sym ) { case SDLK_w: yVel -= DOT_HEIGHT / 2; break; case SDLK_s: yVel += DOT_HEIGHT / 2; break; case SDLK_a: xVel -= DOT_WIDTH / 2; break; case SDLK_d: xVel += DOT_WIDTH / 2; break; } } //If a key was released else if( event.type == SDL_KEYUP ) { //Adjust the velocity switch( event.key.keysym.sym ) { case SDLK_w: yVel += DOT_HEIGHT / 2; break; case SDLK_s: yVel -= DOT_HEIGHT / 2; break; case SDLK_a: xVel += DOT_WIDTH / 2; break; case SDLK_d: xVel -= DOT_WIDTH / 2; break; } } } } void Dot::move() { //Move the dot left or right x+=xVel; ////If the dot went too far to the left or right //if(x + DOT_WIDTH > SCREEN_WIDTH) // x = 0; //if(x < 0) // x = SCREEN_WIDTH-DOT_WIDTH; //Move the dot up or down y += yVel; ////If the dot went too far up or down //if(y + DOT_HEIGHT > SCREEN_HEIGHT) // y = 0; //if(y < 0) // y = SCREEN_HEIGHT-DOT_HEIGHT; } void Dot::move(float x_velocity, float y_velocity) { //Move the dot left or right xVel = x_velocity; x+=x_velocity; ////If the dot went too far to the left or right //if(x + DOT_WIDTH > SCREEN_WIDTH) // x = 0; //if(x < 0) // x = SCREEN_WIDTH-DOT_WIDTH; //Move the dot up or down yVel = y_velocity; y += y_velocity; ////If the dot went too far up or down //if(y + DOT_HEIGHT > SCREEN_HEIGHT) // y = 0; //if(y < 0) // y = SCREEN_HEIGHT-DOT_HEIGHT; } void Dot::show(int color) { //Show the dot if(color == 0) apply_surface( x, y, dot, screen ); else apply_surface( x, y, blueDot, screen ); } float Dot::getX() { return x; } float Dot::getY() { return y; } void Dot::setX(float pos) { x = pos; } void Dot::setY(float pos) { y = pos; } int Dot::getRadius() { return radius; } float Dot::getXVelocity() { return xVel; } float Dot::getYVelocity() { return yVel; } void Dot::setXVelocity(float vel) { xVel = vel; } void Dot::setYVelocity(float vel) { yVel= vel; } void Dot::reset() { xVel = 0; yVel = 0; } int Dot::getDirection() { return direction; } void Dot::setDirection(int dir) { direction = dir; } 

above are the two files that contain almost if not all the changes i made.

##### Share on other sites
if you're not moving in a grid then it is possible for pieces further back to take a different path than the one in front of it (I didn't consider this in my first reply) so it might be easier to let each dot have a queue of positions it should move to, then move the head first:

then your snake has an xvel/yvel, your pieces have one position and a list of positions to move to on future updates , nothing else.

so you get something like this:

 class Snake { //putting code in the class definition to keep things short in the post private: float xvel,yvel; std::vector<Dot> pieces; public: Snake(float x, float y, float xvel, float yvel) { this->xvel=xvel; this->yvel=yvel; pieces.push_back(Dot(x,y)); //create the head } void addToSnake() { float x = pieces[pieces.size()-1].getX(); float y = pieces[pieces.size()-1].getY(); pieces.push_back(Dot(x,y)); for (int i=0;i<5;i++) { //add the same position to the queue 5 times to keep the new piece in place until the rest of the snake has moved away from it. (changing the number here will change the distance between pieces) pieces[pieces.size()-1].addPosition(x,y); } } void move() { for (int i=0;i<pieces.size();i++) { if (i<pieces.size()-1) { //if this piece isn't the last piece we add its position to the queue for the piece behind it. pieces[i+1].addPosition(pieces.getX(),pieces.getY(); } if (i==0) { //This is the head pieces.x+=xvel; pieces.y+=yvel; } else { pieces.moveToNextPosition(); //If its not the head piece the we use the stored positions } } } } class Dot { private: std::queue<float> xPositions; std::queue<float> yPositions; float x,y; public: void addPosition(float x,float y) { xPositions.push_back(x); yPositions.push_back(y); } void moveToNextPosition() { if (xPositions.size()>0 && yPositions.size()>0) { //make sure we got positions in the queue then move this segment to the next one in the queue. x=xPositions.pop_front(); y=yPositions.pop_front(); } } } 

getters, setters, draw functons etc are missing but you should get the idea i think.

##### Share on other sites
Wow it works great now thanks for the new way to do it. Its much easier and works better. Only thing is that since it was queue i had to use pop() and push() instead of pop_front() and push_back(). Now i have to go back and remove all the stuff that remains from my various unsuccessful attempts at making this work. I have one more question thought that is more a display thing. On turning corners there is a white overlap that I assume is background on image of the dot. Is there a simple way to "green screen" the white out of the image so that it displays without corners? Or would i be better of changing the image to have transparency or something using photoshop?

##### Share on other sites

Wow it works great now thanks for the new way to do it. Its much easier and works better. Only thing is that since it was queue i had to use pop() and push() instead of pop_front() and push_back(). Now i have to go back and remove all the stuff that remains from my various unsuccessful attempts at making this work. I have one more question thought that is more a display thing. On turning corners there is a white overlap that I assume is background on image of the dot. Is there a simple way to "green screen" the white out of the image so that it displays without corners? Or would i be better of changing the image to have transparency or something using photoshop?

Both methods work, you can use SDL_SetColorKey to pick one color to become transparant for a given surface:

SDL_SetColorKey(image, SDL_SRCCOLORKEY, SDL_MapRGB(image->format, 255,255,255)); should set white pixels on "image" to transparent.

##### Share on other sites
Somehow I missed that in the documentation. Thanks for the help!

1. 1
2. 2
Rutin
24
3. 3
4. 4
JoeJ
18
5. 5

• 14
• 22
• 11
• 11
• 9
• ### Forum Statistics

• Total Topics
631766
• Total Posts
3002218
×