Build a Calculate Expression Game in Java


The task is to build an application which displays an expression and prompts for the answer. Once you enter the solution a new expression is displayed and these expressions keep on changing. After a certain amout of time the solution given for the respective application were evaluated and the total number of accurate answers were displayed.

Methods (User defined) in the Game

The section will walk you through the methods (and constructor) that are part of the implementation and their roles in the “Calculate Expression Game”.

CalculateExpressionGame()

This is the constructor of the calculateExpressionGame class. It sets up the game window by creating and configuring the Swing components such as JLabel, JTextField, JButton, and JLabel for displaying the expressions and results. It also sets the action listener for the submit button.

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) This method starts the game by initializing the game variables such as totalTime, numQuestions, and numCorrect. It calls the generateQuestion() method to display the first arithmetic expression. It also creates and starts a Timer to track the remaining time. If the time runs out, the endGame() method is called.

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() This method generates a random arithmetic expression by generating random numbers and an operator. It updates the expressionLabel to display the generated expression and clears the answerTextField for the user's input. It also increments the numQuestions counter.

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() This method is called when the user clicks the submit button. It checks the user's answer by parsing the integer value from the answerTextField. It then evaluates the expression displayed in the expressionLabel by calling the evaluateExpression() method. If the user's answer matches the evaluated result, it increments the numCorrect counter. Afterward, it calls generateQuestion() to generate a new question.

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) This method takes an arithmetic expression as a string parameter and evaluates it to obtain the result. It splits the expression into its components (num1, operator, num2) using space as the delimiter. It converts num1 and num2 to integers and applies the operator to perform the arithmetic operation. The resulting value is returned.

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() This method is called when the time limit is reached. It stops the timer and disables the submit button. It calculates the accuracy by dividing the numCorrect by numQuestions and multiplying by 100. The final result is displayed in the resultLabel with information about the total number of questions, the number of correct answers, and the accuracy percentage.

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) This is the entry point of the program. It creates an instance of the CalculateExpressionGame class, sets the time limit (in seconds) for the game, and starts the game by calling startGame(). The game is executed on the Event Dispatch Thread (EDT) to ensure proper Swing UI handling.

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

Complete Example

Following is a complete implementation of this game –

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

Output

This program builds a straightforward game window from Java Swing elements. It creates arbitrary mathematical formulas (+, -, and *) and prompts the user to provide the correct response within a set amount of time (in this case, 60 seconds).

The user can submit their response, and the game will record the number of arithmetic questions, the number of right responses, and the accuracy. The game will show the results after the allotted time has passed.

To test this code's functionality, run it in a Java development environment like Eclipse or IntelliJ IDEA.

Updated on: 12-Jul-2023

51 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements