2016-03-20 12 views
0

私はJavaでテキストアドベンチャーゲームを作成しています。このゲームでは、ヘルプを 'H'、北を移動する 'N'などのコマンドを入力します。場合によっては、その部屋にあるキーを取るために、「Tキー」のようなものを入力する必要があります。だから私はsplitメソッドを使用して、コマンドとユーザーが取っておきたい項目を分割する必要があります。返される文字列は、ある文字を入力した場合にのみコマンドが返される場合もあれば、コマンドとアイテムの両方になる場合もあるため、実際に戻り部分に詰まっています。すべての助けに感謝します!.splitを使用してユーザー入力を処理する

これはメインクラスで私のコードです:

import java.util.Scanner; 
import java.util.ArrayList; 
import java.util.Arrays; 

public class GameEngine { 
    private Scanner userInput = new Scanner(System.in); 
    private Player player1 = new Player("playerName", 0); 
    private int currentLocation = player1.currentRoom; 
    private boolean stillPlaying = true; //When this is true, the game continues to run 

    private Item[] items = { 
      new Item ("map","a layout of your house", 10), 
      //new Item ("battery", "a double A battery", 5), 
      new Item ("battery", "a double A battery", 5), 
      new Item ("flashlight", "a small silver flashlight", 10), 
      new Item ("key", "this unlocks some door in your house", 15), 
    }; 

    //Locations {roomName, description, item} 
    private Locale[] locales = { 
      new Locale("bedroom","You see the outline of a bed with your childhood stuffed bear on it.",items[0]), 
      new Locale("hallway","A carpeted floor and long pictured walls lie ahead of you.",null), 
      new Locale("kitchen","The shining surface of your stove reflects the pale moonlight coming in the window over the sink.",items[1]), 
      new Locale("bathroom","You find yourself standing in front of a mirror, looking back at yourself.",items[2]), 
      new Locale("living room","You stub your toe on the sofa in the room, almost falling right into the TV.",null), 
      new Locale("dining room","You bump the china cabinet which holds your expensive dishes and silverware.",items[3]), 
      new Locale("office","The blinking light from the monitor on your desk can be seen in the dark",null), 
      new Locale("library","The smell of old books surrounds you.",null), 
      new Locale("basement","You reach the top of some stairs and upon descending down, you find the large metal generator.",null), 
    }; 

    //Matrix for rooms 
    private int[][] roomMap = { 
      // N,E,S,W 
      {6,1,-1,-1}, //Bedroom (room 0) 
      {4,2,3,0}, //Hallway (room 1) 
      {-1,-1,5,1}, //Kitchen (room 2) 
      {1,-1,-1,-1}, //Bathroom (room 3) 
      {-1,7,1,-1}, //Living Room (room 4) 
      {2,-1,-1,-1}, //Dining Room (room 5) 
      {-1,-1,0,-1}, //Office (room 6) 
      {8,-1,-1,4}, //Library (room 7) 
      {-1,-1,7,-1} //Basement (room 8) 
    }; 

    private BreadcrumbTrail trail = new BreadcrumbTrail(); 

    //Move method 
    private String[] dirNames = {"North", "East", "South", "West"}; 

    //Welcome Message 
    public void displayIntro(){ 
     System.out.println("\tWelcome to Power Outage!"); 
     System.out.println("================================================="); 
     System.out.print("\tLet's start by creating your character.\n\n\tWhat is your name? "); 

     //Will read what name is entered and return it 
     player1.playerName = userInput.nextLine(); 

     System.out.println("\n\tHello, " +player1.playerName+ ". Let's start the game! \n\n\tPress any key to begin."); 
     System.out.print("================================================="); 

     //Will move to next line when key is pressed 
     userInput.nextLine(); 

     System.out.println("\tYou wake up in your bedroom. \n\n\tThe power has gone out and it is completely dark."); 
     System.out.println("\n\tYou must find your way to the basement to start the generator."); 
    } 

    private void displayMoveInfo(){ 
     System.out.println("\n\tMove in any direction by typing, 'N', 'S', 'E', or 'W'."); 
     System.out.println("\n\tTake an item from a room by pressing 'T'."); 
     System.out.println("\n\tTo go back to the room you were just in type 'B'."); 
     System.out.println("\n\tType 'H' at any time for help and 'Q' to quit the game. Good luck!"); 
     System.out.println("\n\tPress any key."); 
    } 
    private void move(int dir) { 
     int dest = roomMap[currentLocation][dir]; 
     if (dest >= 0 && dest != 8) { 
      System.out.println("================================================="); 
      System.out.println("\tYou have moved " + dirNames[dir]); 
      currentLocation = dest; 
      System.out.println("\n\tYou are in the "+locales[currentLocation].roomName+"."); 
      System.out.println("\n\t"+locales[currentLocation].description); 
      Locale locale = locales[currentLocation]; 
      itemPresent(); 
      //Drop breadcrumb at current location 
      trail.dropCrumb(currentLocation); 
     } 
     //If the player reaches the basement and wins 
     else if (dest == 8){ 
      System.out.println("\tCongratulations!! You have found the basement and turned on the generator! \n\n\tYou have won the game!"); 
      System.out.println("\n\tTHANKS FOR PLAYING!!!!!!"); 
      System.out.println("\n\tCopyright 2016 \n\n"); 
      stillPlaying = false; 
     } 
     //If dest == -1 
     else { 
      System.out.println("\tThere is no exit that way, please try again."); 
     } 
    }//End of Move 

    private void itemPresent(){ 
     Locale locale = locales[currentLocation]; 
     if(locale.item != null){ 
      System.out.println("\n\tThere is a " + locale.item + " in this room."); 
     } 
     else{ 
      System.out.println("\n\tThere is no item in this room."); 
     } 
    } 

    public Command getCommandFromResponse(String response) throws IllegalArgumentException{ 
     String[] split = response.split(" "); 

     if(split.length < 1){ 
      throw new IllegalArgumentException("Invalid command."); 
     } 

     Command command = new Command(split[0]); 
     if(split.length >= 2) { 
      command.setItem(split[1]); 
     } 

     return command; 
    } 

    //All possible responses to keys pressed 
    public void processInput(){ 
     displayMoveInfo(); 
     Command userCommand = getCommandFromResponse(userInput.nextLine()); 

     while(stillPlaying){ 
      if(player1.currentRoom != 8 && !"Q".equalsIgnoreCase(userCommand.getCommand())){ 

       //Map 
       if(userCommand.command.equalsIgnoreCase("M")){ 
        //only print if the player has the map 
        //String[] inventory = player1.inventory; 
        int mapFoundAt = -1; 
        if(player1.inventory != null){ 
         for(int i=0; i < player1.inventory.size(); i++){ 
          Item checkItem; 
          checkItem = player1.inventory.get(i); 
          if(checkItem.itemName.equals("map")){ 
           mapFoundAt = i; 
           break; 
          } 
         } 
         if(mapFoundAt >=0){ 
          System.out.println("Here is your map: \n\n\t\t\tbasement\n\noffice\t living room\tlibrary\n\nbedroom\t hallway\tkitchen\n\n\t bathroom \tdining room"); 
         } 
         else{ 
          System.out.println("\tYou do not have the map in your inventory."); 
         } 
        } 
        else{ 
         System.out.println("\tYou don't have any items in your inventory."); 
        } 
        break; 
       }//End of Map 


       //Take 
       else if(userCommand.command.equalsIgnoreCase("T")){ 
        Locale locale = locales[currentLocation]; 
        if(userCommand.command.equalsIgnoreCase("T")){ 

        } 
        if(locale.item != null){ 
         //-User must enter item name with the command 
         System.out.println("Enter the command and item you would like to take."); 
         userCommand = getCommandFromResponse(userInput.nextLine()); 

         if(userCommand.command.equals(locale.item.itemName)){ 
          //-add the item to the player's inventory 
          player1.inventory.add(locale.item); 
          System.out.println("\tA " + locale.item + " was added to your inventory"); 
          if(locale.item.itemName.equals("map")){ 
           System.out.println("\n\tTo view the map press 'M'."); 
          } 
          //-remove the item from the current location 
          locale.item = null; 
          System.out.println("\n\tYou can view your inventory by pressing 'I' or drop an item by pressing 'D'."); 
          //-Add the item's worth to the score and set the items worth to zero to prevent double scoring 
          player1.score += locale.item.value; 
          System.out.println(locale.item.value + " points have been added to your score."); 
          System.out.println("\n\tThis is your current score: "+player1.score); 
         } 
         else{ 
          System.out.println("That item is not at this location."); 
         } 
        } 
        else{ 
         System.out.println("There is no item to pick up here"); 
        } 

       }//End of Take 

       //Help 
       else if(userCommand.command.equalsIgnoreCase("H")){ 
        displayMoveInfo(); 
        break; 
       } 

       //Inventory 
       else if(userCommand.command.equalsIgnoreCase("I")){ 
        if(player1.inventory != null){ 
         System.out.println("\tThese are the items in your inventory: "+player1.inventory+"."); 
        } 
        else{ 
         System.out.println("\tYou currently have no items in your inventory."); 
         System.out.println("\tTo pick up an item in a room, press 'T'."); 
        } 
        break; 
       } 

       //Drop 
       else if(userCommand.command.equalsIgnoreCase("D")){ 
        //Show the list of items in the player's inventory with numbers associated with them 
        if(player1.inventory.size() != 0){ 
         System.out.println("\tThese are the items available to drop: " +player1.inventory); 
        } 
        else if(player1.inventory.size() == 0){ 
         System.out.println("\tYou have no items in your inventory to drop."); 
         break; 
        } 
        System.out.println("\tEnter the name of the item you would like to drop."); 
        String itemToDrop = userInput.nextLine(); 
        Locale locale = locales[currentLocation]; 
        if(locale.item == null){ 
         for(int i=0; i < player1.inventory.size(); i++){ 
          Item checkItem; 
          checkItem = player1.inventory.get(i); 
          if(checkItem.itemName.equalsIgnoreCase(itemToDrop)){ 
           //Remove item entered from a player's inventory 
           System.out.println("\tYou have dropped the " +checkItem.itemName+ "."); 
           player1.inventory.remove(i); 
           //Place the item at the player's current location so it can be picked up again 
           locale.item = checkItem; 
           //Subtract five points from the player's score 
           player1.score -= 5; 
           System.out.println("\tFive points have been subtracted from your score."); 
           System.out.println("\n\tThis is your current score: "+player1.score); 

          } 
          else if(i==player1.inventory.size() && checkItem.itemName != itemToDrop){ 
           System.out.println("\tThat is not an item in your inventory."); 
           break; 
          } 
         } 
        } 
        else{ 
         System.out.println("\tThere is already an item at this location, you can't drop an item."); 
        } 
        break; 
       }//End of Drop 


       //Backtrack 
       else if(userCommand.command.equalsIgnoreCase("B")){ 
        //Pick up breadcrumb 
        trail.pickupCrumb(); 
        if(trail.hasMoreCrumbs() == false){ 
         //Move to previous crumb 
         currentLocation = trail.currentCrumb(); 
         System.out.println("\n\tYou are in the "+locales[currentLocation].roomName+"."); 
         System.out.println("\n\t"+locales[currentLocation].description); 
         itemPresent(); 
        } 
        //When the trail is empty, drop the last breadcrumb, don't move the player again 
        else{ 
         trail.dropCrumb(currentLocation); 
         System.out.println("\tYou are at the beginning of your breadcrumb trail, you can't backtrack any more."); 
        } 
        break; 
       }//End of Backtrack 


       //North 
       else if(userCommand.command.equalsIgnoreCase("N")){ 
        move(0); 
        break; 
       } 

       //East 
       else if(userCommand.command.equalsIgnoreCase("E")){ 
        move(1); 
        break; 
       } 

       //South 
       else if(userCommand.command.equalsIgnoreCase("S")){ 
        move(2); 
        break; 
       } 

       //West 
       else if(userCommand.command.equalsIgnoreCase("W")){ 
        move(3); 
        break; 
       } 

       //If any key is pressed other than those above 
       else{ 
        System.out.println("\tInvalid command!"); 
        break; 
       } 
      }//End of Quit if statement 

      else if(userCommand.command.equalsIgnoreCase("Q")){ 
       System.out.println("Thanks for playing!\n\n"); 
       stillPlaying = false; 
      } 
     }//End of while 
    }//End of pressedKey method 

    public void play(){ 
     displayIntro(); 
     System.out.println("================================================="); 
     System.out.println("\tYou are in the bedroom."); 
     Locale locale = locales[currentLocation]; 
     itemPresent(); 
     trail.dropCrumb(currentLocation); 

     //This makes the game continue to loop 
     while(stillPlaying){ 
      System.out.println("================================================="); 
      System.out.println("\tMove in any direction."); 
      processInput(); 

     } //End of while 

    } 

    public static void main(String[] args) { 
     GameEngine game = new GameEngine(); 
     game.play(); 
    } //End of main 
} //End of class 

これは私のプレーヤークラスです: 輸入はjava.util.ArrayList;

public class Player { 

    //Player class must have name, location, inventory, and score 
    public String playerName; 
    public ArrayList<Item> inventory; 
    public int score; 
    public int currentRoom; 

    public Player(String playerName, int currentRoom){ 
     this.playerName = playerName; 
     this.inventory = new ArrayList<Item>(); 
     this.score = 0; 
     this.currentRoom = currentRoom; 
    } 
} 

これは、Commandクラスです:

class Command{ 
     String command; 
     String item; 

     public Command(String comm){ 
      command = comm; 
     } 

     public Command(String comm, String item){ 
      this.command = comm; 
      this.item = item; 
     } 

     public void setCommand(String command){ 
      this.command = command; 
     } 

     public void setItem(String item){ 
      this.item = item; 
     } 

     public String getCommand(){ 
      return this.command; 
     } 

     public String getItem(){ 
      return this.item; 
     } 

     public String toString(){ 
      return this.command + ":" + this.item; 
     } 
    } 

これは私のLocaleクラスです:

public class Locale { 

    //Locale must have name, description, and Item 
    public static int roomNumber; 
    public String roomName; 
    public String description; 
    public Item item; 


    public Locale(String roomName, String description, Item item){ 
     this.roomName = roomName; 
     this.description = description; 
     this.item = item; 
    } 
} 

これは私Itemクラスです:

public class Item { 
    //item must have a name and a description (both strings) 
    public String itemName; 
    public String itemDes; 
    public boolean isDiscovered; 
    public int value; 

    public Item (String itemName, String itemDes, int value){ 
     this.itemName = itemName; 
     this.itemDes = itemDes; 
     this.isDiscovered = false; 
     this.value = value; 
    } 

    public String toString(){ 
     return itemName + "(" + itemDes + ")"; 
    } 
    } 

これは私のBreadcrumbTrailですクラス:

public class BreadcrumbTrail { 
    //dropCrumb (push) 
    //pickupCrumb (pop) 
    //currentCrumb (peek) 
    //hasMoreCrumbs (empty) 

    //Drop a new breadcrumb whenever the player arrives at a local 
    class Node{ 
     int data; 
     Node link; 

     Node(int s, Node l){ 
      this.data = s; //element stored at the node 
      this.link = l; //link to another node 
     } 
    }//End of Node class 

    private Node currentCrumb; 

    //Constructor 
    public BreadcrumbTrail(){ 
     this.currentCrumb = null; 
    } 

    //pop 
    public void pickupCrumb(){ 
     this.currentCrumb = this.currentCrumb.link; 
    } 

    //push 
    public void dropCrumb(int s){ 
     Node newNode = new Node(s, this.currentCrumb); 
     this.currentCrumb = newNode; 
    } 

    //top or peek 
    public int currentCrumb(){ 
     return this.currentCrumb.data; 
    } 

    //isEmpty 
    public boolean hasMoreCrumbs(){ 
     return this.currentCrumb == null; 
    } 
} 

ここで、if elseのステートメントは明らかに機能しません。これは、今では.equalsの前の部分を変更する必要があるためです。

+0

'split.length == 0'は、' split'配列に要素がないことを意味していますので、索引 '[0]'の要素も偶数になります。 – Pshemo

+0

ああ、ありがとうございます:) – user5959738

+0

メインメソッド/クラスを含むコードのすべてをポストするだけで、問題がどこにあるかを確認できます。 – pczeus

答えて

0

すべての以前の回答はまともです。しかし、私はあなたがユーザーの入力を検証する方が良いと思うし、ユーザーが間違った数のオブジェクトを入力した場合、単に入力するのではなく無効な入力を示す例外をスローします。

 public Command getCommandFromResponse(String response) throws IllegalArgumentException{ 
     String[] split = response.split(" "); 

     if(split.length < 1){ 
      throw new IllegalArgumentException("Invalid command."); 
     } 
     if(split.length < 2){ 
      throw new IllegalArgumentException("You must enter an item."); 
     } 

     return new Command(split[0], split[1]); 
     } 

     class Command{ 
     String command; 
     String item; 

     public Command(){ 
      command = null; 
      item = null; 
     } 

     public Command(String comm, String item){ 
      this.command = comm; 
      this.item = item; 
     } 

     public void setCommand(String command){ 
      this.command = command; 
     } 

     public void setItem(String item){ 
      this.item = item; 
     } 

     public String getCommand(){ 
      return this.command; 
     } 

     public String getItem(){ 
      return this.item; 
     } 

     public String toString(){ 
      return this.command + ":" + this.item; 
     } 
     } 
+0

さて、ありがとう、私のコードは今読んで少し難しいように見えるので、私はこれを試していただきありがとうございます。 – user5959738

+0

ユーザーの入力がヘルプのためにちょうど 'H'に等しいかどうかを確認しようとしている場合、コマンドがcommとitemの両方で受けなければならないので、どうすればできますか? – user5959738

+0

コマンドと項目の両方を持つコマンドを返す前に、両方の引数をチェックしています。したがって、コマンドに「H」だけが入力されていても項目が入力されていない場合は、項目を入力する必要があるというエラーが再び表示されます。両方のバリデーションが完了した後でのみ、Commandオブジェクトが作成され、返されます。しかし、私は答えを編集して、argsを持たないデフォルトのコンストラクタと、コマンドとアイテムの両方のsetterメソッドを許可し、必要な柔軟性を与えます。 – pczeus

0

このようなクラスを作成します。

class UserInput { 
    private String command; 
    private String item; 

    public UserInput() { 
     command = ""; 
     item = ""; 
    } 

    public void setCommand(String command) { 
     this.command = command; 
    } 

    public void setItem(String item) { 
     this.item = item; 
    } 
} 

をそして、それのインスタンスを返します。

String response = userInput.nextLine(); 
String[] split = response.split(" "); 

UserInput input = new UserInput(); 

if (split.length > 0) { 
    input.setCommand(split[0]); 
    if (split.length == 2) { 
     input.setItem(split[1]); 
    } 

    return input; 
} 

System.out.println("Invalid command"); 
return null; 
+0

ありがとうございました!これを実装すると、UserInputからStringに変換できないというエラーがあります。これは簡単な修正ですか? – user5959738

+0

メソッドの戻り値の型を 'UserInput'に変更します。 – rdonuk

+0

申し訳ありませんが、私はそれを実現する必要があります。 – user5959738

0
Scanner userInput = new Scanner(System.in); 
    String response = userInput.nextLine(); 
    String command = null; 
    String item = null; 

    String[] split = response.split(" "); 

    if (split.length == 1) { 
     command = split[0]; 

    } else if (split.length == 2) { 
     command = split[0]; 
     item = split[1]; 

    } else { 
     System.out.println("Invalid command"); 
    } 

    System.out.println(command + "/" + item); 
    userInput.close(); 
+0

フィードバックありがとうございました:) – user5959738

-2

ユーザー入力はコマンドのみが含まれている場合は、ループを実行しないでください。ループの前に

if(split.length == 0){ 
     String command = split[0]; 
     return command; 
    } 

を移動してください。

String response = userInput.nextLine(); 
      String[] split = response.split(" "); 
       if(split.length == 0){ 
        String command = split[0]; 
        return command; 
       } 
      for(int i=0; i < split.length; i++){ 
//use simple java class to store the result 
       if(split.length == 1){ 
        String item = split[1]; 
        return item; 
       } 
       else{ 
        System.out.println("Invalid command"); 
       } 
      } 
+0

これは正しく動作せず、長さ= 0の場合にsplit [0]にアクセスしようとすると、IndexOutOfBounds例外がスローされます – pczeus

+0

ああ、私の誤解はOPコードをコピーすることです。彼にそのアイデアを伝えたいだけです。 – ulab

+0

ありがとう、私はそこに私の間違いを認識しませんでした。 – user5959738

関連する問題