简体   繁体   English

Java猜谜游戏

[英]Java guessing game

I am trying to write a program in Java that takes a random number from 1-1000 and then as the guess it the background color changes to blue(cold) or red(warm) if they are in the number. 我正在尝试用Java编写一个程序,该程序接受1-1000中的一个随机数,然后猜测它的背景颜色变为蓝色(冷)或红色(暖)。 I am new to java GUI, but I think the rest of the logic is right, not sure. 我是Java GUI的新手,但我认为其余逻辑是正确的,不确定。 It compiles, but the guess button doesn't work. 它可以编译,但是猜测按钮不起作用。 Any guidance will be appreciated. 任何指导将不胜感激。

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

    }
}

The colors aren't changing because your setBackgroundColor always uses Color.black. 颜色没有改变,因为您的setBackgroundColor始终使用Color.black。 Change it to: 更改为:

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

As for the number always being zero. 至于数字总是为零。 You do not instantiate the randomNumber field. 您不实例化randomNumber字段。 Add this to your constructor: 将此添加到您的构造函数:

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

Another problem I noticed was you added a window listener to ensure the program exits when you close the window. 我注意到的另一个问题是您添加了一个窗口侦听器,以确保关闭窗口时程序退出。 This is implemented in JFrame. 这是在JFrame中实现的。 In the constructor add: 在构造函数中添加:

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Instead of using the deprecated method: 而不使用不推荐使用的方法:

mainFrame.show();

use the not deprecated: 使用不被弃用的:

mainFrame.setVisible(true);

Furthermore you have a field, which is never queried: 此外,您还有一个从未查询过的字段:

private Color background;

It's best to do the logic before connecting it to the gui. 最好在将逻辑连接到gui之前进行逻辑处理。 It's a lot easier to test and find the worst bugs. 测试和发现最严重的错误要容易得多。

Refactored code: 重构代码:

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

     }
  }

You have more Swing components than you need, and you seem to be adding one set to the frame while manipulating another set. 您的Swing组件数量超过了您的需要,并且似乎在操纵框架时向框架添加了一组。 For example, you have two JTextField s, fieldBox and userInput . 例如,您有两个JTextFieldfieldBoxuserInput You add userInput to the frame, but check fieldBox for input in the Guess button handler. 您将userInput添加到框架,但是检查fieldBox以在Guess按钮处理程序中输入。 Since fieldBox is always empty, the NumberFormatException is caught by your exception handler (which should really just catch NumberFormatException , not Exception ), and comment is updated with "Enter a VALID number!". 由于fieldBox永远是空的, NumberFormatException被异常处理程序(这真的应该正好赶上抓住了NumberFormatException ,没有Exception ),并且comment与“输入有效的数字!”更新。 However, just like with the double text area, comment isn't actually added to the frame, prompt1 and prompt2 are, so you can't see the change 但是,就像在双文本区域中一样, comment实际上并没有添加到框架中, prompt1prompt2确实添加了,因此您看不到更改

I would write your logic without a UI first and test it until it was 100% correct. 我会先编写没有UI的逻辑,然后对其进行测试,直到100%正确为止。 Just use a command line, text UI at first. 首先只使用命令行,文本UI。 Once that's done, put a GUI in front of it. 完成后,在其前面放置一个GUI。 It'll help to isolate your problems: once the text-driven logic is right, you'll know that future problems are due to UI. 它可以帮助您隔离问题:一旦文本驱动的逻辑正确,您就会知道将来的问题归因于UI。

It makes your MVC separation cleaner as well. 它也使您的MVC分离器更清洁。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM