Skip to content
Related Articles

Related Articles

Build a Calculate Expression Game in Java

Improve Article
Save Article
  • Difficulty Level : Basic
  • Last Updated : 03 Jan, 2022
Improve Article
Save Article

Java is a class-based, object-oriented programming language and is designed to have as few implementation dependencies as possible. A general-purpose programming language made for developers to write once run anywhere that is compiled Java code can run on all platforms that support Java. Java applications are compiled to byte code that can run on any Java Virtual Machine. The syntax of Java is similar to c/c++. 

What we are going to build in this article? 

What is 2+3 ? Yupp, 5 is Correct!! What about 5*8? 40, right !! Did it take time to calculate it ?! Let’s find out how many such simple questions can you and your friends do in just 60 seconds. The game will allow us to find out how many questions we will be able to correctly do in just 60 seconds !! For this, we will be creating a SIMPLE and Interactive Time Based “Calculate Expression Game” in java using the Java swing components. A sample video is given below to get an idea about what we are going to do in this article.

So the learning outcomes will be:

  1. Creating Interactive GUI for our Game
  2. Integration of Two JFrame
  3. Creation of Workable Timer
  4. Developing a Style to manage Components

The project will contain 3 java classes: 

  1. Main.java
  2. Home.java
  3. Play.java

We will design two pages or JFrames as we call it. 1st JFrame will give the option to PLAY or EXIT from the game. In case the user chooses to play, the 2nd JFrame will contain the game in which the player has to answer maximum mathematical expression-based questions in 60 seconds.

Step by Step Implementation

Step 1. We will start by first importing all the classes which we will require for this Game.  We will learn how they will be useful as we proceed further in this project. 

Java




// File name is Main.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.*;
import java.util.Random;


Step 2. We will define a class Main which will call the class Home Constructor.

Java




// File name is Main.java
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.*;
import java.util.Random;
import javax.swing.*;
  
public class Main {
    public static void main(String[] arg)
    {
        // to call the constructor of class Home
        Home frame = new Home();
        // Sets the title for this frame "HOME"
        frame.setTitle("HOME");
        // Component will be displayed on the screen
        frame.setVisible(true);
        // position and size of the frame
        // using setBounds(x,y,width,height)
        frame.setBounds(10, 10, 370, 600);
        // application exits on close window
        // event from the operating system
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        // user cannot re-size the frame
        frame.setResizable(false);
    }
}


Step 3. We will now define our class Home and prepare a style for it so that tracking the components does not make our head go haywire. Also, time to make some concepts clear !! We will inherit the JFrame class which is a swing component (part of javax.swing package). In order to define what should be done when a user performs certain operations, we will implement the ActionListener interface.  ActionListener (found in java.awt.event package) has only one method actionPerformed(ActionEvent) which is called when the user performs some action.

Java




// File name is Main.java
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.*;
import java.util.Random;
import javax.swing.*;
  
class Home extends JFrame implements ActionListener {
    Home()
    {
        setLayoutManager();
        setLocationAndSize();
        addComponentsToContainer();
        addActionEvent();
    }
    public void setLayoutManager() {}
    public void setLocationAndSize() {}
    public void addComponentsToContainer() {}
    public void addActionEvent() {}
    @Override public void actionPerformed(ActionEvent e) {}
}
  
public class Main {
    public static void main(String[] arg)
    {
        // to call the constructor of class Home
        Home frame = new Home();
        // Sets the title for this frame "HOME"
        frame.setTitle("HOME");
        // Component will be displayed on the screen
        frame.setVisible(true);
        // position and size of the frame
        // using setBounds(x,y,width,height)
        frame.setBounds(10, 10, 370, 600);
        // application exits on close window
        // event from the operating system
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        // user cannot re-size the frame
        frame.setResizable(false);
    }
}


Step 4. We will define the components and add them to the Home frame. 

Java




// File name is Main.java
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.*;
import java.util.Random;
import javax.swing.*;
  
class Home extends JFrame implements ActionListener {
  
    Container container = getContentPane();
    JLabel home = new JLabel("HOME", JLabel.CENTER);
    JButton playbutton = new JButton("PLAY");
    JButton exitbutton = new JButton("EXIT");
  
    Home()
    {
        setLayoutManager();
        setLocationAndSize();
        addComponentsToContainer();
        addActionEvent();
    }
    public void setLayoutManager()
    {
        // Content panes use
        // BorderLayout by default
        container.setLayout(null);
    }
    public void setLocationAndSize()
    {
        // position and size of the components
        // using setBounds(x,y,width,height)
        home.setBounds(125, 20, 125, 30);
        // to display content or BackGround
        // behind a given component
        home.setOpaque(true);
        home.setBackground(Color.BLACK);
        home.setForeground(Color.WHITE);
        playbutton.setBounds(75, 200, 225, 30);
        exitbutton.setBounds(75, 250, 225, 30);
    }
    public void addComponentsToContainer()
    {
        container.add(home);
        container.add(playbutton);
        container.add(exitbutton);
    }
    public void addActionEvent()
    {
        // listen for changes on the object
        playbutton.addActionListener(this);
        exitbutton.addActionListener(this);
    }
    @Override public void actionPerformed(ActionEvent e) {}
}
  
public class Main {
    public static void main(String[] arg)
    {
        // to call the constructor of class Home
        Home frame = new Home();
        // Sets the title for this frame "HOME"
        frame.setTitle("HOME");
        // Component will be displayed on the screen
        frame.setVisible(true);
        // position and size of the frame
        // using setBounds(x,y,width,height)
        frame.setBounds(10, 10, 370, 600);
        // application exits on close window
        // event from the operating system
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        // user cannot re-size the frame
        frame.setResizable(false);
    }
}


Step 5. Time for adding functionalities to the buttons.

Java




// File name is Main.java
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.*;
import java.util.Random;
import javax.swing.*;
  
class Home extends JFrame implements ActionListener {
  
    Container container = getContentPane();
    JLabel home = new JLabel("HOME", JLabel.CENTER);
    JButton playbutton = new JButton("PLAY");
    JButton exitbutton = new JButton("EXIT");
  
    Home()
    {
        setLayoutManager();
        setLocationAndSize();
        addComponentsToContainer();
        addActionEvent();
    }
    public void setLayoutManager()
    {
        // Content panes use BorderLayout by default
        container.setLayout(null);
    }
    public void setLocationAndSize()
    {
        // position and size of the components
        // using setBounds(x,y,width,height)
        home.setBounds(125, 20, 125, 30);
        // to display content or BackGround
        // behind a given component
        home.setOpaque(true);
        home.setBackground(Color.BLACK);
        home.setForeground(Color.WHITE);
        playbutton.setBounds(75, 200, 225, 30);
        exitbutton.setBounds(75, 250, 225, 30);
    }
    public void addComponentsToContainer()
    {
        container.add(home);
        container.add(playbutton);
        container.add(exitbutton);
    }
    public void addActionEvent()
    {
        // listen for changes on the object
        playbutton.addActionListener(this);
        exitbutton.addActionListener(this);
    }
    @Override public void actionPerformed(ActionEvent e)
    {
        if (e.getSource() == playbutton) {
            // dispose() method clear
            // resources at each frame
            dispose();
            // to call the constructor of class Play
            Play frame = new Play();
            // Sets the title for this frame "PLAY"
            frame.setTitle("PLAY");
            // Component will be displayed on the screen
            frame.setVisible(true);
            // position and size of the frame using
            // setBounds(x,y,width,height)
            frame.setBounds(10, 10, 370, 600);
            // application exits on close window
            // event from the operating system
            frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            // user cannot re-size the frame
            frame.setResizable(false);
        }
        if (e.getSource() == exitbutton) {
            // asks for confirmation from the user to exit
            // or not
            int option = JOptionPane.showConfirmDialog(
                this, "Do You Really Want To Quit",
                "Thank you", JOptionPane.YES_NO_OPTION,
                JOptionPane.PLAIN_MESSAGE);
            if (option == JOptionPane.YES_OPTION) {
                dispose();
            }
        }
    }
}
  
public class Main {
    public static void main(String[] arg)
    {
        // to call the constructor of class Home
        Home frame = new Home();
        // Sets the title for this frame "HOME"
        frame.setTitle("HOME");
        // Component will be displayed on the screen
        frame.setVisible(true);
        // position and size of the frame
        // using setBounds(x,y,width,height)
        frame.setBounds(10, 10, 370, 600);
        // application exits on close window
        // event from the operating system
        frame.setDefaultCloseOperation(
            JFrame.DISPOSE_ON_CLOSE);
        // user cannot re-size the frame
        frame.setResizable(false);
    }
}


Step 6. Let us look into two utility functions that will be used for our project. Calculate function to generate mathematical expression. Here we are generating two random numbers using the imported class import java.util.Random in the given range.

Java




int Calculate(){
        int num1 = new Random().nextInt(11); // 0 to 10
        int num2 = new Random().nextInt(11) + 1; // 1 to 11
  
        String operator = "+-/*%";
        int random_operator = new Random().nextInt(5);
  
        questiontext.setText("(" + num1 + ") " + operator.charAt(random_operator) + " (" + num2 + ")");
  
        return switch (operator.charAt(random_operator)) {
            case ('+') -> num1 + num2;
            case ('-') -> num1 - num2;
            case ('*') -> num1 * num2;
            case ('/') -> num1 / num2;
            case ('%') -> num1 % num2;
            default -> 0;
        };
    }


Score function to display the updated score of the player.

Java




void Score(){
   score += 1;
   presentscoretext.setText(" " +score + " ");
}


Step 7. Now we will define the skeleton of the class Play. 

Here we are requesting the focus of our JFrame object on the text field using WindowActionListener. Also, we are creating a TIMER of 60 seconds so that no input will be accepted just after a delay of 60 seconds and also this will ensure that not more than 60 inputs are taken (In case a user keeps pressing the same input many times). In practice, the timer is running after a delay of 1000 milliseconds waiting for user input and that is why we are surrounding the ActionEvent to try-catch blocks in cases when the user does not provide input for that particular second.

Java




// File name is Main.java
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.*;
import java.util.Random;
import javax.swing.*;
  
class Game extends JFrame implements ActionListener {
  
    Container container = getContentPane();
  
    JLabel questionlabel = new JLabel("QUESTION : ");
    JTextField questiontext = new JTextField();
    JLabel answerlabel = new JLabel("ANSWER : ");
    JTextField answertext = new JTextField();
    JLabel presentscorelabel
        = new JLabel("PRESENT SCORE : ");
    JTextField presentscoretext = new JTextField();
  
    int result = 0;
    int score = -1;
    Timer gametimer;
    // GAME TIMER in seconds
    int start = 60;
  
    Game()
    {
        setLayoutManager();
        setLocationAndSize();
        addComponentsToContainer();
        addActionEvent();
        result = Calculate();
        Score();
        setTimer();
    }
    public void setLayoutManager()
    {
        container.setLayout(null);
    }
    public void setLocationAndSize()
    {
        questionlabel.setBounds(100, 100, 150, 30);
        questiontext.setBounds(100, 140, 150, 30);
        answerlabel.setBounds(100, 200, 150, 30);
        answertext.setBounds(100, 240, 150, 30);
        presentscorelabel.setBounds(100, 290, 150, 30);
        presentscoretext.setBounds(100, 330, 150, 30);
    }
    public void addComponentsToContainer()
    {
        container.add(questionlabel);
        container.add(questiontext);
        container.add(answerlabel);
        container.add(answertext);
        container.add(presentscorelabel);
        container.add(presentscoretext);
    }
    public void addActionEvent()
    {
        questiontext.setEditable(false);
        presentscoretext.setEditable(false);
        answertext.addActionListener(this);
        this.addWindowListener(new WindowAdapter() {
            @Override
            public void windowOpened(WindowEvent evt)
            {
                super.windowOpened(evt);
                answertext.requestFocus();
            }
        });
    }
    public void setTimer()
    {
        gametimer = new Timer(1000, this);
        gametimer.start();
    }
    @Override public void actionPerformed(ActionEvent e1) {}
}
  
class Home extends JFrame implements ActionListener {
  
    Container container = getContentPane();
    JLabel home = new JLabel("HOME", JLabel.CENTER);
    JButton playbutton = new JButton("PLAY");
    JButton exitbutton = new JButton("EXIT");
  
    Home()
    {
        setLayoutManager();
        setLocationAndSize();
        addComponentsToContainer();
        addActionEvent();
    }
    public void setLayoutManager()
    {
        // Content panes use
        // BorderLayout by default
        container.setLayout(null);
    }
    public void setLocationAndSize()
    {
        // position and size of the components
        // using setBounds(x,y,width,height)
        home.setBounds(125, 20, 125, 30);
        // to display content or BackGround
        // behind a given component
        home.setOpaque(true);
        home.setBackground(Color.BLACK);
        home.setForeground(Color.WHITE);
        playbutton.setBounds(75, 200, 225, 30);
        exitbutton.setBounds(75, 250, 225, 30);
    }
    public void addComponentsToContainer()
    {
        container.add(home);
        container.add(playbutton);
        container.add(exitbutton);
    }
    public void addActionEvent()
    {
        // listen for changes on the object
        playbutton.addActionListener(this);
        exitbutton.addActionListener(this);
    }
    @Override public void actionPerformed(ActionEvent e)
    {
        if (e.getSource() == playbutton) {
            // dispose() method clear resources at each
            // frame
            dispose();
            // to call the constructor of class Play
            Game frame = new Game();
            // Sets the title for this frame "PLAY"
            frame.setTitle("PLAY");
            // Component will be displayed on the screen
            frame.setVisible(true);
            // position and size of the frame
            // using setBounds(x,y,width,height)
            frame.setBounds(10, 10, 370, 600);
            // application exits on close window
            // event from the operating system
            frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            // user cannot re-size the frame
            frame.setResizable(false);
        }
        if (e.getSource() == exitbutton) {
            // asks for confirmation from the user to exit
            // or not
            int option = JOptionPane.showConfirmDialog(
                this, "Do You Really Want To Quit",
                "Thank you", JOptionPane.YES_NO_OPTION,
                JOptionPane.PLAIN_MESSAGE);
            if (option == JOptionPane.YES_OPTION) {
                dispose();
            }
        }
    }
}
  
public class Main {
    public static void main(String[] arg)
    {
        // to call the constructor of class Home
        Home frame = new Home();
        // Sets the title for this frame "HOME"
        frame.setTitle("HOME");
        // Component will be displayed on the screen
        frame.setVisible(true);
        // position and size of the frame
        // using setBounds(x,y,width,height)
        frame.setBounds(10, 10, 370, 600);
        // application exits on close window
        // event from the operating system
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        // user cannot re-size the frame
        frame.setResizable(false);
    }
}


Step 8. We are now at the last stage where we add the utilities to our source code and also add two messages so that the user is able to view the score as 60 seconds are elapsed as well as ask the user for playing again. Below is the Working Source Code for this Game.

Java




// File name is Main.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Random;
  
class Game extends JFrame implements ActionListener{
    
    Container container = getContentPane();
  
    JLabel questionlabel = new JLabel("QUESTION : ");
    JTextField questiontext = new JTextField();
    JLabel answerlabel = new JLabel("ANSWER : ");
    JTextField answertext = new JTextField();
    JLabel presentscorelabel = new JLabel("PRESENT SCORE : ");
    JTextField presentscoretext = new JTextField();
  
    int result = 0;
    int score = -1;
    Timer gametimer;
    // GAME TIMER in seconds
    int start = 60
  
    Game(){
        setLayoutManager();
        setLocationAndSize();
        addComponentsToContainer();
        addActionEvent();
        result = Calculate();
        Score();
        setTimer();
    }
    public void setLayoutManager() {
        container.setLayout(null);
    }
    public void setLocationAndSize() {
        questionlabel.setBounds(100, 100, 150, 30);
        questiontext.setBounds(100, 140, 150, 30);
        answerlabel.setBounds(100, 200, 150, 30);
        answertext.setBounds(100, 240, 150, 30);
        presentscorelabel.setBounds(100, 290, 150, 30);
        presentscoretext.setBounds(100, 330, 150, 30);
    }
    public void addComponentsToContainer() {
        container.add(questionlabel);
        container.add(questiontext);
        container.add(answerlabel);
        container.add( answertext);
        container.add(presentscorelabel);
        container.add( presentscoretext);
    }
    public void addActionEvent() {
        questiontext.setEditable(false);
        presentscoretext.setEditable(false);
        answertext.addActionListener(this);
        this.addWindowListener(new WindowAdapter() {
            @Override
            public void windowOpened(WindowEvent evt) {
                super.windowOpened(evt);
                answertext.requestFocus();
            }
        });
    }
    public void setTimer(){
        gametimer = new Timer(1000,this);
        gametimer.start();
    }
    @Override
    public void actionPerformed(ActionEvent e1) {
        start -= 1;
        if(start >= 0){
            try{
                String s = e1.getActionCommand();
                if(result == Integer.parseInt(s)){
                    Score();
                }
                result = Calculate();
                answertext.setText(null);
            }
            catch(Exception e3){
  
            }
        }else{
            gametimer.stop();
            JOptionPane.showMessageDialog(this,"TIME IS UP. YOUR SCORE IS : " + score ,"SCORE",JOptionPane.PLAIN_MESSAGE);
            int option = JOptionPane.showConfirmDialog(this,"DO YOU  WANT TO PLAY AGAIN ?","PLAY AGAIN SCORE : " + score,JOptionPane.YES_NO_OPTION,JOptionPane.INFORMATION_MESSAGE);
            if(option == JOptionPane.YES_OPTION){
                dispose();
                Game frame = new Game();
                frame.setTitle("PLAY");
                frame.setVisible(true);
                frame.setBounds(10,10,370,600);
                frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                frame.setResizable(false);
            }
            else{
                dispose();
                Home frame = new Home();
                frame.setTitle("HOME");
                frame.setVisible(true);
                frame.setBounds(10,10,370,600);
                frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                frame.setResizable(false);
            }
        }
    }
  
    int Calculate(){
        int num1 = new Random().nextInt(11); // 1 to 10
        int num2 = new Random().nextInt(11) + 1; // 0 to 10
  
        String operator = "+-/*%";
        int random_operator = new Random().nextInt(5);
  
        questiontext.setText("(" + num1 + ") " + operator.charAt(random_operator) + " (" + num2 + ")");
  
        return switch (operator.charAt(random_operator)) {
            case ('+') -> num1 + num2;
            case ('-') -> num1 - num2;
            case ('*') -> num1 * num2;
            case ('/') -> num1 / num2;
            case ('%') -> num1 % num2;
            default -> 0;
        };
    }
  
    void Score(){
        score += 1;
        presentscoretext.setText(" " +score + " ");
    }
}
  
class Home extends JFrame implements ActionListener{
  
    Container container = getContentPane();
    JLabel home = new JLabel("HOME",JLabel.CENTER);
    JButton playbutton = new JButton("PLAY");
    JButton exitbutton = new JButton("EXIT");
  
    Home(){
        setLayoutManager();
        setLocationAndSize();
        addComponentsToContainer();
        addActionEvent();
    }
    public void setLayoutManager(){
        // Content panes use 
        // BorderLayout by default
        container.setLayout(null);
    }
    public void setLocationAndSize(){
        // position and size of the components
        // using setBounds(x,y,width,height)
        home.setBounds(125,20,125,30);
        // to display content or BackGround 
        // behind a given component
        home.setOpaque(true);
        home.setBackground(Color.BLACK);
        home.setForeground(Color.WHITE);
        playbutton.setBounds(75,200,225,30);
        exitbutton.setBounds(75,250,225,30);
    }
    public void addComponentsToContainer(){
        container.add(home);
        container.add(playbutton);
        container.add(exitbutton);
    }
    public void addActionEvent(){
        // listen for changes on the object
        playbutton.addActionListener(this);
        exitbutton.addActionListener(this);
    }
    @Override
    public void actionPerformed(ActionEvent e){
        if(e.getSource() == playbutton){
            // dispose() method clear
              // resources at each frame
            dispose();
            // to call the constructor of class Play
            Game frame = new Game();
            // Sets the title for this frame "PLAY"
            frame.setTitle("PLAY");
            // Component will be displayed on the screen
            frame.setVisible(true);
            // position and size of the frame 
            // using setBounds(x,y,width,height)
            frame.setBounds(10,10,370,600);
            // application exits on close window 
            // event from the operating system
            frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            // user cannot re-size the frame
            frame.setResizable(false);
        }
        if(e.getSource() == exitbutton){
            // asks for confirmation from the user to exit or not
            int option = JOptionPane.showConfirmDialog(this,"Do You Really Want To Quit","Thank you", JOptionPane.YES_NO_OPTION,JOptionPane.PLAIN_MESSAGE);
            if(option == JOptionPane.YES_OPTION){
                dispose();
            }
        }
    }
}
  
public class MAN {
    public static void main(String[] arg){
        // to call the constructor of class Home
        Home frame = new Home();
        // Sets the title for this frame "HOME"
        frame.setTitle("HOME");
        // Component will be displayed on the screen
        frame.setVisible(true);
        // position and size of the frame 
        // using setBounds(x,y,width,height)
        frame.setBounds(10,10,370,600);
        // application exits on close window 
        // event from the operating system
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        // user cannot re-size the frame
        frame.setResizable(false);
    }
}


Output:


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!