user3151588 user3151588 - 3 years ago 76
C# Question

I'm having a bug with my snake game

I'm making a Snake game on C#, but I'm having a glitch with my keys.

I'm following the exact code found here. http://codesmesh.com/snake-game-in-c/
The error that I get is that... for example if I was going down, if I pressed right and up at the EXACT same time, where i basically press it together, the snake goes up and walks into its own body, killing itself.

This is my keydown section in my code.

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
//Space is just to restart the form.
if (e.KeyData == Keys.Space)
{
timer1.Enabled = true;
codesmeshlabel.Text= "";
spaceBarLabel.Text = "";
down = false;
up = false;
left = false;
right = true;
}

if (e.KeyData == Keys.Down && up == false)
{
down = true;
up = false;
right = false;
left = false;
}

if (e.KeyData == Keys.Up && down == false)
{
down = false;
up = true;
right = false;
left = false;
}

if (e.KeyData == Keys.Left && right == false)
{
down = false;
up = false;
right = false;
left = true;
}

if (e.KeyData == Keys.Right && left == false)
{
down = false;
up = false;
right = true;
left = false;
}
}

Answer Source

This sounds like you are changing the direction your snake is traveling to "right", and then setting it to "up" before the snake moves again.

Somewhere in your code I assume you have a game loop that updates the screen every (however long). To prevent this from happening you would need to change your design so that after your game has accepted a direction change (key.left/right/up/down) it waits until AFTER the screen has been updated once to accept a second direction change. This should fix your bug :)

As m.t.bennett pointed out another option would be to check each keypress to see if it is the opposite direction of current travel, and if so ignore it. Could be more elegant.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download