Need help fixing a bug in the snake game
So, I have successfully created a Snake game that works great except for one little thing I don't know how to solve. Let me try to explain.
So, the game runs on a timer, where each tick of the timer means moving each block of the snake in the specified direction. It works so that if you move to the right, you cannot move to the left (because then the head will intersect with the body and you will lose). The same goes for all other possible directions. There is a directional variable that determines the current direction of the snake. So the problem is that when you press the left key, it checks for the correct direction to the right, and if so, nothing happens. But if you had to press the down key and then the left key for the same amount of time, then the snake moves to the left and you lose. Here's the code that handles the KeyDown event for the form.
private void frmMain_KeyDown(object sender, KeyEventArgs e)
{
switch (e.KeyData)
{
case Keys.Enter:
if (lblMenu.Visible)
{
lblMenu.Visible = false;
LoadSettings();
gameLoop.Start();
}
break;
case Keys.Space:
if (!lblMenu.Visible)
gameLoop.Enabled = (gameLoop.Enabled) ? false : true;
break;
case Keys.S:
using (frmSettings f = new frmSettings())
{
f.ShowDialog(this);
}
break;
case Keys.Right:
if (direction != Direction.Left)
direction = Direction.Right;
break;
case Keys.Down:
if (direction != Direction.Up)
direction = Direction.Down;
break;
case Keys.Left:
if (direction != Direction.Right)
direction = Direction.Left;
break;
case Keys.Up:
if (direction != Direction.Down)
direction = Direction.Up;
break;
}
}
Here's a download to the game if you want to experience the bug firsthand. Thanks for any help!
source to share
What you have is actually a "function". You want to be able to go down, then left, but you do this over the course of the timer, causing an "error".
This means you have to wait to change direction. Your code will look like this:
if (direction != Direction.Right)
intendedDirection = Direction.Left;
...
OnTimerTick()
{
...
direction = intendedDirection;
}
Now you can press as many keys as you want (they are valid), the latter will act on a timer that will allow the next key press (left) to work properly.
source to share