Java猜谜游戏

时间:2010-08-05 23:34:03

标签: java

我正在尝试用Java编写一个程序,从1-1000中取一个随机数,然后猜测它背景颜色变为蓝色(冷)或红色(暖)如果它们在数字中。我是java GUI的新手,但我认为其余逻辑是正确的,不确定。它编译,但猜测按钮不起作用。任何指导将不胜感激。

package guessGame;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.color.*;
import java.util.Random;


import java.util.Random;
import java.util.logging.FileHandler;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class GuessGame extends JFrame
{
    private JFrame mainFrame;
    private JButton GuessButton;
    private JButton QuitButton;
    private JLabel prompt1, prompt2;
    private JTextField userInput;
    private JLabel comment = new JLabel("What is your destiny?");
    private JLabel comment2 = new JLabel (" ");
    //private int number, guessCount;
    //private int lastGuess;
    private int randomNumber;
    private Color background;


    public GuessGame()
    {
        mainFrame = new JFrame ("Guessing Game!");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //Creates components
        GuessButton = new JButton("Guess");
        QuitButton  = new JButton("Quit");
        prompt1 = new JLabel("I have a number between 1 and 1000.");
        prompt2 = new JLabel("Can you guess my number? Enter your Guess:");
        comment = new JLabel ("What is your destiny?");
        comment2 = new JLabel (" ");
        userInput = new JTextField(5);
        //userInput.addActionListener(new GuessHandler());

        //content pane
        Container c = mainFrame.getContentPane();
        c.setLayout(new FlowLayout());

        //adding component to the pane
        c.add(prompt1);
        c.add(prompt2);
        c.add(userInput);
        c.add(comment2);
        c.add(GuessButton);
        c.add(QuitButton);
        c.add(comment);

        GuessButton.setMnemonic('G');
        QuitButton.setMnemonic('Q');

        mainFrame.setSize(300,200);
        mainFrame.setLocationRelativeTo(null);
        mainFrame.setVisible(true);
        mainFrame.setResizable(false);

        // define and register window event handler
    //  mainFrame.addWindowListener(new WindowAdapter() {
    //      public void windowClosing(WindowEvent e) 
    //      { System.exit(0); }
    //  });

        //creating the handler
        GuessButtonHandler ghandler = new GuessButtonHandler(); //instantiate new object
        GuessButton.addActionListener(ghandler); // add event listener

        QuitButtonHandler qhandler = new QuitButtonHandler(); 
        QuitButton.addActionListener(qhandler); 



    }

    public void paint (Graphics g)
    {
        super.paint(g);
        setBackground(background);
    }

    class QuitButtonHandler implements ActionListener
    {
        public void actionPerformed(ActionEvent e)
        {
            System.exit(0);
        }
    }

    class GuessButtonHandler implements ActionListener
    {
        public void actionPerformed(ActionEvent e)
        {
            int getUserInput=0;
            int diff;
            int Difference;
            randomNumber = new Random().nextInt(1001);
            try {
                getUserInput = Integer.parseInt(
                        userInput.getText().trim());
            } catch (NumberFormatException ex){
                comment.setText("Enter a VALID number!");
                return;
            }
            if (getUserInput == randomNumber){
                JOptionPane.showMessageDialog(null, "CONGRATULATIONS! You got it!!",
                        "Random Number: " + randomNumber, 
                        JOptionPane.INFORMATION_MESSAGE);
                randomNumber = new Random().nextInt(1000) + 1;
                return;
            }
            if (getUserInput > randomNumber){
                comment.setText( "Too High. Try a lower number." );
                diff=getUserInput - randomNumber;
                Difference=Math.abs(diff);
            } else {
                comment.setText( "Too Low. Try a higher number." );
                diff=randomNumber - getUserInput;
                Difference=Math.abs(diff);
            }

            if(Difference<=25){
                comment2.setText("Cold");
                setBackgroundColor(Color.blue);
            }

            if(Difference<=10){
                comment2.setText("Warm");
                setBackgroundColor(Color.red);
            }

            else {
            }
        }
        private void setBackgroundColor(Color color) {
               setBackgroundColor(color);
            }
    }


    public static void main(String args[]) {
        //instantiate gueesgame object
        GuessGame app = new GuessGame();

    }
}

3 个答案:

答案 0 :(得分:6)

颜色不会改变,因为你的setBackgroundColor总是使用Color.black。将其更改为:

private void setBackgroundColor(Color color) {
   setBackground(color);
}

数字始终为零。您不实例化randomNumber字段。将其添加到构造函数中:

randomNumber = new Random().nextInt(1001);

我注意到的另一个问题是你添加了一个窗口监听器,以确保在关闭窗口时程序退出。这是在JFrame中实现的。在构造函数中添加:

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

而不是使用弃用的方法:

mainFrame.show();

使用not deprecated:

mainFrame.setVisible(true);

此外,您有一个永远不会被查询的字段:

private Color background;

最好在将它连接到gui之前进行逻辑处理。测试和发现最严重的错误要容易得多。

重构代码:

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

  public class GuessGame extends JFrame {
     private JTextField userInput;
     private JLabel comment = new JLabel("What is your destiny?");
     private JLabel comment2 = new JLabel(" ");

     private int randomNumber;

     public GuessGame() {
        super("Guessing Game!");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Creates components
        JButton guessButton = new JButton("Guess");
        JButton quitButton = new JButton("Quit");
        JLabel prompt1 = new JLabel("I have a number between 1 and 1000.");
        JLabel prompt2 = new JLabel("Can you guess my number? Enter your Guess:");

        comment = new JLabel("What is your destiny?");
        comment2 = new JLabel(" ");
        userInput = new JTextField(5);

        //content pane
        Container c = getContentPane();
        setLayout(new FlowLayout());

        //adding component to the pane
        c.add(prompt1);
        c.add(prompt2);
        c.add(userInput);
        c.add(comment2);
        c.add(guessButton);
        c.add(quitButton);
        c.add(comment);

        guessButton.setMnemonic('G');
        quitButton.setMnemonic('Q');

        setSize(300, 200);
        setLocationRelativeTo(null);
        setVisible(true);
        setResizable(false);

        initializeNumber();

        //creating the handler
        GuessButtonHandler ghandler = new GuessButtonHandler(); //instantiate new object
        guessButton.addActionListener(ghandler); // add event listener

        QuitButtonHandler qhandler = new QuitButtonHandler();
        quitButton.addActionListener(qhandler);
     }

     private void initializeNumber() {
        randomNumber = new Random().nextInt(1000) + 1;
     }

     class QuitButtonHandler implements ActionListener {
        public void actionPerformed(ActionEvent e) {
           System.exit(0);
        }
     }

     class GuessButtonHandler implements ActionListener {
        public void actionPerformed(ActionEvent e) {
           int getUserInput;
           int diff;
           int Difference;
           try {
              getUserInput = Integer.parseInt(userInput.getText().trim());
              if (getUserInput == randomNumber) {
                 JOptionPane.showMessageDialog(null, "CONGRATULATIONS! You got it!!",
                         "Random Number: " + randomNumber,
                         JOptionPane.INFORMATION_MESSAGE);
                 initializeNumber();
                 return;
              }
              if (getUserInput > randomNumber) {
                 comment.setText("Too High. Try a lower number.");
                 diff = getUserInput - randomNumber;
                 Difference = Math.abs(diff);
              } else {
                 comment.setText("Too Low. Try a higher number.");
                 diff = randomNumber - getUserInput;
                 Difference = Math.abs(diff);
              }

              if (Difference <= 25) {
                 comment2.setText("Cold");
                 GuessGame.this.setBackgroundColor(Color.blue);
              }

              if (Difference <= 10) {
                 comment2.setText("Warm");
                 GuessGame.this.setBackgroundColor(Color.red);
              }
           } catch (NumberFormatException ex) {
              comment.setText("Enter a VALID number!");
           }
        }


     }

     private void setBackgroundColor(Color color) {
        getContentPane().setBackground(color);
     }

     public static void main(String args[]) {
        //instantiate gueesgame object
        GuessGame app = new GuessGame();

     }
  }

答案 1 :(得分:1)

你有比你需要的更多Swing组件,你似乎在操作另一组时向帧添加一组。例如,您有两个JTextFieldfieldBoxuserInput。您将userInput添加到框架中,但在Guess按钮处理程序中选中fieldBox以获取输入。由于fieldBox始终为空,因此NumberFormatException会被您的异常处理程序捕获(它应该只捕获NumberFormatException,而不是Exception),并更新comment使用“输入有效数字!”。但是,就像使用双重文字区域一样,comment实际上并未添加到框架prompt1prompt2,因此您无法看到更改

答案 2 :(得分:1)

我会在没有UI的情况下编写你的逻辑并测试它直到100%正确。首先使用命令行,文本UI。完成后,在其前面放置一个GUI。这有助于隔离你的问题:一旦文本驱动逻辑正确,你就会知道未来的问题是由于UI造成的。

它也使你的MVC分离更清洁。