c# - 重新启动游戏而不退出应用程序
问题描述
我做了一个简单的冒险游戏,玩家必须杀死所有的敌人。玩家有一个生命值,如果这个生命值 <= 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();
}
你能解释一下我在哪里犯了错误吗?
解决方案
我在哪里犯错了?
看起来你在这里做了一个:
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()
关闭您的应用程序(当前形式)。
推荐阅读
- .net - 在 Windows 中使用 VS 2017 和在 Mac os 和 Linux 中托管的 .Net 核心应用程序开发
- php - 从 HTML 中的 JSON 对象格式化 PHP 数组
- java - 如何将数据插入到关系实体内部对象中?
- java - 在 Google Dataflow 模板中添加对 JS UDF 的支持
- php - Yii2基本模式不调用main.php
- javascript - 在 es6 中为反应状态添加不推送的行
- angular - 如何在没有应用按钮的情况下使用angular6中的角度材料过滤价格范围
- c - 在c中的两次执行之间故意更改随机内存位置
- java - RestController 中的 Spring RequestMapping 返回 406
- javascript - 在编辑器中上传图片 - 最佳方法?