我有两个不同的类:TextBasedGame 和IntroductionChoices。 IntroductionChoices 做出所有决定,而 TextBasedGame 基本上只是打印故事(它是带有 main 方法的)。
我想知道的是,如果用户做出错误的选择,如何让游戏结束。 在这种情况下,如果用户输入“Take down the group.”,则会显示一条消息并且游戏结束。就我而言,在 main 方法中,它会继续进行。如何停止游戏运行?
我想我可以以某种方式在主方法中检查是否从IntroductionChoices返回“GAME OVER”并在那里结束游戏。
//Snippet from the main method
System.out.println("What do you do?");
System.out.println(choice.choice1());
System.out.println("Next part...");
//Method choice1 from IntroductionChoices
public static String choice1()
{
Scanner scan = new Scanner(System.in);
System.out.println("Warn her of her shadows.");
System.out.println("Take down the group.");
String decision = scan.next();
if (decision.equalsIgnoreCase("right decision"))
{
System.out.println("some text");
return "some more text in continuation to continue story in main";
}
else if (decision.equalsIgnoreCase("wrong decision"))
{
System.out.println("You creep towards the men, hoping to surprise them from behind.");
System.out.println("Consequence");
return "GAME OVER";
}
else
{
return "That is not a valid response.";
}
}
最佳答案
System.exit(0)
else if (decision.equalsIgnoreCase("wrong decision"))
{
System.out.println("You creep towards the men, hoping to surprise them from behind.");
System.out.println("Consequence");
System.exit(0);
您不需要返回任何东西,它会结束程序。
或
给用户一个选择:
开始新游戏->开始新游戏
退出 ->
System.exit(0)
我还会使用开关来检查用户选项,这样你就不太可能犯错误,而且当选项开始累积时,它会变得更整洁、更快。
您可以创建选项枚举或使用具有有意义名称的最终整数,以便您的代码更易于导航并与用户选项匹配。
关于java - 通过单独的方法结束游戏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37173096/