# Movement problem in snake game

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

## Recommended Posts

I am in the process of making a classic snake game but I have a problem with the movement.

If the snake goes up it normally won't react if you press down. But if it goes up and then I hit right(or left) and then quickly hit down the program isn't able to render it but apparently it recognizes the change of direction so the snake goes down. Same goes for every other direction.

What can I do to fix this?

 void CSnake::Event(SDL_Event &amp;event){ if (SDL_KEYDOWN) switch (event.key.keysym.sym){ case SDLK_UP: if (dir!=DOWN){ yVel = -20; xVel = 0; dir = UP; } break; case SDLK_DOWN: if (dir!=UP){ yVel = 20; xVel = 0; dir = DOWN; } break; case SDLK_LEFT: if (dir!=RIGHT){ xVel = -20; yVel = 0; dir=LEFT; } break; case SDLK_RIGHT: if (dir!=LEFT){ xVel = 20; yVel = 0; dir=RIGHT; } break; } } void CSnake::movement(){ if (t_MoveTime <= (SDL_GetTicks()-t_SnakeStarted)){ SDL_Rect front; iSnake = snake.begin(); front.x = (*iSnake).x + xVel; front.y = (*iSnake).y + yVel; snake.push_front(front); snake.pop_back(); t_SnakeStarted = SDL_GetTicks(); } }  Edited by parinho7

##### Share on other sites
Hey,

I think you must only change your snake current direction only when it has at least moved one square of the new direction (If your snake game is moving square by square).

Maybe have a currentDirection and lastDirection variable. You use the current direction to do your movement, and once at least one movement was made in the new direction you do lastDirection = currentDirection.

Then you allow changing the currentDirection only if currentDirection = lastDirection AND is either one of them is not equal to the direction you don't allow (For exemple, going from up to down).

OR

if your game is somewhat "TIck based" (like the original Snake) only allow one direction change per tick. There would be one draw by tick so you couldn't go from up to down without at least going left of right for a tick.

##### Share on other sites

if your game is somewhat "TIck based" (like the original Snake) only allow one direction change per tick. There would be one draw by tick so you couldn't go from up to down without at least going left of right for a tick.

YES! thank you, problem solved!!! Edited by parinho7