2017-04-07 53 views
1

我正在製作基於文本的冒險遊戲。我試圖讓遊戲根據他們對某些問題的回答爲玩家選擇一個「課堂」。 (例如,如果玩家選擇偷偷摸摸的或隱身的傾斜答案,那麼遊戲將向他們分配適合這種類型的人的「流氓」類。如何向用戶詢問一組問題並存儲答案

到目前爲止,我已經創建了這個方法,我想稍後調用主程序,然後基於返回值是什麼,我將使用另一個條件語句通過調用設置方法來設置玩家類別。

這是我的方法到目前爲止。將有非常非常長的chooseSpec方法,因爲我想要至少10個問題。我的問題具體是什麼是最有效的方法來寫出來,並在一個方法中以正確的方式去做這一切?

public static int chooseSpec(Scanner in) { 
    int war = 0; //counter for warrior class 
    int rog = 0; //counter for rogue class 
    int mag = 0; //counter for magic class 
    int choice; //users choice, a number between 1 and 3. 

    System.out.println("While out hunting, you come across a deer which has been badly mauled by a wolf. What do you do?" + "\n" + 
         "1. Draw your dagger and end it's suffering" + "\n" + 
         "2. Attempt to heal it with a herbal concoction, knowing it may not work." + "\n" + 
         "3. Leave it, and allow nature to take it's course."); 
    choice = in.nextInt(); 

    switch (choice) { 
     case 1: 
      war += 1; 
      break; 

     case 2: 
      mag += 1; 
      break; 
     case 3: 
      rog +=1; 
    } 
    return choice; 
} 
+1

這是一個實現flavory,不是技術問題,請google;) –

+0

歡迎來到Stack Overflow!如果你還沒有參加[旅遊],請看[問]。無論如何,我認爲你應該更多地關注面向對象編程(OOP)。查看[classes](https://docs.oracle.com/javase/tutorial/java/concepts/class.html)和[collections](https://docs.oracle.com/javase/7/docs/api /java/util/Collections.html)。你可以用任何東西做一堂課。對於初學者來說,可能會嘗試創建一個名爲「Question」的類,其中包含與問題相關的所有信息。 – PJvG

+0

另外,如果您有關於*軟件設計*的問題,那麼這些更適合http://softwareengineering.stackexchange.com/。如果您希望獲得有關代碼的反饋,則可以嘗試http://codereview.stackexchange.com/。 – PJvG

回答

2

您應該將所有問題和答案存儲在一個對象中。這樣,你可以混合每個問題的答案,目前選擇總是1將保證相同的答案。

其次它允許您在每個問題中添加任意數量的答案,甚至在每次開始遊戲時混合他們的順序。

這也很好用更多的Java抽象這裏:

public ClassType chooseSpec(List<Question> questions, Scanner in) { 

    List<ClassType> selectedAnswers = new ArrayList<>(questions.size()); 
     // iterate over all your questions 
    for(Question question: questions) { 
     // print question and all answers 
     System.out.println(question.getQuestion() + "\n" 
       + question.getAnswers().stream().map(Answer::getQuestion) 
       .collect(Collectors.joining("\n"))); 

     int choice = in.nextInt(); 
     if(choice >= question.getAnswers().size()){ 
      // check if answer is within the scope 
      throw IllegalArgumentException("There are only "+question.getAnswers() +" answers"); 
     } 
     // add selected answer type to global result list 
     selectedAnswers.add(question.getAnswers().get(choice-1).getClassType()); 
    } 

    return findMostPolularClass(selectedAnswers); 
} 

private ClassType findMostPolularClass(List<ClassType> selectedAnswers){ 
    // might be too fancy, but it will find most frequent answer 
    Map<ClassType, Long> occurences = selectedAnswers.stream().collect(Collectors.groupingBy(e -> e, Collectors.counting())); 
    return occurences.entrySet().stream() 
      .max(Comparator.comparing(Map.Entry::getValue)).get().getKey(); 
} 

舉行的問題,所有的答案:

static class Question { 

    private final String question; 
    private final List<Answer> answers; 

    public Question(String question, List<Answer> answers) { 
     this.question = question; 
     this.answers = answers; 
    } 

    public String getQuestion() { 
     return question; 
    } 

    public List<Answer> getAnswers() { 
     return answers; 
    } 
} 

每個答案定義的答覆文件,以及它屬於最好

哪一類
class Answer { 

    private final String question; 
    private final ClassType classType; 
    // static constructors, help to work with this model 
    public static Answer mageAnswer(String question) { 
     return new Answer(question, ClassType.MAGE); 
    } 

    public static Answer wariorAnswer(String question) { 
     return new Answer(question, ClassType.WARIOR); 
    } 

    private Answer(String question, ClassType classType) { 
     this.question = question; 
     this.classType = classType; 
    } 

    public ClassType getClassType() { 
     return classType; 
    } 

    public String getQuestion() { 
     return question; 
    } 
} 

//將您的所有課程存儲在這裏,它比可記憶的數字更具可讀性小號:)

enum ClassType { 
    MAGE, WARIOR, ARCHER 
} 
0

您應該將所有問題存儲在一個集合中。像arraylist。假設你有10個問題,這個方法應該在迭代問題arraylist的foreach循環中調用。這樣你的方法將被重用。

0

從你的要求,你要處理三個不同Professions

  • 戰士
  • 盜賊
  • 法師

這些職業不抱任何狀態並且新實例不是動態構建的。因此,一個Enumeration將是一個不錯的人選,以表示它們:

public enum Profession { 
    WARRIOR, 
    ROGUE, 
    MAGE; 
} 

接下來你要求玩家選擇哪個與1. Profession和2相關的Answer。用Token,輸入你從鍵盤讀取:

public class Answer { 

    public static Answer of(Profession profession, String token, String description) { 
     return new Answer(description, profession, token); 
    } 

    private final String description; 
    private final Profession profession; 
    private final String token; 

    public Answer(String description, Profession profession, String token) { 
     this.description = requireNonNull(description); 
     this.profession = requireNonNull(profession); 
     this.token = requireNonNull(token); 
    } 

    public String getDescription() { 
     return description; 
    } 

    public Profession getProfession() { 
     return this.profession; 
    } 

    public String getToken() { 
     return token; 
    } 

    public boolean isMatch(String token) { 
     return this.token.equals(token); 
    } 
} 

你想與Answer做的是:

  • 它呈現給玩家。
  • 檢查從玩家處獲得的令牌是否與Answer所關聯的令牌匹配。以可讀形式構建Answer

AnswersQuestions的一部分,它們不保持狀態或動態創建。再一次的Enumeration將代表他們很好:

public enum Question { 

    MAULED_DEER("While out hunting, you come across a deer which has been badly mauled by a wolf. What do you do?", 
     Answer.of(WARRIOR, "1", "Draw your dagger and end it's suffering."), 
     Answer.of(ROGUE, "2", "Attempt to heal it with a herbal concoction, knowing it may not work."), 
     Answer.of(MAGE, "3", "Leave it, and allow nature to take it's course.")), 

    GAME_DEVELOPMENT("While playing games you decided to develop your very own. Which language do you choose?", 
      Answer.of(MAGE, "a", "OOD with Java."), 
      Answer.of(WARRIOR, "b", "OOD and FP using Scala."), 
      Answer.of(ROGUE, "c", "Pure FP with Haskel.")); 

    private final String description; 
    private final List<Answer> answers; 

    Question(String description, Answer... answers) { 
     this.description = description; 
     this.answers = Arrays.asList(answers); 
    } 

    public String getDescription() { 
     return description; 
    } 

    public List<Answer> getAnswers() { 
     return answers; 
    } 

    public Set<Answer> getMatches(String token) { 
     return answers.stream() 
       .filter(answer -> answer.isMatch(token)) 
       .collect(Collectors.toSet()); 
    } 
} 

Questions必須是:

  • 他們Answers一起渲染。
  • 應該確定哪個Answers確實匹配給定的令牌(從玩家處獲得)。

但是你要問玩家很多Questions並且想跟蹤他給出的Answers。更準確地說,Profession你與Answer相關聯。你想跟蹤每個Profession當前比分:

public class Scores { 

    private Map<Profession, AtomicInteger> scores = new HashMap<Profession, AtomicInteger>() {{ 
     for (Profession profession : Profession.values()) { 
      put(profession, new AtomicInteger()); 
     } 
    }}; 

    private int max = 0; 

    public void incrementIf(boolean isTrue, Profession profession) { 
     if (isTrue) { 
      int score = scores.get(profession).incrementAndGet(); 
      max = Math.max(max, score); 
     } 
    } 

    public Set<Profession> getWinners() { 
     return Arrays.stream(Profession.values()) 
       .filter(profession -> scores.get(profession).get() == max) 
       .collect(Collectors.toSet()); 
    } 
} 

類型Scores的責任確定和哪個Profession遞增的得分。最後,應當計算查詢的Winners

public class Inquiry { 

    public Set<Profession> obtainChoice(Scanner scanner) { 
     Scores scores = new Scores(); 
     for (Question question : Question.values()) { 
      String token = ask(question, scanner); 
      question.getAnswers().forEach(answer -> 
        scores.incrementIf(answer.isMatch(token), answer.getProfession())); 
     } 
     return scores.getWinners(); 
    } 

    private String ask(Question question, Scanner scanner) { 
     System.out.println(question.getDescription()); 
     question.getAnswers().forEach(answer -> 
       System.out.println(answer.getToken() + ") " + answer.getDescription())); 
     do { 
      String token = scanner.nextLine(); 
      for (Answer answer : question.getAnswers()) { 
       if (token.equals(answer.getToken())) { 
        return token; 
       } 
      } 
      System.out.println("Try again and select a valid answer please!"); 
     } while (true); 
    } 
} 

的最後一塊拼圖缺少的是應用程序本身,這會觸發查詢:

public class Game { 

    public static void main(String[] args) { 
     try (Scanner scanner = new Scanner(System.in)) { 
      Set<Profession> choices = new Inquiry().obtainChoice(scanner); 
      if (choices.size() == 1) { 
       System.out.println("You are a true " + choices.iterator().next()); 
      } else { 
       System.out.println("You havn't found your path yet and hence must choose between:"); 
       choices.forEach(profession -> System.out.println(" - " + profession)); 
      } 
     } 
    } 
} 

這種設計致力成爲readableextendable等等你可以輕鬆地改變事物。

玩得開心!

相關問題