Java 构建一个计算表达式游戏

Java 构建一个计算表达式游戏

任务是构建一个应用程序,该程序显示一个表达式并提示用户输入答案。一旦你输入解决方法,就会显示一个新的表达式,并且这些表达式会不断变化。一段时间后,对于相应应用程序给出的解决方案进行评估,并显示准确答案的总数。

游戏中的方法(用户自定义)

本节将介绍实现“计算表达式游戏”所涉及的方法(和构造函数)及其作用。

CalculateExpressionGame()

这是calculateExpressionGame类的构造函数。它通过创建和配置Swing组件,如JLabel、JTextField、JButton和用于显示表达式和结果的JLabel,设置游戏窗口。它还为提交按钮设置动作监听器。

public CalculateExpressionGame() {
   super("Calculate Expression Game");
   setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   setLayout(new FlowLayout());

   // Create and configure the Swing components
   expressionLabel = new JLabel();
   expressionLabel.setFont(new Font("Arial", Font.BOLD, 18));
   add(expressionLabel);

   answerTextField = new JTextField(10);
   add(answerTextField);

   submitButton = new JButton("Submit");
   add(submitButton);

   resultLabel = new JLabel();
   resultLabel.setFont(new Font("Arial", Font.BOLD, 18));
   add(resultLabel);

   // Add an ActionListener to the Submit button
   submitButton.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent e) {
         checkAnswer();
      }
   });

   pack();
   setLocationRelativeTo(null);
   setVisible(true);
}

startGame(int timeLimit) 此方法通过初始化游戏变量,例如totalTime,numQuestions和numCorrect来启动游戏。它调用generateQuestion()方法来显示第一个算术表达式。它还创建并启动一个计时器来跟踪剩余时间。如果时间到了,将调用endGame()方法。

public void startGame(int timeLimit) {
   totalTime = timeLimit;
   numQuestions = 0;
   numCorrect = 0;
   generateQuestion();

   // Create and start a Timer to track the remaining time
   timer = new Timer(1000, new ActionListener() {
   @Override
   public void actionPerformed(ActionEvent e) {
      totalTime--;
      if (totalTime >= 0) {
         setTitle("Calculate Expression Game - Time: " + totalTime);
      } else {
         endGame();
      }
   }
   });
   timer.start();
}

generateQuestion() 这个方法通过生成随机数字和运算符来生成一个随机的算术表达式。它更新expressionLabel以显示生成的表达式,并清除answerTextField供用户输入。它还增加numQuestions计数器。

private void generateQuestion() {
   // Generate random numbers and operator for the expression
   int num1 = (int) (Math.random() * 10) + 1;
   int num2 = (int) (Math.random() * 10) + 1;
   int operatorIndex = (int) (Math.random() * 3);
   String operator = "";
   int result = 0;

   // Determine the operator based on the randomly generated index
   switch (operatorIndex) {
      case 0:
         operator = "+";
         result = num1 + num2;
         break;
      case 1:
         operator = "-";
         result = num1 - num2;
         break;
      case 2:
         operator = "*";
         result = num1 * num2;
         break;
}

checkAnswer() 用户点击提交按钮时调用此方法。它通过解析answerTextField中的整数值来检查用户的答案。然后,它通过调用evaluateExpression()方法来计算expressionLabel中显示的表达式的值。如果用户的答案与计算结果匹配,则会增加numCorrect计数器。之后,它调用generateQuestion()方法生成一个新的问题。

private void checkAnswer() {
   try {
      // Parse the user's answer from the text field
      int userAnswer = Integer.parseInt(answerTextField.getText());
      int result = evaluateExpression(expressionLabel.getText());

      // Check if the user's answer is correct and update the count
      if (userAnswer == result) {
         numCorrect++;
      }
   } catch (NumberFormatException e) {
      // Invalid answer format
   }
   // Generate a new question
   generateQuestion();
}

evaluateExpression(String expression) 此方法将算术表达式作为字符串参数,并对其进行评估以获得结果。它使用空格作为分隔符将表达式分成其组件(num1、operator、num2)。它将num1和num2转换为整数,并应用运算符执行算术运算。返回结果值。

private int evaluateExpression(String expression) {
   // Split the expression into parts: num1, operator, num2
   String[] parts = expression.split(" ");
   int num1 = Integer.parseInt(parts[0]);
   String operator = parts[1];
   int num2 = Integer.parseInt(parts[2]);

   int result = 0;
   // Evaluate the expression based on the operator
   switch (operator) {
      case "+":
         result = num1 + num2;
         break;
      case "-":
         result = num1 - num2;
         break;
      case "*":
         result = num1 * num2;
         break;
   }
   return result;
}

endGame() 当时间限制达到时调用此方法。它停止计时器并禁用提交按钮。它通过将 numCorrect 除以 numQuestions 并乘以 100 来计算准确度。最终结果将在 resultLabel 中显示,包括有关总问题数、正确答案数和准确率百分比的信息。

private void endGame() {
   // Stop the timer and disable the submit button
   timer.stop();
   setTitle("Calculate Expression Game - Time's up!");
   submitButton.setEnabled(false);

   // Calculate the accuracy and display the final results
   double accuracy = (double) numCorrect / numQuestions * 100;
   resultLabel.setText("Game Over! Total Questions: " + numQuestions + " | Correct Answers: " + numCorrect + " | Accuracy: " + accuracy + "%");
}

main(String[] args) 这是程序的入口点。它创建一个CalculateExpressionGame类的实例,设置游戏的时间限制(以秒为单位),并通过调用startGame()来启动游戏。游戏在事件分派线程(EDT)上执行,以确保正确的Swing UI处理。

public static void main(String[] args) {
   SwingUtilities.invokeLater(new Runnable() {
      @Override
      public void run() {
         CalculateExpressionGame game = new CalculateExpressionGame();
         game.startGame(60); // 60 seconds time limit
      }
   });
}

完整示例

以下是这个游戏的完整实现:

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

public class CalculateExpressionGame extends JFrame {
    private JLabel expressionLabel;
    private JTextField answerTextField;
    private JButton submitButton;
    private JLabel resultLabel;
    private Timer timer;
    private int totalTime;
    private int numQuestions;
    private int numCorrect;

    public CalculateExpressionGame() {
        super("Calculate Expression Game");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new FlowLayout());

        // Create and configure the Swing components
        expressionLabel = new JLabel();
        expressionLabel.setFont(new Font("Arial", Font.BOLD, 18));
        add(expressionLabel);

        answerTextField = new JTextField(10);
        add(answerTextField);
        submitButton = new JButton("Submit");
        add(submitButton);
        resultLabel = new JLabel();
        resultLabel.setFont(new Font("Arial", Font.BOLD, 18));
        add(resultLabel);

        // Add an ActionListener to the Submit button
        submitButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                checkAnswer();
            }
        });

        pack();
        setLocationRelativeTo(null);
        setVisible(true);
    }

    public void startGame(int timeLimit) {
        totalTime = timeLimit;
        numQuestions = 0;
        numCorrect = 0;

        generateQuestion();

        // Create and start a Timer to track the remaining time
        timer = new Timer(1000, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                totalTime--;
                if (totalTime >= 0) {
                    setTitle("Calculate Expression Game - Time: " + totalTime);
                } else {
                    endGame();
                }
            }
        });
        timer.start();
    }

    private void generateQuestion() {
        // Generate random numbers and operator for the expression
        int num1 = (int) (Math.random() * 10) + 1;
        int num2 = (int) (Math.random() * 10) + 1;
        int operatorIndex = (int) (Math.random() * 3);
        String operator = "";
        int result = 0;

        // Determine the operator based on the randomly generated index
        switch (operatorIndex) {
            case 0:
                operator = "+";
                result = num1 + num2;
                break;
            case 1:
                operator = "-";
                result = num1 - num2;
                break;
            case 2:
                operator = "*";
                result = num1 * num2;
                break;
        }

        // Update the expression label and clear the answer text field
        expressionLabel.setText(num1 + " " + operator + " " + num2 + " = ");
        answerTextField.setText("");
        answerTextField.requestFocus();

        numQuestions++;
    }

    private void checkAnswer() {
        try {
            // Parse the user's answer from the text field
            int userAnswer = Integer.parseInt(answerTextField.getText());
            int result = evaluateExpression(expressionLabel.getText());

            // Check if the user's answer is correct and update the count
            if (userAnswer == result) {
                numCorrect++;
            }
        } catch (NumberFormatException e) {
            // Invalid answer format
        }

        // Generate a new question
        generateQuestion();
    }

    private int evaluateExpression(String expression) {
        // Split the expression into parts: num1, operator, num2
        String[] parts = expression.split(" ");
        int num1 = Integer.parseInt(parts[0]);
        String operator = parts[1];
        int num2 = Integer.parseInt(parts[2]);

        int result = 0;
        // Evaluate the expression based on the operator
        switch (operator) {
            case "+":
                result = num1 + num2;
                break;
            case "-":
                result = num1 - num2;
                break;
            case "*":
                result = num1 * num2;
                break;
        }

        return result;
    }

    private void endGame() {
        // Stop the timer and disable the submit button
        timer.stop();
        setTitle("Calculate Expression Game - Time's up!");
        submitButton.setEnabled(false);

        // Calculate the accuracy and display the final results
        double accuracy = (double) numCorrect / numQuestions * 100;
        resultLabel.setText("Game Over! Total Questions: " + numQuestions + " | Correct Answers: " + numCorrect
                + " | Accuracy: " + accuracy + "%");
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                CalculateExpressionGame game = new CalculateExpressionGame();
                game.startGame(60); // 60 seconds time limit
            }
        });
    }
}

输出

Java 构建一个计算表达式游戏

该程序从Java Swing元素构建一个简单的游戏窗口。它创建任意的数学公式(+,-和*),并提示用户在指定的时间内(这里是60秒)提供正确的回答。

用户可以提交他们的答案,游戏会记录算术问题的数量,正确回答的数量和准确率。游戏会在指定的时间过后显示结果。

为了测试这段代码的功能性,可以在类似Eclipse或IntelliJ IDEA的Java开发环境中运行它。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程