没有期望的输出,可能的原因是过载

时间:2011-11-25 02:00:18

标签: java swing

我正在制作一个简单的Rock Paper Scissors游戏,但通过添加两个选项“Lizard”和“Spock”​​来改变它的传统方式。这个游戏的目的是让它比传统的游戏方式更复杂。不确定我是否正在重载动作事件,但我在代码中得到了这个奇怪的错误。假设有5个按钮,包含Rock Paper Scissors等,以及1个JTextArea。问题在于每当我点击“Spock”​​按钮并且字符串AI获得“Spock”​​/选择[4]时,它似乎忽略了下面的代码,我希望它响应,而不是“你失去了” ......哈哈“选项,

if ((e.getSource() == b5) && (AI == choices[4])) {
  text.append("It's a Tie!\n\n");
  return;
}

此外,当点击“蜥蜴”按钮时,它也会忽略下面的代码,然后选择“你赢了!”改为选择

if ((e.getSource() == b4) && (AI == choices[3])) {
  text.append("It's a Tie!\n\n");
  return;
}

要玩的规则

Scissors cut paper
Paper covers rock
Rock crushes lizard
Lizard poisons Spock
Spock smashes scissors
Scissors decapitate lizard
Lizard eats paper
Paper disproves Spock
Spock vaporizes rock
Rock crushes scissors

为那些好奇的人完成代码。 http://www.mediafire.com/?x4853rq3a4fp4ah *没有病毒。 ;)

代码:

import java.awt.event.*;
import javax.swing.*;


   class Main2 implements ActionListener
  {
    JTextArea text;
    JButton b1;
    JButton b2;
    JButton b3;
    JButton b4;
    JButton b5;
   String[] choices = { "Rock", "Paper", "Scissors", "Lizard", "Spock" };
   int l = this.choices.length;

   public static void main(String[] args)
   {
    Main2 gui = new Main2();
    gui.go();
   }
   public void go() {
    JFrame frame = new JFrame("Rock Paper Scissors");
    this.text = new JTextArea(13,40);
    JPanel panel1 = new JPanel();
    JPanel panel2 = new JPanel();
    b1 = new JButton(choices[0]);
    b2 = new JButton(choices[1]);
    b3 = new JButton(choices[2]);
    b4 = new JButton(choices[3]);
    b5 = new JButton(choices[4]);
    b1.addActionListener(this);
    b2.addActionListener(this);
    b3.addActionListener(this);
    b4.addActionListener(this);
    b5.addActionListener(this);
    text.setEditable(false);

    JScrollPane scroller = new JScrollPane(text);
    scroller.setVerticalScrollBarPolicy(22);

    panel1.add(scroller);
    panel2.add(this.b1);
    panel2.add(this.b2);
    panel2.add(this.b3);
    panel2.add(this.b4);
    panel2.add(this.b5);

    frame.getContentPane().add("Center", panel1);
    frame.getContentPane().add("South", panel2);
    frame.setSize(500, 300);
    frame.setVisible(true);
  }

  public void actionPerformed(ActionEvent e)
  {
    int nr = (int)(Math.random() *l);
    String AI = choices[nr];

    if (e.getSource() == b1) {
      text.append("Your choice was " + choices[0] + "\nComputer's choice was " + AI + "\n");
    }
    if (e.getSource() == b2) {
      text.append("Your choice was " + choices[1] + "\nComputer's choice was" + AI + "\n");
    }
    if (e.getSource() == b3) {
      text.append("Your choice was " + choices[2] + "\nComputer's choice was " + AI + "\n");
    }
    if (e.getSource() == this.b4) {
      text.append("Your choice was " + choices[3] + "\nComputer's choice was " + AI + "\n");
    }
    if (e.getSource() == this.b5) {
      text.append("Your choice was " + choices[4] + "\nComputer's choice was " + AI + "\n");
    }

    if (((e.getSource() ==b1) && (AI == choices[2])) || (AI == choices[3])) {
      text.append("You won!\n\n");
      return;
    }
    if ((e.getSource() == b1) && (AI == choices[0])) {
      text.append("It's a Tie!\n\n");
      return;
    }

    if (((e.getSource() == b1) && (AI == choices[1])) || (AI == choices[4])) {
      text.append("You Lost... Haha!\n\n");
      return;
    }

    if (((e.getSource() == b2) && (AI == choices[0])) || (AI == choices[4])) {
      text.append("You won!\n\n");
      return;
    }
    if ((e.getSource() == b2) && (AI == choices[1])) {
      text.append("It's a Tie!\n\n");
      return;
    }

    if (((e.getSource() == b2) && (AI == choices[2])) || (AI == choices[3])) {
      text.append("You Lost... Haha!\n\n");
      return;
    }

    if (((e.getSource() == b3) && (AI == choices[1])) || (AI == choices[3])) {
      text.append("You won!\n\n");
      return;
    }
    if ((e.getSource() == b3) && (AI == choices[2])) {
      text.append("It's a Tie!\n\n");
      return;
    }

    if (((e.getSource() == b3) && (AI == choices[0])) || (AI == choices[4])) {
      text.append("You Lost... Haha!\n\n");
      return;
    }

    if (((e.getSource() == b4) && (AI == choices[1])) || (AI == choices[4])) {
      text.append("You won!\n\n");
      return;
    }
    if ((e.getSource() == b4) && (AI == choices[3])) {
      text.append("It's a Tie!\n\n");
      return;
    }

    if (((e.getSource() == b4) && (AI == choices[0])) || (AI == choices[2])) {
      text.append("You Lost... Haha!\n\n");
      return;
    }

    if (((e.getSource() == b5) && (AI == choices[0])) || (AI == choices[2])) {
      text.append("You won!\n\n");
      return;
    }
    if ((e.getSource() == b5) && (AI == choices[4])) {
      text.append("It's a Tie!\n\n");
      return;
    }

    if (((e.getSource() == b5) && (AI == choices[1])) || (AI == choices[3]))    {
      text.append("You Lost... Haha!\n\n");
      return;
     }
    }
   }

1 个答案:

答案 0 :(得分:3)

正如Hot Licks建议的那样,这是你的问题:你使用==检查字符串等效,而不是使用equals(...)equalsIgnoreCase(...)方法。理解==检查两个对象是否相同而不是您感兴趣的。另一方面,这些方法检查两个字符串是否在同一个字符中具有相同的字符订单,这就是重要的事情。而不是

if (fu == "bar") {
  // do something
}

做,

if (fu.equals("bar")) {
  // do something
}

,或者

if (fu.equalsIgnoreCase("bar")) {
  // do something
}

另一个问题,为什么不使用win-matrix简单,轻松地和简单地检查一个选择是否胜过另一个,而不是使用if块的chit-load。枚举对此有用,类似这样的东西可以起作用:

import java.util.Comparator;

public enum HandGameChoice  {
   ROCK,
   PAPER,
   SCISSORS,
   LIZARD,
   SPOCK;

   private static MyComparator myComparator = new MyComparator();

   public static int compare(HandGameChoice o1, HandGameChoice o2) {
      return myComparator.compare(o1, o2);
   }

   private static class MyComparator implements Comparator<HandGameChoice> {
      private int[][] winMatrix = {
            { 0, -1,  1,  1, -1},
            { 1,  0, -1, -1,  1},
            {-1,  1,  0,  1, -1},
            {-1,  1, -1,  0,  1},
            { 1, -1,  1, -1,  0}
      };

      @Override
      public int compare(HandGameChoice o1, HandGameChoice o2) {
         return winMatrix[o1.ordinal()][o2.ordinal()];
      }
   }
}

测试此枚举的类可能如此:

public class TestHandGameChoices {
   public static void main(String[] args) {
      for (HandGameChoice choice1 : HandGameChoice.values()) {
         for (HandGameChoice choice2 : HandGameChoice.values()) {
            int value = HandGameChoice.compare(choice1, choice2);
            String result = "";
            if (value > 0) {
               result = "win";
            } else if (value < 0) {
               result = "lose";
            } else {
               result = "tie";
            }
            System.out.printf("%-8s vs %-8s: %s%n", choice1, choice2, result);
         }
      }
   }
}

测试类的输出显示:

ROCK     vs ROCK    : tie
ROCK     vs PAPER   : lose
ROCK     vs SCISSORS: win
ROCK     vs LIZARD  : win
ROCK     vs SPOCK   : lose
PAPER    vs ROCK    : win
PAPER    vs PAPER   : tie
PAPER    vs SCISSORS: lose
PAPER    vs LIZARD  : lose
PAPER    vs SPOCK   : win
SCISSORS vs ROCK    : lose
SCISSORS vs PAPER   : win
SCISSORS vs SCISSORS: tie
SCISSORS vs LIZARD  : win
SCISSORS vs SPOCK   : lose
LIZARD   vs ROCK    : lose
LIZARD   vs PAPER   : win
LIZARD   vs SCISSORS: lose
LIZARD   vs LIZARD  : tie
LIZARD   vs SPOCK   : win
SPOCK    vs ROCK    : win
SPOCK    vs PAPER   : lose
SPOCK    vs SCISSORS: win
SPOCK    vs LIZARD  : lose
SPOCK    vs SPOCK   : tie

然后GUI会像这样使用它:

import java.awt.*;
import java.awt.event.*;
import java.util.Random;
import javax.swing.*;

@SuppressWarnings("serial")
public class HandGameGui extends JPanel {
   private JTextArea tArea = new JTextArea(13, 40);

   public HandGameGui() {
      ButtonListener btnListener = new ButtonListener();
      JPanel btnPanel = new JPanel(new GridLayout(1, 0, 5, 0));
      for (HandGameChoice hgChoice : HandGameChoice.values()) {
         String choiceString = hgChoice.name();
         String initCapChoiceString = choiceString.substring(0, 1)
               + choiceString.substring(1, choiceString.length()).toLowerCase();

         JButton button = new JButton(initCapChoiceString);
         button.setActionCommand(choiceString);
         button.addActionListener(btnListener);
         btnPanel.add(button);
      }

      setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
      setLayout(new BorderLayout(5, 5));
      add(new JScrollPane(tArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
            JScrollPane.HORIZONTAL_SCROLLBAR_NEVER), BorderLayout.CENTER);
      add(btnPanel, BorderLayout.PAGE_END);
   }

   private class ButtonListener implements ActionListener {
      private Random random = new Random();
      @Override
      public void actionPerformed(ActionEvent e) {
         String actionCommand = e.getActionCommand();
         HandGameChoice userChoice = HandGameChoice.valueOf(actionCommand);
         int randomInt = random.nextInt(HandGameChoice.values().length);
         HandGameChoice aiChoice = HandGameChoice.values()[randomInt];

         int gameResult = HandGameChoice.compare(userChoice, aiChoice);
         String resultStr = "";
         if (gameResult > 0) {
            resultStr = "win";
         } else if (gameResult < 0) {
            resultStr = "lose";
         } else {
            resultStr = "tie";
         }

         String output = String.format("You chose %s, and the computer chose %s; you %s%n", 
               userChoice, aiChoice, resultStr);
         tArea.append(output);
      }
   }

   private static void createAndShowGui() {
      HandGameGui mainPanel = new HandGameGui();

      JFrame frame = new JFrame("Rock Paper Scissors Lizard Spock");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}