2016-03-20 3 views
0

Я создаю текстовую приключенческую игру на Java, в которой пользователь вводит команды, такие как «H» для справки, или «N» для перемещения на север. В некоторых случаях пользователю необходимо ввести что-то вроде клавиши «Т», чтобы взять ключ, который находится в этой комнате. Поэтому из-за этого мне нужно использовать метод 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; 
    } 
} 

Это мой товар класс:

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' массив не имеет элементов, так что ISN» t даже четный элемент в индексе '[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, так и элемент? – user5959738

+0

Перед возвратом команды, которая имеет как команду, так и элемент, она проверяет оба аргумента. Итак, если для команды был введен только «H», но ни один элемент не был введен, он снова выдаст ошибку, которую должен ввести элемент. Только после проверки обоих существующих объектов будет создан и возвращен объект Command. Но я отредактирую ответ, чтобы разрешить конструктор по умолчанию без аргументов, а также методы 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

Это определенно не работает и все равно будет генерировать исключение IndexOutOfBounds при попытке получить доступ к split [0], если length = 0 – pczeus

+0

А, моя ошибка - скопировать код OPs. просто хочу показать ему эту идею. – ulab

+0

Спасибо, я даже не осознал свою ошибку. – user5959738

Смежные вопросы