1
\$\begingroup\$

Sorry for any confusion but I could only came up with the name Simplification. This game displays a simplification problem and the user has to solve it using BODMAS rule. The user will get 1 minute to solve each problem there are total 20 problems which are divided into 5 levels. I wanted to add graphics using LWJGL to make it more like a game. Will this be a good thing to do? Because LWJGL are heavyweight where as swings are lightweight thanks in advance!

package searchAlgo;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
import javax.swing.*;
import javax.swing.event.MenuEvent;
import javax.swing.event.MenuListener;

public class MyProject {
    JFrame frame;
  JLabel label, levelLabel;
  JPanel panelOne, panelTwo, panelThree, panelFour;
  JButton buttonEnter, buttonClear, buttonNew;
  JTextField textField, timerField1, timerField2;
  JMenu  menuAbout, menuTheme;
  JMenuBar menuBar;
  JRadioButton [] radioButtons;
  String [] radioName = {"Monuments", "Plants", "Animals", "Art", "Army"};
  Action enterAction;
  ButtonGroup buttonGroup;
  Timer timer;
  int score = 0, count = -1, levelNum = 0;
  Boolean flag = false;
  private JTextArea textArea;
  private Queue<String> queue = new LinkedList<> ();

  MyProject(){

      //text field for answer
      textField = new JTextField();

      //text area for question
      textArea = new JTextArea(6,20);
      textArea.setEditable(false);
      textArea.setWrapStyleWord(true);
      textArea.setOpaque(false);

      timer = new Timer(1000, new timerListener());

      // timer field for minutes
      timerField1 = new JTextField();
      timerField1.setText("1");
      timerField1.setOpaque(false);
      timerField1.setFont(new Font("Calibri", Font.BOLD, 30));
      timerField1.setEditable(false);

      //the timer label
      label = new JLabel();
      label.setText(":");
      label.setFont(new Font("Calibri", Font.BOLD, 30));

      //level label
      levelLabel = new JLabel("Level : ", SwingConstants.CENTER);
      levelLabel.setFont(new Font("Calibri", Font.BOLD, 20));


      // timer field for seconds
      timerField2 = new JTextField();
      timerField2.setText("00");
      timerField2.setOpaque(false);
      timerField2.setFont(new Font("Calibri", Font.BOLD, 30));
      timerField2.setEditable(false);

      // for future use
      buttonGroup = new ButtonGroup();

      radioButtons = new JRadioButton [5];
      for(int i = 0; i < radioButtons.length; i++){
          buttonGroup.add(radioButtons[i] = new JRadioButton(radioName[i]));
          radioButtons[i].addActionListener(new radioListener());
      }

      // menu bar and details
      menuBar = new JMenuBar();

      menuAbout = new JMenu("About");
      menuAbout.setMnemonic(KeyEvent.VK_A);
      menuBar.add(menuAbout);
      menuAbout.addMenuListener(new menuListener());

      menuTheme = new JMenu("Theme");
      menuBar.add(menuTheme);
      for(int i = 0; i < radioButtons.length; i++){
         menuTheme.add(radioButtons[i]); 
      }

      //JButtons start form here
      buttonEnter = new JButton("Enter");
      buttonEnter.addActionListener(new buttonListener());

      //Key Binding for Enter key
      enterAction = new EnterAction();

      textField.getInputMap().put(KeyStroke.getKeyStroke("ENTER"), "doEnterAction");
      textField.getActionMap().put("doEnterAction", enterAction);

      buttonClear = new JButton("Clear");
      buttonClear.addActionListener(new buttonListener());

      buttonNew = new JButton("New");
      buttonNew.addActionListener(new buttonListener());

      //panel one adding buttons
      panelOne = new JPanel();
      panelOne.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
      panelOne.add(buttonEnter);
      panelOne.add(buttonClear);
      panelOne.add(buttonNew);
      panelOne.setVisible(true);
      panelOne.setOpaque(false);

      //panel one in panel two
      panelTwo = new JPanel();
      panelTwo.setLayout(new BoxLayout(panelTwo, BoxLayout.LINE_AXIS));
      panelTwo.add(Box.createHorizontalStrut(30));
      panelTwo.add(panelOne);
      panelTwo.add(Box.createHorizontalStrut(30));
      panelTwo.setVisible(true);
      panelTwo.setOpaque(false);

      //panel three for timer field
      panelThree = new JPanel();
      panelThree.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
      panelThree.add(timerField1);
      panelThree.add(label);
      panelThree.add(timerField2);

      //panel four adding panel two, text area and text field
      panelFour = new JPanel();
      panelFour.setLayout(new BorderLayout());
      panelFour.add(panelTwo, BorderLayout.PAGE_START);
      panelFour.add(textArea, BorderLayout.CENTER);
      panelFour.add(textField, BorderLayout.PAGE_END);

      //frame and its settings
      frame = new JFrame("Simplification");
      frame.setSize(360, 360);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setResizable(true);
      frame.setLayout(new BorderLayout(30, 30));
      frame.setJMenuBar(menuBar);
      frame.add(levelLabel, BorderLayout.PAGE_START);
      frame.add(panelFour, BorderLayout.LINE_START);
      frame.add(panelThree, BorderLayout.LINE_END);
      //frame.add(textArea, BorderLayout.CENTER);
      //frame.add(panelThree, BorderLayout.LINE_END);
      //frame.add(textField, BorderLayout.PAGE_END);
      frame.setVisible(true);

  }
 class menuListener implements MenuListener{

    @Override
    public void menuCanceled(MenuEvent menuEventCanceled) {
        // TODO Auto-generated method stub
    }

    @Override
    public void menuDeselected(MenuEvent menuEventDeselect ) {
        // TODO Auto-generated method stub  
    }

    @Override
    public void menuSelected(MenuEvent menuEventSelect) {
        // TODO Auto-generated method stub
        if(menuEventSelect.getSource().equals(menuAbout)){
            JOptionPane.showMessageDialog(frame, "Use BODMAS rule to solve the questions :)");
        }

    }

 }


 class timerListener implements ActionListener{

     int remainSec = 60;

    @Override
    public void actionPerformed(ActionEvent e) {
        // TODO Auto-generated method stub
        if(flag == true){
            remainSec = 60;
            flag = false;
        }
        remainSec--;
        timerField1.setText("0");
        timerField2.setText(Integer.toString(remainSec));
        if(remainSec == 0){
            if(flag == false){
                timer.stop();
                buttonEnter.setEnabled(false);
                buttonClear.setEnabled(false);
                JOptionPane.showMessageDialog(frame, "Time Over");
            }
        }
    }

 }


  // key binding
 class EnterAction extends AbstractAction{

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    @Override
    public void actionPerformed(ActionEvent buttonEvent) {
        // TODO Auto-generated method stub
        Double computedVal = EvaluateString(textArea.getText());
        System.out.println(computedVal);
        flag = checkAnswer(computedVal, textField.getText());
        if(flag){
            score += 10;
            JOptionPane.showMessageDialog(frame, "Your score"+" "+score);
            timer.stop();
            ClearTextField();
            String store = buttonEvent.getActionCommand();
            NewGameOrNext(store);
        }
        else{
            JOptionPane.showMessageDialog(frame, "Wrong answer try again");
        }
        //count varialble is used to update level
        if(count % 4 == 0){
            levelNum++;
            levelLabel.setText("Level : " + levelNum);
        }
    }
    //after enter is pressed then the textfield in gui will be cleared
    private void ClearTextField() {
        // TODO Auto-generated method stub
        StringBuilder str = new StringBuilder(textField.getText());
        str.delete(0, textField.getText().length());
        textField.setText(str.toString());
    }

 }

 // not implemented yet
 class radioListener implements ActionListener{
    @Override
    public void actionPerformed(ActionEvent actionEvent) {
        // TODO Auto-generated method stub
        if(actionEvent.getActionCommand().equals("Monuments")){

        }

 }}


 class buttonListener implements ActionListener{

    @Override
    public void actionPerformed(ActionEvent buttonEvent) {
        // TODO Auto-generated method stub
        if(buttonEvent.getActionCommand().equals("Enter")){
            Double computedVal = EvaluateString(textArea.getText());
            System.out.println(computedVal);
            flag = checkAnswer(computedVal, textField.getText());
            if(flag){
                score += 10;
                JOptionPane.showMessageDialog(frame, "Your score"+" "+score);
                timer.stop();
                String store = buttonEvent.getActionCommand();
                NewGameOrNext(store);
            }
            else{
                JOptionPane.showMessageDialog(frame, "Wrong answer try again");
            }
             // same sequence of actions are performed by JButton "Enter" and by the key binding
            if(count % 4 == 0){
                //timer.stop();
                levelNum++;
                levelLabel.setText("Level : " + levelNum);
            }

        }
        if(buttonEvent.getActionCommand().equals("Clear")){
            //it removes one character at a time from JTextField
            ClearTextArea();
        }
        if(buttonEvent.getActionCommand().equals("New")){
            String store = buttonEvent.getActionCommand();
            NewGameOrNext(store);
            //checkTimer();
            if(count == 0){
                levelNum = count+1;
                levelLabel.setText("Level : " + levelNum);
            }
            //timer.start();
            panelOne.remove(buttonNew);
            panelOne.revalidate();
            panelOne.repaint();
        }
    }

    private void ClearTextArea() {
        // TODO Auto-generated method stub
        try{
            if(textField.getText().length() > 0){
                StringBuilder str = new StringBuilder(textField.getText());
                str.deleteCharAt(textField.getText().length()-1);
                textField.setText(str.toString());
            }}
            catch(NumberFormatException num){
                num.printStackTrace();
                }
    }
 }

// returns true if the computed value is equal to the entered value 
public boolean checkAnswer(Double computedVal, String text) {
    // TODO Auto-generated method stub
    if(computedVal == Integer.parseInt(text)){
        return true;
    }
    else {
        return false;
    }

}

 // infix to postfix evaluation of the expression is done here
public Double EvaluateString(String text) {
    // TODO Auto-generated method stub
    char[] tokens = text.toCharArray();

    Stack<Double> intStack = new Stack<Double> ();
    Stack<Character> opStack = new Stack<Character> ();

    for(int i = 0; i < tokens.length; i++){
        if(tokens[i] == ' '){
            continue;
        }
        if(tokens[i] >= '0' && tokens[i] <= '9' ){
            StringBuffer stringBuf = new StringBuffer();
            while(i < tokens.length && tokens[i] >= '0' && tokens[i] <= '9')
                stringBuf.append(tokens[i++]);
            //System.out.println();
            intStack.push(Double.parseDouble(stringBuf.toString()));

            }

            else if(tokens[i] == '('){
                opStack.push(tokens[i]);
            }
            else if(tokens[i] == ')'){
                while(opStack.peek() != '(')
                    intStack.push(applyOp(opStack.pop(), intStack.pop(), intStack.pop()));
                opStack.pop();
        }
            else if(tokens[i] == '+' || tokens[i] == '-' || tokens[i] == '*' || tokens[i] == '/'){
                //System.out.println("Entered");
                System.out.println(intStack.peek());
                while(!opStack.empty() && checkPrecedence(tokens[i] , opStack.peek()))
                {//System.out.println(intStack.peek()); System.out.println(opStack.peek());
                intStack.push(applyOp(opStack.pop(), intStack.pop(), intStack.pop()));}
                opStack.push(tokens[i]);
                //System.out.println(opStack.peek());
            }
         }  
    while(!opStack.empty()){
        intStack.push(applyOp(opStack.pop(), intStack.pop(), intStack.pop()));
    }
    return intStack.pop();
    //return null;
}

private boolean checkPrecedence(char charOne, char charTwo) {
    // TODO Auto-generated method stub
    if(charTwo == '(' || charTwo == ')'){
        return false;
    }
    if((charOne == '*' || charOne == '/') && (charTwo == '+' || charTwo == '-')){
        return false;
    }
    else{
        return true;
    }
}

private Double applyOp(char operator, Double valTwo, Double valOne) {
    // TODO Auto-generated method stub
    switch (operator){
    case '+':
        //System.out.println("addition");
        //System.out.println("one "+ valOne + " " + "two" + valTwo);
        //System.out.println(valOne + valTwo);
        return valOne + valTwo;
    case '-':
        //System.out.println("subtract");
        //System.out.println("one "+ valOne + " " + "two" + valTwo);
        //System.out.println(valOne - valTwo);
        return valOne - valTwo;
    case '*':
        //System.out.println("multiply");
        //System.out.println("one "+ valOne + " " + "two" + valTwo);
        //System.out.println(valOne * valTwo);
        return valOne * valTwo;
    case '/':
        //System.out.println("divide");
        //System.out.println("one "+ valOne + " " + "two" + valTwo);
        if(valTwo == 0){
            throw new UnsupportedOperationException("Cannot divided by zero");
        }
        //System.out.println(valOne / valTwo);
        return valOne / valTwo;
    }
    return 0.0;
}

public void NewGameOrNext(String store){
    // TODO Auto-generated method stub
    String line = null;
    try{
        BufferedReader reader = new BufferedReader(new FileReader("C:\\Users\\Yastika Kumar\\Documents\\operator.txt"));
        while((line = reader.readLine()) != null){
            System.out.println(line);
            queue.add(line);
        }
        reader.close();
    }
    catch(IOException exception){
        exception.printStackTrace();
    }
        flag = true;
        String display = queue.remove();
        System.out.println("count "+count);
        count++;
        textArea.setText(display);
        if(flag){
            timerField1.setText("1");
            timerField2.setText("00");
        }
        timer.start();
}

public static void main(String [] args) throws Exception{
        new MyProject();
      }

}

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.