I have recently written a snake clone in c#. All is going well, and I'm having a great time working through it and learning. I should mention that although I have been programming for a while, this is my first attempt at a game that includes System.Drawing for the animation, and keyboard movement.
The problem I am having is that when the snake is moving to the right, if I press down the left quickly, to bring the snake down one line and move the opposite direction, my game detects that the snake has collided with itself, and calls the reset method (game over) I have tried adding different conditions to my if statements for key press detection, to no avail. Code is posted below, thanks in advance for any/all help!
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
//Starts the game when the spacebar is pressed.
if (e.KeyData == Keys.Space)
{
timer1.Enabled = true;
lblSpace.Visible = false;
up = false;
down = false;
right = true;
left = false;
}
//Each of my directions is a boolean. up, down, left, right. Here I check to make sure that up
//(the opposite direction) is false before changing the variable for down to true. I believe this
//is where my problem originates.
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;
}
}
If you would like to install the game and try it to get a better understanding of my problem, please visit www.action-bob.com and click "snake" to download and install.
Thanks!

New Topic/Question
Reply


MultiQuote



|