-4

我正在做一个游戏,我有一个射击子弹的功能,一个玩家得到10颗子弹。这就是它现在的样子:

private void Form1_MouseDown(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left)
    {
        bullets.Add(new Bullet(robot.RobotRec));
        Bullet -= 1;// lose a life
        lblBullet.Text = Bullet.ToString();// display number of lives
        checkBullet();
    }
}
private void pnlGame_MouseDown(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left)
    {
        bullets.Add(new Bullet(robot.RobotRec));
        Bullet -= 1;// lose a life
        lblBullet.Text = Bullet.ToString();// display number of lives
        checkBullet();
    }
}
private void checkBullet()
{
    if (Bullet == 0)
    {
        tmrShoot.Enabled = false;

    }
}

但是在子弹数为零后,我仍然可以射击它们,尽管它们不会影响任何东西。好的,他们刚刚通过的分数,但我想禁用子弹图像。所以我在想:你能禁用鼠标按下吗?这样做的代码是什么?

4

1 回答 1

0

您正在检查 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
        }
}
于 2013-08-03T08:54:50.087 回答