So I've successfully created a Snake game that functions fine with the exception of one little thing that I don't know how to solve. Let me try to explain.
So the game works 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're moving right, you cannot move left (because then the head would intersect with the body and you'd lose). The same goes for the all the other possible directions. There is a direction variable that specifies the current direction of the snake. So the problem is that when you press the left key, it will check if the direction is set to right and if it is, nothing will happen. But if you were to press the down key and then the left key both within the same interval of time, then the snake will move left and you'll 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 first-hand. Thank you for any help!