您正在检查 Bullet == 0 是否错误,它应该更像这样:
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
if (Bullet == 0)
{
tmrShoot.Enabled = false;
return; //leaves the method and followup code doesnt run
}
if (e.Button == MouseButtons.Left)
{
bullets.Add(new Bullet(robot.RobotRec));
Bullet -= 1;// lose a life
lblBullet.Text = Bullet.ToString();// display number of lives
}
}
private void pnlGame_MouseDown(object sender, MouseEventArgs e)
{
if (Bullet == 0)
{
tmrShoot.Enabled = false;
return; //leaves the method and followup code doesnt run
}
if (e.Button == MouseButtons.Left)
{
bullets.Add(new Bullet(robot.RobotRec));
Bullet -= 1;// lose a life
lblBullet.Text = Bullet.ToString();// display number of lives
}
}
这将防止创建 Bullet 并计算额外的 -1。
您也可以将 MouseDown 事件的整个代码放在一个方法中以减少代码,如下所示:
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
FireBullet(e);
}
private void pnlGame_MouseDown(object sender, MouseEventArgs e)
{
FireBullet(e);
}
private void FireBullet(MouseEventArgs e)
{
if (Bullet == 0)
{
tmrShoot.Enabled = false;
return; //leaves the method and followup code doesnt run
}
if (e.Button == MouseButtons.Left)
{
bullets.Add(new Bullet(robot.RobotRec));
Bullet -= 1;// lose a life
lblBullet.Text = Bullet.ToString();// display number of lives
}
}
或者在 Form1 和您的 pnlGame 上注册相同的 MouseDown 事件,如下所示:
//In FormLoad
Form1.MouseDown += FireBullet_MouseDown;
pnlGame.MouseDown += FireBullet_MouseDown;
private void FireBullet_MouseDown(object sender, MouseEventArgs e)
{
if (Bullet == 0)
{
tmrShoot.Enabled = false;
return; //leaves the method and followup code doesnt run
}
if (e.Button == MouseButtons.Left)
{
bullets.Add(new Bullet(robot.RobotRec));
Bullet -= 1;// lose a life
lblBullet.Text = Bullet.ToString();// display number of lives
}
}