2013-06-03 11 views
5

Ho lavorato a un'avventura testuale e tutto procede senza problemi finché non raggiunge una riga di codice. Il mio amico che è molto bravo a programmare non è riuscito a capire cosa c'era che non andava, così ha fatto alcuni test e ancora nessun risultato positivo. Ho bisogno del tuo aiuto perché il suo non era il massimo. Ecco il codice fino ad ora. Prova a testarlo finché non incappi nel bug dove non accetta più input. All'inizio scegli l'ascia, poi scegli l'aiuto, poi si, poi continua, poi smette di accettare.Text-Adventure si arresta inaspettatamente dopo una determinata linea.

Il principale Codice classe:

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

L'inputhandler Codice classe:

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); 
    } 
} 
} 
+20

questa è una delle affermazioni case più profondamente nidificate della storia. –

+0

Si sta generando un errore? se è così, metti la traccia dello stack – greedybuddha

+1

+1 Sicuramente ti metti impegno a scrivere tutto quel codice! – A4L

risposta

2

Sei semplice arrivare alla fine del programma. Non c'è nessun altro getInput() o print dopo questo:

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?"); 

modo che il metodo delle principali uscite, ma non ha ucciso la finestra.

+0

Mi dispiace, puoi spiegare cosa intendi in modo più dettagliato, perché quello che stai dicendo potrebbe solo risolvere la mia domanda. –

+0

Quando si ritorna dal ramo case per Attact il programma non è entrato in nessun altro 'InputHandler.getInput()' esce da tutti i casi e termina il metodo principale. Puoi controllare la scrittura di un 'debug (" Esci ... ");' alla fine del metodo principale – Joan

+0

Grazie, proverò a farlo, ma prima di dare la risposta corretta ti piacerebbe vedere le soluzioni di altre persone. Questo suona come se fosse una buona idea, grazie. –

3

Il motivo per cui si blocca è perché il codice è scritto male :)

Sì, la causa è probabilmente che si dispone di un bug da qualche parte. Ma questo è solo un sottoprodotto del vero problema, che è che il tuo codice è troppo confuso da seguire.

Quello che vorrei suggerire di fare è scrivere in un file di testo o meno così:

{ 
    "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... 
} 

poi cercare di capire come ottenere il vostro programma per leggere (Questo è JSON) e utilizzarlo per guidare il gioco.

NOTA: Questo è proprio fuori dalla mia testa, quindi sentitevi liberi di modificare questa risposta se è possibile trovare una soluzione migliore.

+1

Grazie, proverò anche questo per vedere se cambia qualcosa. Ci vorrà un po 'per riprogrammare il gioco ma potrebbe risolvere il mio problema. Mi piace anche come hai usato le critiche costruttive invece della critica. –

4

La struttura del programma è come un albero, con ogni nodo avere una descrizione e alcune decisioni ramificazione da esso:

  /walk away 
    /ax - help 
start 
     \ sword - race 
       \ face his wrath 

Ad ogni passo abbiamo bisogno di una descrizione e una serie di opzioni

class Situation { 
    String description; 
    Decision[] options; 
} 

Dove ogni decisione ha bisogno di qualche input e conduce ad una conseguenza

class Decision { 
    String expectedInput; 
    Situation consequence; 
} 

Poi la logica del gioco potrebbe essere qualcosa di simile

while (currentSituation.moreToDo()) { 
    currentSituation.describe(); 
    choice = InputHandler.getInput().toLowerCase(); 
    currentSituation = currentSituation.consequence(choice); 
} 

Il metodo describe sarebbe stampare la descrizione ed il ciclo attraverso le opzioni per visualizzare l'ingresso previsto.

Il metodo delle conseguenze controllerebbe la scelta rispetto all'input previsto di ciascuna opzione e seguirà la conseguenza della corrispondenza o visualizzerà un messaggio e tornerà alla situazione corrente.

Il vero divertimento sarà ottenere tutte le descrizioni e le opzioni in quegli oggetti. È meglio leggere da un file che è possibile modificare rapidamente e facilmente (almeno in modo più rapido e semplice rispetto alla modifica del codice).

+0

Hmm, tutte le risposte sembrano promettenti, quindi cercherò di provarle tutte, grazie per il vostro aiuto! –

Problemi correlati