您好我正在用c#制作文字冒险游戏。 当我开始游戏时,如果用户想要启动游戏或退出游戏,我希望它显示一个问题。 这就是我的开始。
`Console.WriteLine("Press Space to start the game!");
Console.WriteLine("Press Esc to quit the game!");
if (Console.ReadKey(true).Key == ConsoleKey.Space)
{
"My whole code of the game here"
}
if (Console.ReadKey(true).Key == ConsoleKey.Escape)
{
Don't know what to put here
}`
我还没有找到一种方法来让应用程序(运行代码的cmd.exe)关闭。我找到了一种崩溃方式,但仍然会收到Windows警告消息“已停止工作”。 我发现有人回答这个问题,但我测试过的东西都没有,其中一些是:
`Environment.Exit(0)
Environment.Exit
Application.Exit
this.Close();
return;`
要么没有任何反应,要么我收到消息“已停止工作”。
我要求以某种方式命令以这种方式关闭游戏。 如果有人有一个更好的解决方案来回答问题,我会很高兴,而不是我正在使用的
`if (Console.ReadKey(true).Key == ConsoleKey.Space)`
答案 0 :(得分:1)
我认为你应该使用带有布尔标志的while循环并将所有逻辑放在那里并在每次迭代中扫描按下的键,如果是Escape则将while循环标志设为false,否则继续。
Console.WriteLine("Press Space to start the game!");
Console.WriteLine("Press Esc to quit the game!");
bool isGameClose = false;
while (!isGameClose)
{
ConsoleKey pressedKey = Console.ReadKey(true).Key;
if(pressedKey == ConsoleKey.Spacebar)
{
Console.WriteLine("Game is On");
}
else if(pressedKey == ConsoleKey.Escape)
{
isGameClose = true;
}
}
Console.WriteLine("Game Exited!");