java - 通过单独的方法结束游戏

标签 java

我有两个不同的类: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);

您不需要返回任何东西,它会结束程序。

给用户一个选择:

  1. 开始新游戏->开始新游戏

  2. 退出 -> System.exit(0)

我还会使用开关来检查用户选项,这样你就不太可能犯错误,而且当选项开始累积时,它会变得更整洁、更快。

您可以创建选项枚举或使用具有有意义名称的最终整数,以便您的代码更易于导航并与用户选项匹配。

From java the docs.

关于java - 通过单独的方法结束游戏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37173096/

相关文章:

java - ARCore 世界对齐

java - 按照惯例,我是否希望在我的 java 项目中使用 com 文件夹?

java - 如何格式化蓝牙可移植打印机?

java - 如何为 java replaceall 函数编写正则表达式?

java - 在java中用 '\\'替换 '\'字符串

java - 使用newCachedThreadPool时如何获取当前线程数

java - 当用户尝试使用 JavaFx 中的 setOnCloseRequest 关闭应用程序时的警告框

java - 检查方法参数的泛型类型

Java 在另一个类文件的 jframe 中的 jtabbed Pane 中添加 jpanel

java - 用 1 和 0 初始化的信号量之间的区别