0

私はStone、Sheet、Shearsゲームのプログラムを作ることになっています。これには、Math.random(). から来る人間の遊びとコンピューターの遊びが含まれます。ということで、4が入るまで無限大にすることにしました。

仕組みは次のとおりです。

遊びたい?PCに勝て!

  1. 結石
  2. シート
  3. 終了する

4 を入力すると終了しますが、 1 、 2 、または 3 が入力されている限り継続的に実行する必要があります。どうやってやるの。これが私の現在のコードです。while player != 4 の配置が間違っているのはわかっています

import javax.swing.*;

public class StoneSheetShears
{
    public static void main(String[] args)
    {
          String consoleStr;
          int player = 0;    
              int[] numChoices = {1,2,3,4};
              String[] strChoices = {"Stone", "Sheet", "Shears", "Quit"};
              String playerChoice = "";
              String compChoice = "";

              int computer = (int)(Math.random() * 3);
              String output = "";

             while(true)
             {
               do
               {
                  try
                  {
                      consoleStr = JOptionPane.showInputDialog("Beat the computer\n1. Rock\n2. Paper" +
                                        "\n3. Scissors\n4. Quit ");
                      player = Integer.parseInt(consoleStr);

                      for(int x = 0; x <numChoices.length; x++)
                      {
                          if(player == numChoices[x])
                          {
                             playerChoice = strChoices[x];
                          }
                      }

                      for(int y = 0; y <numChoices.length; y++)
                      {
                          if(computer == numChoices[y])
                          {
                             compChoice = strChoices[y];
                          }
                      }
                 }

             }while(player!=4)


          catch (NumberFormatException err)
          {
              JOptionPane.showMessageDialog(null, "There is an error on entry",
                  "Error Message", JOptionPane.WARNING_MESSAGE);
              continue;
          }
          break;
      } 

      if (player == computer)
      {
          output = "Both are " + compChoice;
          JOptionPane.showMessageDialog(null, output, "DRAW!", JOptionPane.INFORMATION_MESSAGE);
      }


      else if (player == 1)
      {
          if (computer == 2)
          {
              output = "Computer move is " + compChoice +
                      "\nYour move is " + playerChoice;
              JOptionPane.showMessageDialog(null,output, "You Lose!",
                            JOptionPane.INFORMATION_MESSAGE);
          }
          else if (computer == 3)
          {
              output = "Computer move is " + compChoice +
                      "\nYour move is " + playerChoice;
              JOptionPane.showMessageDialog(null,output, "You Win!",
                            JOptionPane.INFORMATION_MESSAGE);
          } 
      }

      else if (player == 2)
      {
          if (computer == 3)
          {
              output = "Computer move is " + compChoice +
                      "\nYour move is " + playerChoice;
              JOptionPane.showMessageDialog(null,output, "You Lose!",
                            JOptionPane.INFORMATION_MESSAGE);
          }
          else if (computer == 1)
          {
              output = "Computer move is " + compChoice +
                      "\nYour move is " + playerChoice;
              JOptionPane.showMessageDialog(null,output, "You Win!",
                            JOptionPane.INFORMATION_MESSAGE);
          }
      }

      else if (player == 3)
      {
          if (computer == 1)
          {
              output = "Computer move is " + compChoice +
                      "\nYour move is " + playerChoice;
              JOptionPane.showMessageDialog(null,output, "You Lose!",
                            JOptionPane.INFORMATION_MESSAGE);
          }
          else if (computer == 2)
          {
              output = "Computer move is " + compChoice +
                      "\nYour move is " + playerChoice;
              JOptionPane.showMessageDialog(null,output, "You Win!",
                            JOptionPane.INFORMATION_MESSAGE);
          }         
      }
}
}

基本的に石板と鋏を選択するゲームです。

  1. 人間のプレイヤーは、1 (石)、2 (シート)、3 (ハサミ)、4 (やめる) から選択します。
  2. コンピュータ プレーヤーは、数学ランダムに基づいています。配列を使用して、人間のプレーヤーとコンピューターの動きを定義しました。(配列は Java 構文の一部であり、このような説明には適していません。)
  3. 両方とも同じ動きだったら引き分けです。
  4. 人間が紙を選び、コンピューターのプレーヤーがはさみなら、明らかにコンピューターが勝ちます。同じことが他の選択肢にも当てはまります。
  5. プレーヤーは、1 2 または 3 のいずれかの別の数字を入力します。(これは単に手順 1 を繰り返すだけなので、不要です)。4 を入力するとゲームが停止します。これは、プロンプトに示されているように終了することを意味します。

私の唯一の問題は、4 が入力されるまで継続的に動作させるにはどうすればよいかということです。

4

2 に答える 2

1

このループ

do
{
    // Your choices...
}while (player != 4);

ユーザーがオプションを選択した場合にのみ終了します4。ゲームロジックはこのループ内に含まれている必要があります(つまり、while(true)ループを失う可能性があります)。

これは、このタイプのアプリケーションをユーザーに提示するための恐ろしい方法でもあります。Swingはイベント駆動型の環境です。つまり、ユーザーにUIを提示し、そこでのインタラクションに反応します。あなたのコードの見た目から、あなたは基本的なコマンドラインプログラムを取り、変換しようとしました。これは決して良い考えではありません。

グラフィカルユーザーインターフェイスに、このようなフローを制御するループが含まれることはめったにありません。

より良い選択(IMHO)は、独自のフレーム/ダイアログを作成し、ユーザーにオプションを提示することです。各オプションは、ゲームがプレイまたは終了される一連のイベントをトリガーします。

これにより、ユーザーが複数のポップアップウィンドウに襲われるのを防ぐことができます。

ここに画像の説明を入力してください

(これは、可能なインターフェイス設計の1つにすぎません)

public class RockPaperScissors {

    public static void main(String[] args) {
        new RockPaperScissors();
    }

    public RockPaperScissors() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new GamePane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class GamePane extends JPanel {

        public static final int STONE = 0;
        public static final int SHEET = 1;
        public static final int SHEARS = 2;

        private JButton stoneButton;
        private JButton sheetButton;
        private JButton shearsButton;
        private JButton quitButton;

        private JLabel player;
        private JLabel computer;
        private JLabel winner;

        public GamePane() {

            winner = new JLabel("Come play", JLabel.CENTER);
            player = new JLabel("Player", JLabel.CENTER);
            computer = new JLabel("computer", JLabel.CENTER);

            stoneButton = new JButton(new GameAction("Stone", STONE));
            sheetButton = new JButton(new GameAction("Sheet", SHEET));
            shearsButton = new JButton(new GameAction("Shear", SHEARS));
            quitButton = new JButton("Quit");

            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.anchor = GridBagConstraints.CENTER;
            gbc.gridx = 0;
            gbc.gridy = 0;
            gbc.gridwidth = 4;
            gbc.fill = GridBagConstraints.HORIZONTAL;
            add(winner, gbc);

            gbc.anchor = GridBagConstraints.WEST;
            gbc.gridy++;
            gbc.gridwidth = 2;
            add(player, gbc);

            gbc.anchor = GridBagConstraints.EAST;
            gbc.gridx = 2;
            add(computer, gbc);

            gbc.anchor = GridBagConstraints.CENTER;
            gbc.gridy++;
            gbc.gridwidth = 1;
            gbc.gridx = 0;
            add(stoneButton, gbc);

            gbc.gridx++;
            add(sheetButton, gbc);

            gbc.gridx++;
            add(shearsButton, gbc);

            gbc.gridx++;
            add(quitButton, gbc);

            quitButton.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    System.exit(0);
                }
            });

        }

        protected void play(int action) {

            int ai = (int)Math.round((Math.random() * 2));
            updateChoice("Computer", computer, ai);
            updateChoice("Player", player, action);

            if (ai == action) {
                winner.setText("Draw!");
            } else if (action == STONE) {
                if (ai == SHEET) {
                    winner.setText("Computer Wins");
                } else if (ai == SHEARS) {
                    winner.setText("Player Wins");
                }
            } else if (action == SHEET) {
                if (ai == STONE) {
                    winner.setText("Player Wins");
                } else if (ai == SHEARS) {
                    winner.setText("Computer Wins");
                }
            } else if (action == SHEARS) {
                if (ai == STONE) {
                    winner.setText("Computer Wins");
                } else if (ai == SHEET) {
                    winner.setText("Player Wins");
                }
            }
        }

        protected void updateChoice(String prefix, JLabel label, int action) {

            switch (action) {
                case STONE:
                    label.setText(prefix + " chose STONE");
                    break;
                case SHEET:
                    label.setText(prefix + " chose SHEET");
                    break;
                case SHEARS:
                    label.setText(prefix + " chose SHEARS");
                    break;
            }

        }

        public class GameAction extends AbstractAction {

            private int action;

            public GameAction(String text, int action) {
                this.action = action;
                putValue(NAME, text);
            }

            @Override
            public void actionPerformed(ActionEvent e) {
                play(action);
            }

        }

    }

}

アップデート

答えの最初の部分で述べたように:

2つのループは必要ありません。内側のループは、ユーザーがオプションを選択するまで外側のループが実行されないようにします4

ゲームロジックはdo-whileループに属しています。

public class StoneSheetShears {

    public static void main(String[] args) {
        String consoleStr;
        int player = 0;
        int[] numChoices = {1, 2, 3, 4};
        String[] strChoices = {"Stone", "Sheet", "Shears", "Quit"};
        String playerChoice = "";
        String compChoice = "";

        int computer = -1; //(int) (Math.random() * 3);
        String output = "";

        do {

            try {

                consoleStr = JOptionPane.showInputDialog("Beat the computer\n1. Rock\n2. Paper"
                        + "\n3. Scissors\n4. Quit ");

                player = Integer.parseInt(consoleStr);

                for (int x = 0; x < numChoices.length; x++) {
                    if (player == numChoices[x]) {
                        playerChoice = strChoices[x];
                    }
                }

                computer = (int) Math.round(Math.random() * 3);
                compChoice = strChoices[computer];

                if (player == computer) {
                    output = "Both are " + compChoice;
                    JOptionPane.showMessageDialog(null, output, "DRAW!", JOptionPane.INFORMATION_MESSAGE);
                } else if (player == 1) {
                    if (computer == 2) {
                        output = "Computer move is " + compChoice
                                + "\nYour move is " + playerChoice;
                        JOptionPane.showMessageDialog(null, output, "You Lose!",
                                JOptionPane.INFORMATION_MESSAGE);
                    } else if (computer == 3) {
                        output = "Computer move is " + compChoice
                                + "\nYour move is " + playerChoice;
                        JOptionPane.showMessageDialog(null, output, "You Win!",
                                JOptionPane.INFORMATION_MESSAGE);
                    }
                } else if (player == 2) {
                    if (computer == 3) {
                        output = "Computer move is " + compChoice
                                + "\nYour move is " + playerChoice;
                        JOptionPane.showMessageDialog(null, output, "You Lose!",
                                JOptionPane.INFORMATION_MESSAGE);
                    } else if (computer == 1) {
                        output = "Computer move is " + compChoice
                                + "\nYour move is " + playerChoice;
                        JOptionPane.showMessageDialog(null, output, "You Win!",
                                JOptionPane.INFORMATION_MESSAGE);
                    }
                } else if (player == 3) {
                    if (computer == 1) {
                        output = "Computer move is " + compChoice
                                + "\nYour move is " + playerChoice;
                        JOptionPane.showMessageDialog(null, output, "You Lose!",
                                JOptionPane.INFORMATION_MESSAGE);
                    } else if (computer == 2) {
                        output = "Computer move is " + compChoice
                                + "\nYour move is " + playerChoice;
                        JOptionPane.showMessageDialog(null, output, "You Win!",
                                JOptionPane.INFORMATION_MESSAGE);
                    }
                }

            } catch (NumberFormatException exp) {

                JOptionPane.showMessageDialog(null, "Bad choice", "Bad Choice", JOptionPane.ERROR_MESSAGE);

            }

        } while (player != 4);
    }
}
于 2012-12-18T02:19:22.060 に答える
0

あなたが提供した手順は、コードを修正する方法を理解するための素晴らしい出発点です (または、必要に応じて最初からやり直すこともできます)。これまでのコメントでの議論では、手順を英語で説明することに集中してきました。いくつかのコンピューター プログラミングの概念を紹介して、これらの手順を少し洗練させてみましょう。特に、ある種のループが必要です。ただし、重要な点を強調するために、Java 構文にはまだあまり関心がありません。私たちが理解できるものを書いている限り、コンパイラがそれを理解するかどうかは問題ではありません。そうは言っても、ここにあなたの説明に対する私の提案された修正があります:

Continue while human input is not 4
    Human player will choose from 1 (stone), 2 (sheet), 3(shears), 4(to quit)
    Computer player is based on math random.
    Determine the winner (or if it's a draw).

ループ内で繰り返されるステップを示すためにインデントを使用していることに注意してください。また、最後のステップの詳細については触れていません。その部分の実行方法は理解されていると思います。

この短い説明は、Java に翻訳できるようになりました。ループが 1 つしかないことに注意してください。これは while または do...while ループとして実装できます。

于 2012-12-18T19:27:20.917 に答える