文本冒险在某一行之后突然停止



我一直在开发一款文本冒险游戏,一切都很顺利,直到出现一行代码。我的一个非常擅长编程的朋友不知道哪里出了问题,所以他做了一些测试,仍然没有好的结果。我需要你的帮助,因为他不是最棒的。下面是目前为止的代码。尝试测试它,直到遇到它不接受任何输入的错误。一开始选择了"ax",然后选择了"help",然后是"yes",然后是"continue",最后停止接受。

主类代码:
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 1n 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 mann,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 thatn 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 backn 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 theren 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...nn 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 backn 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);
    }
}
}
inputhandler类代码:
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);
    }
}
}

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

           / 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);
}

description方法将打印描述并循环遍历选项以显示期望的输入。

结果方法将根据每个选项的预期输入检查选择,并遵循匹配的结果或显示消息并返回到当前情况。

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

它崩溃的原因是因为你的代码写得很糟糕:)

是的,原因可能是你在某个地方有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)并使用它来驱动游戏。

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

您只是到达了程序的末尾。在此之后没有任何其他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?");

所以main方法退出,但没有杀死窗口。

最新更新