5

私はテキストの冒険に取り組んできましたが、コード行に到達するまではすべてスムーズに進みます。プログラミングが得意な私の友人は、何が悪いのかわからなかったので、いくつかのテストを行いましたが、それでも良い結果は得られませんでした。彼は最高ではなかったので、あなたの助けが必要です。ここまでのコードです。それ以上の入力を受け入れないというバグに遭遇するまでテストしてみてください。最初に斧を選択し、次にヘルプを選択し、次にはい、次に続行すると、受け入れが停止します。

メインクラスのコード:

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

3 に答える 3

4

プログラムの構造はツリーのようなもので、各ノードには説明があり、そこから分岐するいくつかの決定があります。

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

describe メソッドは、説明を出力し、オプションをループして、予想される入力を表示します。

結果メソッドは、各オプションの予想される入力に対して選択をチェックし、一致の結果に従うか、メッセージを表示して現在の状況に戻ります。

本当の楽しみは、すべての説明とオプションをそれらのオブジェクトに入れることです。すばやく簡単に変更できるファイルから読み取るのが最善です (少なくとも、コードを変更するよりもすばやく簡単に変更できます)。

于 2013-06-03T23:08:52.797 に答える
3

クラッシュする理由は、コードの書き方が悪いためです:)

はい、原因はおそらくどこかにバグがあることです。しかし、それは実際の問題の副産物にすぎません。それは、コードがわかりにくく、理解できないということです。

私がお勧めするのは、次のようなテキストファイルに書くことです:

{
    "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 です)、それを使用してゲームを駆動する方法を考え出します。

注:これは私の頭の中で考えただけなので、より良い解決策を思い付くことができれば、この回答を自由に編集してください。

于 2013-06-03T22:46:41.247 に答える
2

あなたはプログラムの終わりに到着するだけです。他にはありません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?");

したがって、メイン メソッドは終了しますが、ウィンドウは強制終了しません。

于 2013-06-03T22:37:48.597 に答える