Java 文本冒险在某行之后意外停止。

Java 文本冒险在某行之后意外停止。,java,text,switch-statement,maintainability,adventure,Java,Text,Switch Statement,Maintainability,Adventure,我一直在做一个文本冒险,在它到达一行代码之前,一切都很顺利。我的一个非常擅长编程的朋友不知道出了什么问题,所以他做了一些测试,但仍然没有好的结果。我需要你的帮助,因为他不是最棒的。这是到目前为止的代码。尝试测试它,直到您遇到错误,它不再接受任何输入。首先选择ax,然后选择帮助,然后选择是,然后继续,然后停止接受 主类代码: package main; import java.awt.*; import java.util.*; import javax.swing.*; public cl

我一直在做一个文本冒险,在它到达一行代码之前,一切都很顺利。我的一个非常擅长编程的朋友不知道出了什么问题,所以他做了一些测试,但仍然没有好的结果。我需要你的帮助,因为他不是最棒的。这是到目前为止的代码。尝试测试它,直到您遇到错误,它不再接受任何输入。首先选择ax,然后选择帮助,然后选择是,然后继续,然后停止接受

主类代码:

package main;

import java.awt.*;
import java.util.*;

import javax.swing.*;

public class Main 
{
public static String thetext;
public static int test;
public static boolean boo;
public static Scanner scan=new Scanner(System.in);
public static JFrame window = new JFrame();
public static JPanel panel = new JPanel();
public static JTextArea out = new JTextArea();
public static JTextField in = new JTextField(30);
public static boolean debug_mode = true;

public static void main (String[] a)
{
    window.setSize(640, 480);
    window.setTitle("CtaQuest_A_Text_Adventure");
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.setLocation(200, 200);
    window.setVisible(true);
    window.setResizable(false);
    window.setFocusable(true);

    out.setEditable(false);
    out.setSize(new Dimension(640, 340));
    out.setMaximumSize(new Dimension(640, 340));

    GridBagLayout layout = new GridBagLayout();
    panel.setLayout(layout);

    GridBagConstraints constraints = new GridBagConstraints();

    constraints.gridx = 0;
    constraints.gridy = 0;

    panel.add(out,constraints);
    constraints.gridy++;

    panel.add(in,constraints);

    window.add(panel);
    out.setSize(new Dimension(640, 340));
    out.setMinimumSize(new Dimension(640, 340));
    out.setMaximumSize(new Dimension(640, 340));


    print("Welcome, My Fellow Nerd! Today, You Will Set Off On A Text Based Adventure, In The Land Of Java.\n");
    print("Before You Set Off On Your Adventure, Let Me Explain What You Will Need To Be Doing.");
    print("To Start, Please Let Me Describe Your Setting...");
    print("The Woods around you glimmer in the sunlight... Water droplets fall off of the leaves \nfrom the morning dew... Birds chirp in the distance. You turn around and \nlook at a stump on the ground.. A Sword and Ax lay \n neatly and orderly next to one another.\n");
    print("Now, for your first task, choose either (Sword), or (Ax). \n (Make sure you use correct spelling. \n and type only what is in the ()'s)");

    switch(InputHandler.getInput().toLowerCase()) 
    {
    case "ax":print("Nice choice. You went for Brute Force, instead of agility.\n Your Quest now begins, with an old traveler that needs your help. \n "+'"'+"Young traveler. I need you to help me gather wood with your \n new looking Axe."+'"'+"");
        print("Would you like to (Help)? Or Would you like to (Walk Away)?(Remember, Repeat the options exactly,\n or it wont work)");
        switch (InputHandler.getInput().toLowerCase())
        {
        case "walk away":print("But he is just so charming of an old man, how could you say no? You help him anyway.");
        case "help":print("The old man thanks you and shows you where to start cutting. \n He signals for you to go into a dark part of the forest.\n Do you go into the deep dark forest? (Yes) or (No).");
            switch (InputHandler.getInput().toLowerCase())
            {
            case "no":print("Come on dude, its an old guy that need some wood. Just go and chop some up for him.");
            case "yes":print("You head into the dark Jungle and stumble upon a large vine. \n It swerves and moves freely along the ground. Do you (Attack) or do you (Run)");
                switch (InputHandler.getInput().toLowerCase())
                {
                case "run":print("The vine notices you and attacks quickly, cutting your face. \n A tiny bar on the top left of you sceen flashes, and you health drops by 1\n you now have 9/10 Health. You have no choice but to fight back.\n Swinging your sword helplessly, you chop the vines tip off, \n forcing it to fall like a rope, \n smashing the ground. Do you (Go Back) and confront the old man\n,or (Continue) to chop down wood.");
                    switch (InputHandler.getInput().toLowerCase())
                    {
                    case "go back":print("You travel slowly, and ohh so cautiously \n back to where you entered the dark part of the forest. You look out of the bushes \n and find that the old man is gone! That sneeky little \n bastard! He must have planned for you to get caught back there. \n But wait, you see a person running away in the distance. Do you: (chase) after the figure, or (Leave) him alone?");
                        switch (InputHandler.getInput().toLowerCase())
                        {
                        case "chase":print("you run for about an hour when you realize its a lost cause.\n Man! You should have known that the old man \n wasn't really an old man! Who can run that\n fast and still have wrinkles all over the face!");break;
                        case "leave":print("It was a lost cause anyway. \n You turn around to go find shelter because night is biggening to fall.\n As you turn around a small creature lurks. It turns around and looks at you.\n  Unsheathing your weapon, it copies. Although it is only \n 2 feet tall about you are still scared of what it could do.\n It look just as worried as you do. Suddenly it opens its mouth and talks!\n He says,\n Mister, If you are the violent type of person, i would advise you to join in the colluseum. If you win, you would become the Lord Of All Goblins. Do you (Take) the offer or (Decline)?");break;
                        default:print("Please, try to complete this and dont fool around.Terminating Program.Teehee!!!");window.dispose();break;
                        }break;
                    case "continue": print("You made a good choice, helping the old man \n before going back. As you chop down a few more branches, you keep your gaurd up, \n watching out for any more monsters. After grabbing the logs and sticks you gathered you travel back\n and relieze that the man is gone! Aww man!\n He made you waste all this time and now he is gone! You look around and find a small rock. \n You chuck it into a tree in frustration. Bad idea.\n The tree starts to move and it looks at you. Do you: (Brace) for impact, or (Attack) first?");
                        switch (InputHandler.getInput().toLowerCase())
                        {
                        case "brace":print("The tree winds up his branch, and lashes out at you, striking with great force.\n It knocks you to the ground, and you here a crack. Pain jolts through your arm/n as you try to move it. Without hesitation you run away,/n clenching your broken arm. You find a small cave in the woods and a tall \n mound of dirt. Which do you travel to or into, the (Cave) or the (Dirt) hill?");
                            switch (InputHandler.getInput().toLowerCase())
                            {
                            case "cave":print("You cautiously approch the cave.\n Thinking to yourself if there is a monster or not in there\n you take the risk anyway. As you progress into the never ending cave,\n you see a light! It becons in the dark cave and the warmth drags you closer.\n suddenly you hear a voice! Do you, (Continue) or (Turn) around?");break;
                            case "dirt":print("The mound of dirt takes about 30 minutes to climb with your broken arm,\n and at the top it is like a tiny platue. It is a tall mound and the tree looks so puny from up here. You stay the night on the top of the mound...\n\n In the morning you here the birds chirping. You look around at spot a small village!\n Do you (Go) to the village or (Stay) on the mound?");break;
                            default:print("Please, try to complete this and dont fool around.Terminating Program.Teehee!!!");window.dispose();break;
                            }break;
                        case "attack":print("You run in at high speed,\n the tree looks down at you but before \n it can attack you you strike!\n knocking it to the floor, sliced in half,/n like last nights steak. You gather/n the wood you had chopped and you get the hell out of there./n As you near the point of the forest in which you met the old man you realize/n he is missing! Must have been a set up all along!/n Do you (Search) the forest for him or/n set up a (Fire)?");break;
                        default:print("Please, try to complete this and dont fool around.Terminating Program.Teehee!!!");window.dispose();break;
                        }break;
                    default:print("Please, try to complete this and dont fool around.Terminating Program.Teehee!!!");window.dispose();break;
                    }break;
                case "attack":print("You swing you sword at the vine,\n It falls to the ground, dead. Do you \n(Continue) To chop wood, or (Go back)\n And confront the old man?");
                    switch (InputHandler.getInput().toLowerCase())
                    {
                    case "go back":print("You travel slowly, and ohh so cautiously \n back to where you entered the dark part of the forest. You look out of the bushes \n and find that the old man is gone! That sneeky little \n bastard! He must have planned for you to get caught back there. \n But wait, you see a person running away in the distance. Do you: (chase) after the figure, or (Leave) him alone?");break;
                    case "continue":print("You made a good choice, helping the old man \n before going back. As you chop down a few more branches, you keep your gaurd up, \n watching out for any more monsters. After grabbing the logs and sticks you gathered you travel back\n and relieze that the man is gone! Aww man!\n He made you waste all this time and now he is gone! You look around and find a small rock. \n You chuck it into a tree in frustration. Bad idea.\n The tree starts to move and it looks at you. Do you: (Brace) for impact, or (Attack) first?");break;
                    default:print("Please, try to complete this and dont fool around.Terminating Program.Teehee!!!");window.dispose();break;
                    }break;
                default:print("Please, try to complete this and dont fool around.Terminating Program.Teehee!!!");window.dispose();break;
                }break;
            default:print("Please, try to complete this and dont fool around.Terminating Program.Teehee!!!");window.dispose();break;
            }break;
        default:print("Please, try to complete this and dont fool around.Terminating Program.Teehee!!!");window.dispose();break;
        }break;
    case "sword":print("Ahh, So you chose Agility over brute force.\n Your Quest now begins,\n with an young traveler that is eager to challenge you. "+'"'+" Race me or face my Wrath!"+'"'+" ");
            print("Would you like to (Race)? Or Would you like to (Face His Wrath)?(Remember, Repeat the options exactly,\n or it wont work)");
        switch (InputHandler.getInput().toLowerCase())
        {
        case "race":print("The Young Traveler gets a head start!\n He sprints all the way down an open path way in the trees.\n Do you follow? (Yes) or (No).");
            switch (InputHandler.getInput().toLowerCase())
            {
            case "no":print("The boy looks like such an easy opponent to race against, So you run after him.");
            case "yes":print("You sprint as fast as you can to catch up, but something catches your foot and you trip.\n You turn around and see a large vine has caught your leg.\n Do you, (Attack) or (Escape)?");
                switch (InputHandler.getInput().toLowerCase())
                {
                case "escape":print("The vine just pulls tighter and makes it even harder to escape. \n A small bar on the top of the screen shows your health. It drops by one, leaving you at 9/10 health.\n You pull out your sword.");
                case "attack":print("You swing you sword at the vine,\n chopping it off your leg. It falls to the ground, dead.");break;
                default:print("Please, try to complete this and dont fool around.Terminating Program.Teehee!!!");window.dispose();break;
                }break;
            default:print("Please, try to complete this and dont fool around.Terminating Program.Teehee!!!");window.dispose();break;
            }

        }break;case "face his wrath":print("The young boy slits your throat and you die instantly. You need to have some common sense in this game.\n You lose. Program Termination...");window.dispose();break;


    default:print("Please, try to complete this and dont fool around.Terminating Program.Teehee!!!");window.dispose();break;
    }   }
private static void print(String string) 
{
    debug("Printing...");
    System.out.println();
    out.setText(out.getText()+"\n");
    boolean threwException = false;
    int exceptions = 0;

    string+=" ";
    for(int prog = 0; prog<string.length(); prog++)
    {
        int wait = 25;

        if(string.charAt(prog) != ' ' || string.charAt(prog-1) != '\n')
        {
            System.out.print(string.charAt(prog));
            out.setText(out.getText()+string.charAt(prog));
        }
        window.repaint();
        switch(string.charAt(prog))
        {
        case ',': wait = 175; break;
        case ' ': wait = 0; break;
        case ':':
        case '-': wait = 135; break;
        case '.': if(string.charAt(prog+1) == ')') {prog++; try{Thread.sleep(25);}catch(Exception e){} System.out.print(string.charAt(prog));
        out.setText(out.getText()+string.charAt(prog)); window.repaint();} wait = 1000; break;
        case '?':
        case '!': wait = 1000; break;
        default: wait=25;
        }
        try 
        {
            string.charAt(prog+2);
            Thread.sleep(wait);
        } 
        catch (Exception e) {threwException = true; exceptions++;}
        }
    debug("Done printing.");
    if(threwException)
    {
        debugErr("Threw exception "+exceptions+" time(s).");
    }
    }
public static void debug(String text)
{
    if(debug_mode)
    {
        System.out.println(text);
    }
}

public static void debugErr(String text)
{
    if(debug_mode)
    {
        System.err.println(text);
    }
}
}
package main;

import java.awt.*;
import java.awt.event.KeyEvent;
import java.util.concurrent.*;

public class InputHandler
{
static CountDownLatch latch = new CountDownLatch(1);
public static void waitForEnter()
{
    debug("Waiting for the enter key to be pressed...");
    latch = new CountDownLatch(1);
    KeyEventDispatcher dispatcher = new KeyEventDispatcher()
    {
            @Override
            public boolean dispatchKeyEvent(KeyEvent e) 
            {
                if (e.getKeyCode() == KeyEvent.VK_ENTER)
                {
                    latch.countDown();
                }
            return false;
        }
    };
    KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(dispatcher);
    try
    {
        latch.await();
    } catch (Exception e)
    {
        e.printStackTrace();
    } 
    KeyboardFocusManager.getCurrentKeyboardFocusManager().removeKeyEventDispatcher(dispatcher);
    debug("Enter key pressed.");
}

public static String getInput()
{
    debug("Getting input...");
    waitForEnter();
    String ret = Main.in.getText();
    Main.out.setText("");
    Main.in.setText("");
    debug("Input obtained.");
    return ret;
}

public static void debug(String text)
{
    if(Main.debug_mode)
    {
        System.out.println(text);
    }
}
}

你在节目结束时很简单。在此之后没有任何其他
getInput()
print

print("You swing you sword at the vine,\n It falls to the ground, dead. Do you \n(Continue) To chop wood, or (Go back)\n And confront the old man?");

因此主方法退出,但没有关闭窗口

它崩溃的原因是因为您的代码写得不好:)

是的,原因可能是你的某个地方有个bug。但这只是真正问题的一个副产品,即您的代码太混乱而无法遵循

我建议您在文本文件中写入如下内容:

{
    "1": {
        "question": "Now, for your first task, choose either (Sword), or (Ax). \n (Make sure you use correct spelling. \n and type only what is in the ()s)",
        "choices": {
            "Sword": 2,
            "Ax": 1
        }
    },
    "2": {
        "question": "Nice choice. You went for Brute Force, instead of agility.\n Your Quest now begins, with an old traveler that needs your help. \n \"Young traveler. I need you to help me gather wood with your \n new looking Axe.\" Would you like to (Help)? Or Would you like to (Walk Away)?(Remember, Repeat the options exactly,\n or it wont work)",
        "choices": {
            "Help": 3,
            "Walk Away": 4
        }
    },
    "3" : ...etc...
}
然后找出如何让程序读取(这是JSON)并使用它来驱动游戏


注意:这只是我的想法,如果你能想出一个更好的解决方案,请随意编辑这个答案。

你的程序结构就像一棵树,每个节点都有一个描述和一些决策分支:

           / walk away
      / ax - help
start 
      \ sword - race
              \ face his wrath
在每个步骤中,我们都需要一个描述和一系列选项

class Situation {
    String description;
    Decision[] options;
}
每个决策都需要一些输入并导致结果

class Decision {
    String expectedInput;
    Situation consequence;
}
那么游戏的逻辑可能是这样的

while ( currentSituation.moreToDo() ) {
    currentSituation.describe();
    choice = InputHandler.getInput().toLowerCase();
    currentSituation = currentSituation.consequence(choice);
}
descripe方法将打印描述并通过选项循环以显示预期的输入

结果方法将根据每个选项的预期输入检查选择,并跟踪匹配结果或显示消息并返回到当前状态


真正的乐趣将是把你所有的描述和选择融入到这些对象中。最好是从一个可以快速轻松更改的文件中读取(至少比更改代码更快更容易)。

这是历史上嵌套最深的case语句之一。编写文本冒险的方式非常糟糕。它应该是数据驱动的(程序编写的一般目的是获取有关冒险的数据,并从中解释向用户显示的内容以及作为动作从用户处获取的内容),而不是代码驱动的(冒险是硬编码到程序中的,逻辑变得异常复杂,难以遵循和添加-就像现在一样)。选择“是”后,选择“运行”或“攻击”,否则您将陷入默认状态,从而结束程序。拜托,谁在开始时没有编写文本冒险或自己的开发生涯?:))+为了美好的时光,我们必须更深入!很抱歉,您能更详细地解释一下您的意思吗,因为您所说的可能正好解决了我的问题。当您从案例分支返回进行附加时,程序没有输入任何其他
InputHandler.getInput()
它退出所有案例并结束main方法。您可以检查编写
调试(“退出…”)在main method的末尾谢谢,我会尝试这个,但是在我给你正确的答案之前,我想看看其他人的解决方案。这听起来像是个好主意,谢谢。谢谢,我也会试试看它是否改变了什么。这将需要一段时间来重新编程的游戏,但它只是可能解决我的问题。我也喜欢你用建设性的批评而不是单纯的批评。嗯,到目前为止,所有的答案听起来都很有希望,所以我会尝试所有的答案,谢谢你的帮助!