WindowsForms app - keyEvent doesn't work, where is the problem? - c#

I have little problem with my windowsforms app - its a snake game
Everywhing is ok, but after click "Play Again" button app doesn't see any kay Event (I try debug and put break point in KeyIsDown(object sender, KeyEventArgs e); but it isn't call when I clicked Key
Can you tell me where is a problem?
Full repository (little other version, but still doesn't work) : https://github.com/ldidil/snake-game
Short version of the code:
namespace SnakeGame
{
public partial class Form1 : Form
{
private List<Circle> Snake = new List<Circle>();
private Circle food;
public Form1()
{
InitializeComponent();
new Settings();
DisplayTopScore();
gameTimer.Interval = 1000 / Settings.Speed; //TO DO (change speed lvl)
gameTimer.Tick += UpdateScreen;
gameTimer.Start();
StartGame();
}
private void StartGame()
{
GenerateSnake();
GenerateFood();
}
private void UpdateScreen(object sender, EventArgs e)
{
if (Settings.GameOver == false)
{
if (Input.KeyPress(Keys.Right) && Settings.Direction != Directions.Left)
{
Settings.Direction = Directions.Right;
}
else if (Input.KeyPress(Keys.Left) && Settings.Direction != Directions.Right)
{
Settings.Direction = Directions.Left;
}
else if (Input.KeyPress(Keys.Up) && Settings.Direction != Directions.Down)
{
Settings.Direction = Directions.Up;
}
else if (Input.KeyPress(Keys.Down) && Settings.Direction != Directions.Up)
{
Settings.Direction = Directions.Down;
}
MovePlayer();
}
boardCanvas.Invalidate(); //odśwież plansze
}
private void MovePlayer()
{
for (int i = Snake.Count - 1; i >= 0; i--)
{
if (i == 0)
{
switch (Settings.Direction)
{
case Directions.Right:
Snake[i].X++;
break;
case Directions.Left:
Snake[i].X--;
break;
case Directions.Up:
Snake[i].Y--;
break;
case Directions.Down:
Snake[i].Y++;
break;
}
checkCollision(i);
checkFood();
}
else
{
Snake[i].X = Snake[i - 1].X;
Snake[i].Y = Snake[i - 1].Y;
}
}
}
private void KeyIsDown(object sender, KeyEventArgs e)
{
Input.ChangeState(e.KeyCode, true);
}
private void KeyIsUp(object sender, KeyEventArgs e)
{
Input.ChangeState(e.KeyCode, false);
}
private void Die()
{
topScore.Write();
Settings.GameOver = true;
}
private void UpdateGraphic(object sender, PaintEventArgs e)
{
{
if (!Settings.GameOver)
{
draw(e);
}
else
{ //game over
string gameOver = "Game Over\n" + "Final Score: " + Settings.Points;
endText.Text = gameOver;
endText.Visible = true;
playAgainButton.Visible = true;
exitButton.Visible = true;
}
}
}
private void draw(PaintEventArgs e)
{
for (int i = 0; i < Snake.Count; i++)
{
string location;
if (i == 0)
{
location = (#"..\..\Img\snakeHead.png");
}
else
{
location = (#"..\..\Img\snakeBody.png");
}
var img = new Bitmap(AppDomain.CurrentDomain.BaseDirectory + location);
Rotate(img);
Point p1 = new Point(Snake[i].X *Settings.Width, Snake[i].Y * Settings.Height);
e.Graphics.DrawImage(img, p1);
}
Point p2 = new Point(food.X * Settings.Width, food.Y * Settings.Height);
var appleImage = new Bitmap(AppDomain.CurrentDomain.BaseDirectory + #"..\..\Img\apple.png");
e.Graphics.DrawImage(appleImage, p2);
}
private static void Rotate(Bitmap img)
{
switch (Settings.Direction)
{
case Directions.Right:
break;
case Directions.Left:
img.RotateFlip(RotateFlipType.Rotate180FlipNone);
break;
case Directions.Up:
img.RotateFlip(RotateFlipType.Rotate270FlipNone);
break;
case Directions.Down:
img.RotateFlip(RotateFlipType.Rotate90FlipNone);
break;
}
}
private void playAgainButton_Click(object sender, EventArgs e)
{
endText.Visible = false;
playAgainButton.Visible = false;
exitButton.Visible = false;
new Settings(Form2.nickname, Form2.speed);
Snake.Clear();
StartGame();
}
private void exitButton_Click(object sender, EventArgs e)
{
System.Windows.Forms.Application.Exit();
}
}
}

You need to register your KeyIsDown function as event handler for your control - Control.KeyDown Event:
playAgainButton.KeyDown += KeyIsDown;

Related

Using/adding delegation method and BackgroundWorker to my currently fully working program

I've searched many topics but I can't seem to understand how to replace my existing methods with delegation+timer as I am currently using timer only. Also when adding BackgroundWorker to work with btng that moves the elevator down and opens the doors I get a multi-thread usage error stating that another thread is trying to insertdata in the .accdb where the main thread is recorded. I am adding the code which is not very long but fully working. Could someone give me a hint how to replace my existing methods with delegation and add one or two BackgroundWorkers to help the buttons that move the elevator and still keep the timers, please.
P.S. Do I need to share/change the database connection code in order to make it work with the backgroundworker? I'll add it if necessary. It's another couple of more lines..
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Speech;
using System.Speech.Synthesis;
using System.Data.OleDb;
namespace rewrite
{
public partial class Form1 : Form
{
//variables
int y_up = 63;
int y_down = 376;
int x_door_left_close = 74;
int x_door_left_open = 12;
int x_door_right_close = 139;
int x_door_right_open = 200;
bool go_up = false;
bool go_down = false;
bool arrived_G = false;
bool arrived_1 = false;
//object
SpeechSynthesizer reader = new SpeechSynthesizer();
public Form1()
{
InitializeComponent();
}
private void timerliftdown_Tick(object sender, EventArgs e)
{
if (picturelift.Top <= y_down)
{
picturelift.Top += 1;
}
else
{
timerliftdown.Enabled = false;
btnup.Enabled = true;
btn1.Enabled = true;
btnclose.Enabled = true;
btnopen.Enabled = true;
btndown.BackColor = Color.Red;
btng.BackColor = Color.Red;
dooropendown();
arrived_G = true;
picturelift.Image = global::rewrite.Properties.Resources.Inside_of_the_lift;
displaypanel.Image = global::rewrite.Properties.Resources.G;
displaytop.Image = global::rewrite.Properties.Resources.G;
displaybottom.Image = global::rewrite.Properties.Resources.G;
}
}
private void timerliftup_Tick(object sender, EventArgs e)
{
if (picturelift.Top >= y_up)
{
picturelift.Top -= 1;
}
else
{
timerliftup.Enabled = false;
btndown.Enabled = true;
btng.Enabled = true;
btnclose.Enabled = true;
btnopen.Enabled = true;
btnup.BackColor = Color.Red;
btn1.BackColor = Color.Red;
dooropenup();
arrived_1 = true;
picturelift.Image = global::rewrite.Properties.Resources.Inside_of_the_lift;
displaypanel.Image = global::rewrite.Properties.Resources._1;
displaytop.Image = global::rewrite.Properties.Resources._1;
displaybottom.Image = global::rewrite.Properties.Resources._1;
}
}
private void dooropendown_Tick(object sender, EventArgs e)
{
if (doorleftdown.Left >= x_door_left_open && doorrightdown.Left <= x_door_right_open)
{
doorleftdown.Left -= 1;
doorrightdown.Left += 1;
}
else
{
timerdooropendown.Enabled = false;
}
}
private void timerdoorclosedown_Tick(object sender, EventArgs e)
{
if (doorleftdown.Left <= x_door_left_close && doorrightdown.Left >= x_door_right_close)
{
doorleftdown.Left += 1;
doorrightdown.Left -= 1;
}
else
{
timerdoorclosedown.Enabled = false;
if (go_up == true)
{
picturelift.Image = global::rewrite.Properties.Resources.lift_transparent;
displaypanel.Image = global::rewrite.Properties.Resources.up;
displaytop.Image = global::rewrite.Properties.Resources.up;
displaybottom.Image = global::rewrite.Properties.Resources.up;
reader.Speak("Going up");
timerliftup.Enabled = true;
go_up = false;
}
}
}
private void dooropenup_Tick(object sender, EventArgs e)
{
if (doorleftup.Left >= x_door_left_open && doorrightup.Left <= x_door_right_open)
{
doorleftup.Left -= 1;
doorrightup.Left += 1;
}
else
{
timerdooropenup.Enabled = false;
}
}
private void timerdoorcloseup_Tick(object sender, EventArgs e)
{
if (doorleftup.Left <= x_door_left_close && doorrightup.Left >= x_door_right_close)
{
doorleftup.Left += 1;
doorrightup.Left -= 1;
}
else
{
timerdoorcloseup.Enabled = false;
if (go_down == true)
{
picturelift.Image = global::rewrite.Properties.Resources.lift_transparent;
displaypanel.Image = global::rewrite.Properties.Resources.down;
displaytop.Image = global::rewrite.Properties.Resources.down;
displaybottom.Image = global::rewrite.Properties.Resources.down;
reader.Speak("Going down");
timerliftdown.Enabled = true;
go_down = false;
}
}
}
private void doorclosedown()
{
reader.Speak("doors closing");
insertdata("door closing #Ground floor");
timerdoorclosedown.Enabled = true;
timerdooropenup.Enabled = false;
}
private void dooropendown()
{
reader.Speak("Ground floor, doors opening");
insertdata("doors opening #Ground floor");
timerdoorclosedown.Enabled = false;
timerdooropendown.Enabled = true;
}
private void doorcloseup()
{
reader.Speak("doors closing");
insertdata("Doors closing #First Floor");
timerdoorcloseup.Enabled = true;
timerdooropenup.Enabled = false;
}
private void dooropenup()
{
reader.Speak("First Floor, doors opening");
insertdata("Doors Opening #First Floor");
timerdoorcloseup.Enabled = false;
timerdooropenup.Enabled = true;
}
private void going_up()
{
go_up = true;
doorclosedown();
btng.Enabled = false;
btndown.Enabled = false;
btnclose.Enabled = false;
btnopen.Enabled = false;
arrived_G = false;
insertdata("Lift going up");
}
private void going_down()
{
go_down = true;
doorcloseup();
btn1.Enabled = false;
btnup.Enabled = false;
btnclose.Enabled = false;
btnopen.Enabled = false;
arrived_1 = false;
insertdata("Lift going down");
}
private void btndown_Click(object sender, EventArgs e)
{
btnup.BackColor = Color.DarkCyan;
going_up();
}
private void btnup_Click(object sender, EventArgs e)
{
btndown.BackColor = Color.DarkCyan;
going_down();
}
private void btn1_Click(object sender, EventArgs e)
{
btn1.BackColor = Color.DarkCyan;
going_up();
}
private void btng_Click(object sender, EventArgs e)
{
btng.BackColor = Color.DarkOrange;
going_down();
}
private void btnclose_Click(object sender, EventArgs e)
{
if (arrived_G == true)
{
doorclosedown();
}
else if (arrived_1 == true)
{
doorcloseup();
}
}
private void btnopen_Click(object sender, EventArgs e)
{
if (arrived_G == true)
{
dooropendown();
}
else if (arrived_1 == true)
{
dooropenup();
}
}
private void btnalarm_Click(object sender, EventArgs e)
{
btnalarm.BackColor = Color.Green;
reader.Speak("Emergency Stop. Please exit carefully.");
insertdata("Emergency Stop!");
timerliftdown.Enabled = false;
timerliftup.Enabled = false;
timerdooropendown.Enabled = true;
timerdooropenup.Enabled = true;
displaypanel.Image = global::rewrite.Properties.Resources.alarmbellbutton;
displaytop.Image = global::rewrite.Properties.Resources.alarmbellbutton;
displaybottom.Image = global::rewrite.Properties.Resources.alarmbellbutton;
}

C#- why the backcolor of the button cannot change after the timer reach its condition?

I having problem on the C# Windows Forms.
I have created a timer and a button to act as a timer lamp.
Now I have created the timer and the timer value can get successfully.
But I dont know why the button backcolor cannot change as the setted on the code.
Below is my whole codes.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace TimerLamp
{
public partial class Form1 : Form
{
System.Timers.Timer t;
int s, c, x;
String sec;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
t = new System.Timers.Timer();
t.Interval = 1000; //1s
t.Elapsed += OnTimeEvent;
//t.Enabled = true;
}
private void OnTimeEvent(object sender, System.Timers.ElapsedEventArgs e)
{
s += 1;
sec = s.ToString();
if (s == 23)
{
s = 0;
c += 1;
}
TimerTextBox.Invoke((MethodInvoker)(() => TimerTextBox.Text = s.ToString()));
TimerTextBox.Invoke((MethodInvoker)(() => CounterTextBox.Text = c.ToString()));
sec = s.ToString();
}
private void TurnOnLamp_CheckedChanged(object sender, EventArgs e)
{
if (TurnOnLamp.Checked == true)
{
x = Convert.ToInt16(sec);
if (x >= 0 && x <7)
{
btnLamp.BackColor = Color.Green;
}
if (x > 8 && x < 19)
{
btnLamp.BackColor = Color.Red;
}
else if (x >= 19)
{
btnLamp.BackColor = Color.Green;
}
else
{
btnLamp.BackColor = Color.Red;
}
}
if (TurnOnLamp.Checked == false)
{
btnLamp.BackColor = Color.Red;
}
}
private void btnStart_Click(object sender, EventArgs e)
{
if (btnStart.Text == "Start")
{
t.Start();
if (c >= 30)
{
MessageBox.Show("Limit reached");
return;
}
btnStart.Text = "Stop";
}
else if (btnStart.Text == "Stop")
{
t.Stop();
btnStart.Text = "Start";
}
}
private void btnLamp_Click(object sender, EventArgs e)
{
}
private void TimerTextBox_TextChanged(object sender, EventArgs e)
{
}
private void CounterTextBox_TextChanged(object sender, EventArgs e)
{
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
t.Stop();
Application.DoEvents();
}
}
}
Can someone help me to solve this problem?
When you press the button once, it starts counting in the btnLamp_Click class. And when the checkbox is checked, the button blinks as following code.
using System;
using System.Drawing;
using System.Windows.Forms;
namespace TimerLamp
{
public partial class Form1 : Form
{
Timer t;
int s, c, x;
String sec;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
t = new Timer();
t.Interval = 1000; //1s
t.Tick += OnTimeEvent;
//t.Enabled = true;
}
private void OnTimeEvent(object sender, EventArgs e)
{
s += 1;
sec = s.ToString();
if (s == 9)
{
s = 0;
c += 1;
}
textBox1.Text = "sec = " + sec;
textBox2.Text = "c = " + c;
if (TurnOnLamp.Checked == true)
{
x = s;
if (x == 0) btnLamp.BackColor = Color.Green;
if (x == 2) btnLamp.BackColor = Color.Red;
if (x == 4) btnLamp.BackColor = Color.Blue;
if( x == 6) btnLamp.BackColor = Color.LightCyan;
}
else
{
btnLamp.BackColor = Color.Gray;
}
}
private void btnLamp_Click(object sender, EventArgs e)
{
if (btnLamp.Text == "Start")
{
t.Start();
if (c >= 2)
{
MessageBox.Show("Limit reached");
t.Stop();
}
btnLamp.Text = "Stop";
}
else if (btnLamp.Text == "Stop")
{
t.Stop();
btnLamp.Text = "Start";
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
t.Stop();
Application.DoEvents();
}
}
}

I'm getting error Ambiguity between '¨Form1.score' and ¨Form1.score'

i have int score = 0; under public partial class Form1 : Form and Im getting error in txtscore.Text = "Score: " + score; and score = 0; in private void RestartHry() does someone know why is that? Or know how to fix that bsc i have no idea. ......................................................................................................................................................................................
namespace Projekt_Havlík
{
public partial class Form1 : Form
{
bool vpravo, vlevo;
int rychlost = 8;
int score = 0;
int minul = 0;
Random rndX = new Random();
Random rndY = new Random();
PictureBox minulcoin = new PictureBox();
public Form1()
{
InitializeComponent();
RestartHry();
}
private void MainGameTimerEvent(object sender, EventArgs e)
{
//naprogramovaní textboxů
txtscore.Text = "Score: " + score;
txtminul.Text = "Minul: " + minul;
//změnění postavy při jízdě do leva/prava
if (vlevo == true && player.Left > 0)
{
player.Left -= 12;
player.Image = Properties.Resources.main_left;
}
if (vpravo == true && player.Left + player.Width <this.ClientSize.Width)
{
player.Left += 12;
player.Image = Properties.Resources.main_right;
}
}
private void KeyIsUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Left)
{
vlevo = false;
}
if (e.KeyCode == Keys.Right)
{
vpravo = false;
}
}
private void KeyIsDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Left)
{
vlevo = true;
}
if (e.KeyCode == Keys.Right)
{
vpravo = true;
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void RestartHry()
{
foreach(Control x in this.Controls)
{
if (x is PictureBox &&(string)x.Tag == "coins")
{
x.Top = rndY.Next(80, 300) * -1;
x.Left = rndX.Next(5, this.ClientSize.Width - x.Width);
}
}
player.Left = this.ClientSize.Width / 2;
player.Image = Properties.Resources.main_right;
score = 0;
minul = 0;
rychlost = 8;
vpravo = false;
vlevo = false;
CasovacHry.Start();
}
}
}
Try changing the name of your "score" variable, try calling it like, "myScore", typically if something is ambiguous it is because there are two fields or properties with the same name in assembly references that are not directly specified in the code.

Why does my disableButtons method not work?

I am currently working on a schoolproject for C# and I am making Tic Tac Toe.
I have a little problem though..
My code used to work perfectly fine untill I build in a scoreboard.
I think the scoreboard is overruling the disableButtons.. Before I added the scoreboard it worked perfectly fine..
Can someone look at my code and tell me what's wrong?
It's supposed to work like this:
Play, if there is a winner, disable buttons. Please help me out!
Edit: I don't know why my namespace is in this textfield..
namespace Tic_Tac_Toe
{
public partial class Form1 : Form
{
bool turn = true; //true = x en false = o
int turn_count = 0;
static String player1, player2;
public Form1()
{
InitializeComponent();
}
public static void setPlayerName(String n1, String n2)
{
player1 = n1;
player2 = n2;
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
{
MessageBox.Show("Gemaakt door Luca Fraser", "About");
}
private void button_click(object sender, EventArgs e)
{
Button b = (Button)sender;
if (turn)
b.Text = "X";
else
b.Text = "O";
turn = !turn;
b.Enabled = false;
turn_count++;
checkForWinner();
if (turn_count % 2 == 0)
{
lblTurn.Text = player1 + " is aan de beurt";
}
else
{
lblTurn.Text = player2 + " is aan de beurt";
}
}
private void checkForWinner()
{
bool thereIsWinner = false;
//Horizontaal checken
if((btnA1.Text == btnA2.Text) && (btnA2.Text == btnA3.Text) && (!btnA1.Enabled))
thereIsWinner = true;
else if((btnB1.Text == btnB2.Text) && (btnB2.Text == btnB3.Text) && (!btnB1.Enabled))
thereIsWinner = true;
else if((btnC1.Text == btnC2.Text) && (btnC2.Text == btnC3.Text) && (!btnC1.Enabled))
thereIsWinner = true;
//Verticaal checken
if ((btnA1.Text == btnB1.Text) && (btnB1.Text == btnC1.Text) && (!btnA1.Enabled))
thereIsWinner = true;
else if ((btnA2.Text == btnB2.Text) && (btnB2.Text == btnC2.Text) && (!btnA2.Enabled))
thereIsWinner = true;
else if ((btnA3.Text == btnB3.Text) && (btnB3.Text == btnC3.Text) && (!btnA3.Enabled))
thereIsWinner = true;
//Diagonaal checken
if ((btnA1.Text == btnB2.Text) && (btnB2.Text == btnC3.Text) && (!btnA1.Enabled))
thereIsWinner = true;
else if ((btnA3.Text == btnB2.Text) && (btnB2.Text == btnC1.Text) && (!btnC1.Enabled))
thereIsWinner = true;
if (thereIsWinner)
{
disableButtons();
String winner = "";
if (turn)
{
winner = player2;
lblO.Text = (Int32.Parse(lblO.Text) + 1).ToString();
}
else
{
winner = player1;
lblX.Text = (Int32.Parse(lblX.Text) + 1).ToString();
}
MessageBox.Show(winner + " wins!");
}
else
{
if (turn_count == 9)
{
lblDraw.Text = (Int32.Parse(lblDraw.Text) + 1).ToString();
MessageBox.Show("It's a draw!");
}
}
}
private void disableButtons()
{
try
{
foreach (Control c in Controls)
{
Button b = (Button)c;
b.Enabled = false;
}
}
catch { }
}
private void newGameToolStripMenuItem_Click(object sender, EventArgs e)
{
turn = true;
turn_count = 0;
foreach (Control c in Controls)
{
try
{
Button b = (Button)c;
b.Enabled = true;
b.Text = "";
}
catch { }
}
}
private void Form1_Load(object sender, EventArgs e)
{
Form2 formtwo = new Form2();
formtwo.ShowDialog();
lblXcount.Text = player1;
lblOcount.Text = player2;
lblTurn.Text = player1 + " is aan de beurt";
}
private void mouse_enter(object sender, EventArgs e)
{
Button b = (Button)sender;
if (b.Enabled)
{
if (turn)
{
b.Text = "X";
}
else
b.Text = "O";
}
}
private void mouse_leave(object sender, EventArgs e)
{
Button b = (Button)sender;
if (b.Enabled)
{
b.Text = "";
}
}
private void resetWinCountToolStripMenuItem_Click(object sender, EventArgs e)
{
lblO.Text = "0";
lblX.Text = "0";
lblDraw.Text = "0";
}
private void lblOcount_Click(object sender, EventArgs e)
{
}
private void lblOcount_TextChanged(object sender, EventArgs e)
{
}
}
}
Here:
private void disableButtons()
{
try
{
foreach (Control c in Controls)
{
Button b = (Button)c;
b.Enabled = false;
}
}
catch { }
}
When you iterate over a control that is not a Button, you have an exception and the loop ends.
You can try with this:
foreach (Control c in Controls)
{
Button b = c as Button;
if(b != null)
b.Enabled = false;
}
Your existing code tries to parse every control to Button, if it fails and throws exception. You catch it and nothing happens.
Try this code and get only Buttons to disable:
foreach (Button btn in this.Controls.OfType<Button>())
{
btn.Enabled = false;
}
A suggestion: Comment the catch block code while you're developing, because its easy to debug when and where exception occurs.
private void disableButtons()
{
try
{
foreach (Control c in Controls)
{
Button b = c as Button;
if(b != null)
b.Enabled = false;
}
}
catch (Exception e)
{
Console.Writeline(e.ToString());
}
}
You need to check if the control is a button otherwise you will cause an exception to be thrown.
This is a prime example about why it is a BAD idea to swallow exceptions. If you had reported or logged the exception the problem would have been apparent.

Keys do not work while using Keys.Down (Or up, left, right)

I am a beginner at C# (C Sharp) and I couldn't figure out why my Arrow keys would not work. Can anyone help me? Note: I am a beginner, I have been working at this for a while now and I can't figure it out. I have tried researching it with no luck, I hope I don't bother you. When I try and move it it doesn't work.
Here is my Form1
public partial class Form1 : Form
{
Graphics paper;
Snake snake = new Snake();
bool left = false;
bool right = false;
bool down = false;
bool up = false;
public Form1()
{
InitializeComponent();
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
paper = e.Graphics;
snake.drawSnake(paper);
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
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.Right && left == false)
{
down = false;
up = false;
right = true;
left = false;
}
if (e.KeyData == Keys.Left && right == false)
{
down = false;
up = false;
right = false;
left = true;
}
}
private void timer1_Tick(object sender, EventArgs e)
{
if (down) { snake.moveDown(); }
if (up) { snake.moveUp(); }
if (right) { snake.moveRight(); }
if (left) { snake.moveLeft(); }
this.Invalidate();
}
}
}
Here is my Snake class if you need it.
{
public Snake()
{
snakeRec = new Rectangle[3];
brush = new SolidBrush(Color.Blue);
x = 20;
y = 0;
width = 10;
height = 10;
for(int i = 0; i < snakeRec.Length; i++)
{
snakeRec[i] = new Rectangle(x, y, width, height);
x -= 10;
}
}
public void drawSnake(Graphics paper)
{
foreach (Rectangle rec in snakeRec)
{
paper.FillRectangle(brush, rec);
}
}
public void drawSnake()
{
for (int i = snakeRec.Length - 1; i > 0; i--)
{
snakeRec[i] = snakeRec[i - 1];
}
}
public void moveDown()
{
drawSnake();
snakeRec[0].Y += 10;
}
public void moveUp()
{
drawSnake();
snakeRec[0].Y -= 10;
}
public void moveRight()
{
drawSnake();
snakeRec[0].X += 10;
}
public void moveLeft()
{
drawSnake();
snakeRec[0].X -= 10;
}
}
}
I tried your code and it works well, so this is the only thing I can think of:
private void Form1_Load(object sender, EventArgs e)
{
timer1.Enabled = true;
}
Make sure that big guy is enabled.
Don't hold on to the Graphics from the Paint() event like that. Just pass e.Graphics directly to your Draw() method like this:
private void Form1_Paint(object sender, PaintEventArgs e)
{
snake.drawSnake(e.Graphics);
}
Also, make sure the Paint() event of the Form is wired up. Select the Form. Now click the "Lightning" Bolt" icon in the Properties Pane (bottom right by default). Find the Paint entry and change the dropdown to the right to "Form1_Paint".

Categories

Resources