0

我应该做一个石头,床单和剪刀游戏的程序。它涉及来自 Math.random() 的人类游戏和计算机游戏。它实际上是有效的,但我必须在我喜欢玩的时候一次又一次地重新运行它。所以我决定让它无限,直到输入 4。

这里'它是如何工作的:

想玩?打败电脑!

  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

This loop

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

Will only exit if the user selects option 4. You game logic should be contained within this loop (meaning you can lose the while(true) loop).

This is also a horrible way to present this type of application to a user. Swing is a event driven environment, meaning you present you UI to the user and react to there interactions to it. From the looks of you code, you've taken a basic command line program and tried to convert. This is never a good idea.

Graphical user interfaces should rarely contain loops that control flow like this.

A better choice (IMHO), would be to create your own frame/dialog and present the options to the user. Each option would trigger a sequence of events by which the game would either be played or terminated.

This prevents the user being bombarded with multiple popup windows, which is just annoying.

enter image description here

(This is just one possible interface design)

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);
            }

        }

    }

}

UPDATE

As stated in the first part of the answer:

You don't need two loops. You inner loop is preventing the outter loop from running UNTIL the user selects option 4.

You game logic belongs in the do-while loop.

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。请注意,只有一个循环。您可以将其实现为 while 或 do...while 循环。

于 2012-12-18T19:27:20.917 回答