As others have stated, there's no need to create new PictureBox for your villain each time. Below I've moved your Random instance and the villain PictureBox out to Form level (the same place as you existing x and y variables). Next we setup the villain in the Load()
event as these properties don't change. Finally, we use different variables for the random location of the villain so that the player doesn't get changed:
int x, y;
Random r = new Random();
PictureBox villain = new PictureBox();
private void Form1_Load(object sender, EventArgs e)
{
x = 0;
y = 0;
villain.Height = 150;
villain.Width = 150;
villain.SizeMode = PictureBoxSizeMode.Zoom;
villain.Image = Properties.Resources.snitch;
this.Controls.Add(villain);
villain.Hide();
}
private void button1_Click(object sender, EventArgs e)
{
//enable the timer when the start button is clicked
timer1.Enabled = true;
}
private void timer1_Tick(object sender, EventArgs e)
{
//create a random x and y coordinate
int villX = r.Next(1, 500);
int villY = r.Next(1, 500);
villain.Location = new Point(villX, villY);
villain.Show();
if (picPlayer.Bounds.IntersectsWith(villain.Bounds))
{
MessageBox.Show("You won");
villain.Hide();
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…