首页 > 解决方案 > 重新启动游戏而不退出应用程序

问题描述

我做了一个简单的冒险游戏,玩家必须杀死所有的敌人。玩家有一个生命值,如果这个生命值 <= 0 游戏结束,然后显示游戏菜单(有开始按钮,退出按钮,重新开始按钮)。如果游戏结束并且玩家选择重新开始,我希望游戏从头开始。实际上,我在 Form with game 中有类似的东西

private void checkHitPoints(int playerHitPoints)
{
    if (game.PlayerHitPoints <= 0)
    {
        MessageBox.Show("You have been killed", "Opsss");
        menu.VisibleRestart();
        menu.ShowDialog();
    }
}

在带有菜单的表单中是这样的

private void restartButton_Click(object sender, EventArgs e)
        {
            this.Close();
            Dungeons dungeons = new Dungeons();
        }

如果我按下restartButton,我会尝试调用构造函数,但不幸的是它不起作用。此外,带有游戏的主类的构造函数看起来像这样

public Dungeons()
        {
            InitializeComponent();
            this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint |
                ControlStyles.OptimizedDoubleBuffer, true);
            player30.Visible = true;
            CenterToScreen();
            this.Show();
            menu.ShowDialog();
        }

你能解释一下我在哪里犯了错误吗?

标签: c#

解决方案


我在哪里犯错了?

看起来你在这里做了一个:

this.Close();
Dungeons dungeons = new Dungeons();

看看这段代码!您创建变量并在函数结束dungeons后立即处理它。restartButton_Click您最好将dungeons变量移出函数范围,如下所示:

Dungeons dungeons;
private void restartButton_Click(object sender, EventArgs e)
{
    dungeons = new Dungeons();
}

this.Close()关闭您的应用程序(当前形式)。


推荐阅读