0

私は非常に基本的な Java ベースの RPG ゲームを作成しています。多くのオプションがあり、入力できるようになったときに「x」を押すと自動的にゲームが終了するようにしたいと考えています。ユーザーが進行するたびに「if-then」ステートメントを継続的に追加したくありません。

やりたくないこと: (これを 50 回以上行う必要がある: インベントリ、ゲームの終了、キャラクター情報など)

switch (choice1)
  {
     case "x":
        System.out.println("\nYou quit the game!");
        System.exit(0);
        break;  
     }    

私が持っているもの:(動作しません)

import java.util.Scanner;
import java.awt.*;
import java.awt.event.*;


public class TheDungeon extends KeyAdapter
{
    public void keyPressed(KeyEvent e) {
        char ch = e.getKeyChar();
        if (ch == 'a')
        {
        System.out.println("You pressed A"); 
        }    
    }   
    public static void main(String[] args)
    {
    /* My variables...

    */
    System.out.println("e: Check experience and level");
    System.out.println("c: Character Information");
    System.out.println("i: Inventory");
    System.out.println("x: Quit Game");
    choice1 = keyboard.nextLine();
    switch (choice1)
        {
        case "x":                                         //This section
            System.out.println("\nYou quit the game!");   //here works
            System.exit(0);                               //but I don't
        break;                                            //want to add this section
    }                                                     //every time the user
                                                          //progresses.
4

2 に答える 2

0

KeyAdaptersおよび/または使用するKeyListenersには、これらのアダプター/リスナーも追加する Gui を作成する必要があります。

ユーザー アクションで現在読み取っている方法は、コンソール アプリで有効な方法です。

BlakeP の回答の拡張を編集determineActionする方法がある場合は、印刷したテキストのマップを持つことができるので、キーの特別なアクションを追加するだけで済みます。

Map<Character, String> actionText = new HashMap<Character, String>();

actionText.put('x', "\nYou quit the game!");
actionText.put('i', "\nInventory Items:\n  Things are here");


private void determineAction(char choice) {
   System.out.println(actionText.get(choice));
   switch (choice1)
   {
     case "x":                                        
         System.exit(0);                               
     break;                                    
   }
}

または、各特別なアクションを実行する別の方法を用意する必要があります。これにより、スイッチが短くなり、読みやすくなります。そのようです

private void determineAction(char choice) {
   System.out.println(actionText.get(choice));
   switch (choice1)
   {
     case "x":                                        
         doExit();                              
         break;                                    
     case "i":
         printInventory();
         break;

   }
}

private void doExit()
{
    System.out.println("\nYou quit the game!");
    System.exit(0);
}

private void printInventory()
{
    System.out.println("\nInventory Items:");
    System.out.println("\n  Things are here");
}
于 2013-09-04T20:51:47.757 に答える