Collision detection only works when a key is being pressed - c#

void snake_PreviewKeyDown_1(object sender, PreviewKeyDownEventArgs e)
{
e.IsInputKey = true;
if(e.KeyCode == Keys.Up)
{
up_ispressed = true;
down_ispressed = false;
left_ispressed = false;
right_ispressed = false;
snake.Top = snake.Top + i;
}
if (e.KeyCode == Keys.Down)
{
up_ispressed = false;
down_ispressed = true;
left_ispressed = false;
right_ispressed = false;
snake.Top = snake.Top + j;
}
if (e.KeyCode == Keys.Left)
{
up_ispressed = false;
down_ispressed = false;
left_ispressed = true;
right_ispressed = false;
snake.Left = snake.Left + i;
}
if (e.KeyCode == Keys.Right)
{
up_ispressed = false;
down_ispressed = false;
left_ispressed = false;
right_ispressed = true;
snake.Left = snake.Left + j;
}
//if 'snake' touches the 'apple', change its size, speed and give the player 100 points
if (snake.Bounds.IntersectsWith(apple.Bounds))
{
GenerateApple();
points = points + 100;
i = i + -1;
j = j + 1;
k = k + 10;
snake.Size = new Size(k,k);
this.Text = "Score: " + points;
}
}
Here is my code. As you can see, I detect the collision between 'snake' and 'apple' using Bounds.IntersectsWith() but the collision is only detected when a key is being pressed. How can I solve this issue?
Sorry for the bad code. I am a begginer.

Related

clearing pictureboxes from a list array

im trying to clear the picturebox that are created from a list in my game once it has ended, i have cleared the list but the picturebox still display i have tried using the below code in a timer that is enable upon the game ending
foreach (Invader ship in invaders)
{
ship.isDisposed = true;
ship.ship.Dispose();
}
this doesnt do anyhting tho so does anyone have any ideas how i could do this?
public partial class Form1 : Form
{
private List<Invader> invaders = new List<Invader>();
private List<Laser> lasers = new List<Laser>();
int invaderNumber = 0;
int score = 0;
public Form1()
{
InitializeComponent();
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
// moves the spacefighter up when clicked
if (e.KeyCode.Equals(Keys.W))
{
if (SpaceFighter.Top > 0)
{
SpaceFighter.Top = SpaceFighter.Top - 30;
}
}
// moves the spacefighter left when clicked
if (e.KeyCode.Equals(Keys.A))
{
if (SpaceFighter.Left > 0)
{
SpaceFighter.Left = SpaceFighter.Left - 10;
}
}
// moves the spacefighter right when clicked
if (e.KeyCode.Equals(Keys.D))
{
if (SpaceFighter.Right < this.Width)
{
SpaceFighter.Left = SpaceFighter.Left + 10;
}
}
// moves the spacefighter down when clicked
if (e.KeyCode.Equals(Keys.S))
{
if (SpaceFighter.Bottom < this.Height - 10)
{
SpaceFighter.Top = SpaceFighter.Top + 10;
}
}
// fires lasers when clicked
if (e.KeyCode.Equals(Keys.Space))
{
System.Media.SoundPlayer LaserSound = new System.Media.SoundPlayer(Properties.Resources.LaserSound);
LaserSound.Play();
this.lasers.Add(new Laser(this, SpaceFighter));
}
}
private void timer1_Tick(object sender, EventArgs e)
{
// introduces 10 enemies once the game starts
if (invaderNumber > 9 )
{
timer1.Enabled = false;
timer2.Enabled = true;
}
else
{
invaders.Add(new Invader(this));
invaderNumber++;
}
}
private void timer2_Tick(object sender, EventArgs e)
{
// detects if the enemy ship interacts with the spacefighter and ends the game if this happens
invaders.RemoveAll(ship => ship.isDisposed);
foreach(Invader ship in invaders)
{
ship.MoveInvader(this);
if (SpaceFighter.Bounds.IntersectsWith(ship.ship.Bounds))
{
// plays sound for exploding ship
System.Media.SoundPlayer SpaceshipSound = new System.Media.SoundPlayer(Properties.Resources.SpaceshipSound);
SpaceshipSound.Play();
timer2.Enabled = false;
timer3.Enabled = false;
timer4.Enabled = true;
invaders.Clear();
listBox1.Items.Add(lblScore.Text); // adds score to listbox
MessageBox.Show("You Lose!");
return;
}
}
// detects if an enemy ship his hit by a laser
lasers.RemoveAll(laser => laser.isDisposed);
foreach (Laser laser in lasers)
{
laser.MoveLaser(this);
foreach (Invader ship in invaders)
{
if (laser.laser.Bounds.IntersectsWith(ship.ship.Bounds))
{
laser.isDisposed = true;
laser.laser.Dispose();
ship.isDisposed = true;
ship.ship.Dispose(); // makes the ship dissappear once its shot
System.Media.SoundPlayer ShipSound = new System.Media.SoundPlayer(Properties.Resources.EnemySound); // sound for the enemy ship being destroyed
ShipSound.Play();
score = score + 2; //adds 2 points to players score if enemy is hit
lblScore.Text = score.ToString(); //updates the score label
invaderNumber = invaderNumber - 1;
}
}
}
foreach (Invader ship in invaders)
{
if (ship.ship.Top > 485)
{
ship.isDisposed = true;
ship.ship.Dispose();
invaderNumber = invaderNumber - 1;
}
}
}
private void btnStart_Click(object sender, EventArgs e)
{
timer1.Enabled = true; // activates timer 1
timer3.Enabled = true; // activates timer 3
btnStart.Visible = false; // hidesthe start button
lblScore.Text = "0"; // updates score label to 0 for start of game
lblName.Text = txtName.Text; // updates the name label to user nput
txtName.Visible = false; // hides the textbox
lblEnterName.Visible = false; // hides the enter name label
SpaceFighter.Visible = true; // makes the spacefighter visible
}
// code for the countdown clock
int m = 2;
int s = 60;
private void timer3_Tick(object sender, EventArgs e)
{
if(s > 0)
{
s = s - 1;
lblTimer.Text = "0" + m.ToString() + ":" + s.ToString();
}
if(s == 0)
{
s = 59;
m = m - 1;
lblTimer.Text = "0" + m.ToString() + ":" + s.ToString();
}
if(s < 10)
{
s = s - 1;
lblTimer.Text = "0" + m.ToString() + ":" + "0" + s.ToString();
}
if (m < 0)
{
listBox1.Items.Add(lblScore.Text + " " + lblName.Text); // adds score to list box
timer4.Enabled = true;
invaders.Clear();
}
if (m >= 0)
{
timer1.Enabled = true;
}
}
private void Form1_Load(object sender, EventArgs e)
{
SpaceFighter.Visible = false; // hides the space fighter until the player starts the game
listBox1.Visible = false; // keepsscore table hidden
lblScoreTable.Visible = false; // score table lables kept hidden
lblNameTable.Visible = false;
btnMenu.Visible = false;
}
private void Timer4_Tick(object sender, EventArgs e)
{
lblTimer.Text = "00:00"; // sets game timer to 00:00
timer3.Enabled = false; // disbales timer 3
listBox1.Visible = true; // makes score card visible
listBox1.Sorted = true;
lblNameTable.Visible = true; // displays score table labels
lblScoreTable.Visible = true;
btnMenu.Visible = true;
foreach (Invader ship in invaders)
{
ship.isDisposed = true;
ship.ship.Dispose();
}
}
private void BtnMenu_Click(object sender, EventArgs e)
{
// resets game to its original state in order to play another game
m = 2;
s = 60;
lblTimer.Text = "03:00";
timer1.Enabled = false;
timer2.Enabled = false;
timer3.Enabled = false;
timer4.Enabled = false;
listBox1.Visible = false;
lblNameTable.Visible = false;
lblScoreTable.Visible = false;
lblEnterName.Visible = true;
txtName.Visible = true;
SpaceFighter.Visible = false;
btnMenu.Visible = false;
btnStart.Visible = true;
score = 0;
lblScore.Text = "Score";
lblName.Text = "Name";
txtName.Clear();
invaderNumber = 0;
SpaceFighter.Top = 380;
SpaceFighter.Left = 400;
}
}
this would do:
foreach (var control in this.Controls)
{
var pb = control as PictureBox;
if (pb != null)
{
if (pb.Name != "SpaceFighter")
{
pb.Dispose();
this.Controls.Remove(pb);
}
}
}
for the listbox sorting:
using System.Collections;
ArrayList Sorting = new ArrayList();
foreach (var o in listBox1.Items)
{
Sorting.Add(o);
}
Sorting.Sort();
Sorting.Reverse();
listBox1.Items.Clear();
foreach (var o in Sorting)
{
listBox1.Items.Add(o);
}

C# Windows Form snake

I have this simple snake game, my problem is that the tails wont add when it reaches three tails.
namespace Snake
{
public partial class Form1 : Form
{
bool left = false, right = false;
bool top = false, down = false;
PictureBox pic = new PictureBox();
List<PictureBox> tails = new List<PictureBox>();
int score = 0;
public Form1()
{
InitializeComponent();
}
private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
if (((e.KeyChar.ToString() == "a") || (e.KeyChar.ToString() == "A"))&&(right == false))
{
right = false;
top = false;
down = false;
left = true;
}
else if (((e.KeyChar.ToString() == "d") || (e.KeyChar.ToString() == "D"))&& (left == false))
{
top = false;
down = false;
left = false;
right = true;
}
else if (((e.KeyChar.ToString() == "w") || (e.KeyChar.ToString() == "W"))&& (down == false))
{
down = false;
left = false;
right = false;
top = true;
}
else if (((e.KeyChar.ToString() == "s") || (e.KeyChar.ToString() == "S"))&& (top == false))
{
top = false;
left = false;
right = false;
down = true;
}
}
private void timer1_Tick(object sender, EventArgs e)
{
//ticks every 1 sec
if (pic.Location == head.Location)
{
score++;
spawnFood();
tails.Add(addTails());
}
sortLocation();
if (right == true)
{
int r = head.Location.X + head.Height;
head.Location = new Point(r, head.Location.Y);
}
else if(left == true)
{
int l = head.Location.X - head.Height;
head.Location = new Point(l, head.Location.Y);
}
else if (top == true)
{
int t = head.Location.Y - head.Height;
head.Location = new Point(head.Location.X, t);
}
else if (down == true)
{
int d = head.Location.Y + head.Height;
head.Location = new Point(head.Location.X,d);
}
txtScore.Text = score.ToString();
}
private void sortLocation()
{
if (tails.Count == 0)
{
}
else
{
for (int i = 1; i < tails.Count; i++)
{
tails[i].Location = tails[i-1].Location;
}
tails[0].Location = head.Location;
}
}
private PictureBox addTails()
{
PictureBox tail = new PictureBox();
tail.Name = "tail" + score.ToString();
tail.BackColor = Color.Black;
tail.Width = 10;
tail.Height = 10;
this.Controls.Add(tail);
return tail;
}
private void spawnFood()
{
Random rnd = new Random();
int rndLocationX = rnd.Next(10, 50);
int rndLocationY = rnd.Next(10, 50);
pic.BackColor = Color.Red;
pic.Height = 10;
pic.Width = 10;
this.Controls.Add(pic);
if (rndLocationX >= 500)
{
rndLocationX -= 10;
}
if (rndLocationY >= 500)
{
rndLocationY -= 10;
}
pic.Location = new Point(rndLocationX*10,rndLocationY*10);
}
private void Form1_Load(object sender, EventArgs e)
{
timer1.Start();
spawnFood();
}
}
}
for (int i = 1; i < tails.Count; i++)
{
tails[i].Location = tails[i+1].Location;
}
tails[0].Location = head.Location;
Are your tails there just stacked so to speak? That's another thought I might be thinking. I changed the tails[i-1] to tails [i+1]. Check if that does the trick.

Wpf Button IsEnabled not working

i have a method that enabling and disabling button in here.My if-else block should do when enter a number to lbDivide the 'öde', '0' and '00' buttons should be active but only activing öde button.How do i solve this ?
öde = make payment
Kişi Sayısı = How many person?
private void Bol_Click(object sender, RoutedEventArgs e)
{
lbDivide.Text = "0";
btnBol.Opacity = 0.5;
btnBol.IsEnabled = false;
lbPayment.Visibility = Visibility.Hidden;
if (lbDivide.Text == "0")
{
btnQr.Opacity = 0.5;
btnQr.IsEnabled = false;
zero.Opacity = 0.2;
zero.IsEnabled = false;
double_zero.IsEnabled = false;
double_zero.Opacity = 0.2;
}
else
{
btnQr.Opacity = 1;
btnQr.IsEnabled = true;
zero.Opacity = 1;
double_zero.Opacity = 1;
zero.IsEnabled = true;
double_zero.IsEnabled = true;
}
I think I know where the error is.
private void Bol_Click(object sender, RoutedEventArgs e)
{
lbDivide.Text = "0"; /// in this line of code you're basically setting lbDivide.text to be 0 every time the button is clicked, so the else condition will never be met.
btnBol.Opacity = 0.5;
btnBol.IsEnabled = false; /// you're basically disabling the button after the first click.
lbPayment.Visibility = Visibility.Hidden;
if (lbDivide.Text == "0")
{
btnQr.Opacity = 0.5;
btnQr.IsEnabled = false;
zero.Opacity = 0.2;
zero.IsEnabled = false;
double_zero.IsEnabled = false;
double_zero.Opacity = 0.2;
}
else
{
btnQr.Opacity = 1;
btnQr.IsEnabled = true;
zero.Opacity = 1;
double_zero.Opacity = 1;
zero.IsEnabled = true;
double_zero.IsEnabled = true;
}
}
change if(lbDivide.Text == "0") by if(lbDivide.Text.Equals("0"))

String value not changing

Hi, I have code that reads and writes to a COM port. When the program reads from the COM port it searches for a string value and puts it in a variable. After it does this, it again listens to the COM port. I need to write to the COM port and read some new data, but I'm not seeing the value has changing to a new value.
Here is my code:
private void timer1_Tick(object sender, EventArgs e)
{
sq = "777";
if (CommunicationManager.myQ.Count != 0)
{
sq = CommunicationManager.myQ.Dequeue().ToString();
textBox1.Text = sq + textBox1.Text;
buffer = Regex.Match(textBox1.Text, #"\
((.+?)\,15,").Groups[1].Value;
}
}
private void button1_Click(object sender, EventArgs e)
{
for (int i = 0; i <= numtst; i++)
{
listView1.Items[i].BackColor = Color.White;
fl[i] = false;
}
nt = 0;
flon = false;
flag[0] = false;
comm.WriteData("AT\r\n");
wait(700);
if (buffer.lenght == 16)
{
flag[0] = true
}
if (flag[0] == true)
{
flon = true;
CommunicationManager.myQ.Clear();
break;
}
}
if (flon == true)
{
listView1.Items[nt].BackColor = Color.LightGreen;
fl[nt] = true;
}
else
{
listView1.Items[nt].BackColor = Color.Red;
if (flag[76] == true)
{
button1.Enabled = true;
button1.BackColor = Color.Red;
button1.Text = "Test ERROR";
return;
}
}
comm.WriteData("ATT\r\n");
wait(3700);
comm.WriteData("AT4\r\n");
nt = 1;
flon = false;
flag[1] = false;
if (buffer == text4.text)
{
flag[1] = true
}
wait(700);
if (flag[1] == true)
{
flon = true;
CommunicationManager.myQ.Clear();
break;
}
if (flag[76] == true)
{
button1.Enabled = true;
return;
}
}
if (flon == true)
{
listView1.Items[nt].BackColor = Color.LightGreen;
fl[nt] = true;
}
else
{
listView1.Items[nt].BackColor = Color.Red;
if (flag[76] == true)
{
button1.Enabled = true;
button1.BackColor = Color.Red;
button1.Text = "Test ERROR";
return;
}
}
in the second part if (buffer == text4.text) i see only first value of the buffer variable.
i checked in the terminal and all commands working good.

How can i prevent form the user to move the point beyond the pictureBox1 borders?

This is all the events and functions in my Form1 what should i do ?
I need to detect the borders/bounds of the pictureBox1 control and stop the mouse move when its touching the borders.
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
label1.Text = e.X.ToString();
label2.Text = e.Y.ToString();
label1.Visible = true;
label2.Visible = true;
label3.Visible = true;
label4.Visible = true;
// find the index that is closest to the current mouse location
MinDist = float.MaxValue;
for (idx = 0; idx < Point_X.Count; ++idx)
{
float dx = Point_X[idx] - e.X;
float dy = Point_Y[idx] - e.Y;
float dist = (float)Math.Sqrt(dx * dx + dy * dy);
if (dist < MinDist)
{
MinDist = dist;
selectedIndex = idx;
}
}
if (MinDist < 5)
{
mouseMove = true;
OriginalX = Point_X[(int)selectedIndex];
OriginalY = Point_Y[(int)selectedIndex];
if (cyclicSelectedIndex.Count() == 2)
{
cyclicSelectedIndex[currentCyclicIndex] = (int)selectedIndex;
currentCyclicIndex++;
if (currentCyclicIndex > 1)
{
currentCyclicIndex = 0;
}
if ((cyclicSelectedIndex[0] == cyclicSelectedIndex[1]) || (cyclicSelectedIndex[0] == -1) || (cyclicSelectedIndex[1] == -1))
{
button2.Enabled = false;
}
else
{
button2.Enabled = true;
}
label13.Text = selectedIndex.ToString();
label13.Visible = true;
label14.Visible = true;
listView1.Items.Add(selectedIndex.ToString()).EnsureVisible();
}
}
}
}
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
if (mouseMove == true)
{
Point NewPoint = e.Location;
Point_X[(int)selectedIndex] = NewPoint.X;
Point_Y[(int)selectedIndex] = NewPoint.Y;
label1.Text = NewPoint.X.ToString();
label2.Text = NewPoint.Y.ToString();
pictureBox1.Refresh();
Point_X[(int)selectedIndex] = Math.Max(pictureBox1.Left, Math.Min(pictureBox1.Right, NewPoint.X));
}
}
private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
if (mouseMove == true)
{
Point NewPoint = e.Location;
Point_X[(int)selectedIndex] = NewPoint.X;
Point_Y[(int)selectedIndex] = NewPoint.Y;
mouseMove = false;
}
}
private void button1_Click(object sender, EventArgs e)
{
halfX = pictureBox1.ClientRectangle.Width / 2;
halfY = pictureBox1.ClientRectangle.Height / 2;
Random rnd = new Random();
offsetX = rnd.Next(-10, 10);
offsetY = rnd.Next(-10, 10);
addPoint(halfX + offsetX, halfY + offsetY);
pictureBox1.Refresh();
numberOfPoints++;
label16.Text = numberOfPoints.ToString();
label16.Visible = true;
label15.Visible = true;
}
private void addPoint(float x , float y)
{
Point_X.Add(x);
Point_Y.Add(y);
label5.Text = x.ToString();
label6.Text = y.ToString();
label5.Visible = true;
label6.Visible = true;
label7.Visible = true;
label8.Visible = true;
}
private void pictureBox1_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
{
Point connectionPointStart;
Point connectionPointEnd;
Graphics g = e.Graphics;
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
SolidBrush brush = new SolidBrush(Color.Red);
Pen p = new Pen(brush);
for (int idx = 0; idx < Point_X.Count; ++idx)
{
Point dPoint = new Point((int)Point_X[idx], (int)Point_Y[idx]);
dPoint.X = dPoint.X - 5; // was - 2
dPoint.Y = dPoint.Y - 5; // was - 2
Rectangle rect = new Rectangle(dPoint, new Size(10, 10));
g.FillEllipse(brush, rect);
}
for (int i = 0; i < connectionStart.Count; i++)
{
int startIndex = connectionStart[i];
int endIndex = connectionEnd[i];
connectionPointStart = new Point((int)Point_X[startIndex], (int)Point_Y[startIndex]);
connectionPointEnd = new Point((int)Point_X[endIndex], (int)Point_Y[endIndex]);
p.Width = 4;
g.DrawLine(p, connectionPointStart, connectionPointEnd);
}
}
private void button2_Click(object sender, EventArgs e)
{
addConnection(cyclicSelectedIndex[0], cyclicSelectedIndex[1]);
pictureBox1.Invalidate();
}
private void addConnection(int i, int j)
{
if (cyclicSelectedIndex[0] == -1)
{
return;
}
if (cyclicSelectedIndex[0] == cyclicSelectedIndex[1])
{
return;
}
if (connectionStart.Count() == 0)
{
connectionStart.Add(i);
connectionEnd.Add(j);
//label12.Text = i.ToString();
//label11.Text = j.ToString();
label12.Text = connectionStart[0].ToString();
label11.Text = connectionEnd[0].ToString();
label9.Visible = true;
label10.Visible = true;
label11.Visible = true;
label12.Visible = true;
return;
}
for (int f = 0; f < connectionStart.Count(); f++)
{
if ((connectionStart[f] == i && connectionEnd[f] == j) || (connectionStart[f] == j && connectionEnd[f] == i)) // this checking dosent work good !
{
button2.Enabled = false;
return;
}
else
{
label12.Text = connectionStart[f].ToString();
label11.Text = connectionEnd[f].ToString();
label9.Visible = true;
label10.Visible = true;
label11.Visible = true;
label12.Visible = true;
}
}
connectionStart.Add(i);
connectionEnd.Add(j);
}
Im not sure how to explain it. But how can i do it ?
Thanks.
When calculating the X value use Math.Max with that and the left boundary of the image, and Min on the right boundary of the image. Do the same with the Y value on the Top and Bottom.
Point_X[(int)selectedIndex] = Math.Max(imageLeft, Math.Min(imageRight, NewPoint.X));
I assume you can determine the left/right/top/bottom of the image?

Categories