这是我的代码:
public partial class Form1 : Form
{
Invader monster; // Invader is the name of the class
Random rand = new Random();
PictureBox[] pb = new PictureBox[5];
private void Spawner()
{
for (int i = 0; i < 5; i++)
{
this.monster = new Invader();
this.pb[i] = new PictureBox();
this.pb[i].Name = "pb" + i.ToString();
this.pb[i].Location = new Point(rand.Next(10, 300), monster.LocY);
this.pb[i].BackgroundImageLayout = ImageLayout.Stretch;
this.pb[i].BackgroundImage = Image.FromFile(@"Path");
this.pb[i].BackColor = Color.Transparent;
this.pb[i].Size = new System.Drawing.Size(40, 30);
this.Controls.Add(this.pb[i]);
this.pb[i].Click += this.Form1_Click;
}
}
private void Form1_Click(object sender, EventArgs e)
{
PictureBox currentpicturebox = (PictureBox)sender;
this.monster.HealthDown();
if (this.monster.Health == 0)
{
currentpicturebox.Dispose();
}
}
和我的班级:
class Invader
{
// Fields
private int health;
// Properties
public int Health
{
get { return this.health; }
}
// Constructor
public Invader()
{
this.health = 5;
}
// Methods
public void HealthDown()
{
this.health -= 1;
}
让我说我点击1张图片框4次,然后点击另一张1次。使用此代码,最后点击的图片框将被处理掉。关于如何解决这个问题的任何想法?
答案 0 :(得分:0)
您的Invader monster
是Form1的实例变量,在for循环内的方法Spawner()
中,您每次都会重新分配它:{{1}}
基本上当你点击一个图片框(并不是什么)时,this.monster = new Invader();
方法会发生每次你的最后一个怪物,它会让它的健康状况下降,而不是假想的。
为了解决这个问题,你可以:
这是一个例子:
Form1_Click