JavaFX Math Game

Let’s make a simple math game using JAVAFX program. This is an ongoing project so I will add more functionalities in futures post.

Here is the interface that we want to develop using JAVAFX:

The interface is composed by 3 Labels (in Aquamarine color) one TextField object and one Button.

Moving down we have one simple Label and another TextField to show the user the current score.

The Layout in JavaFX is a Flow Layout: this means that all controls(Buttons, Labels and TestFields) will be placed horizontally and if others controls do not fit the GUI Interface they will be showed below the first row of controls.

The Flow Layout is quite a useful Layout Schema to arrange Buttons, Labels and other controls.

As usual the complete program will be available in a link at the bottom of this page. Here for brevity we will discuss the key elements of the program

FlowPane mybox = new FlowPane();
mybox.setPadding(new Insets(40,40,40,40));
Scene myscene = new Scene(mybox,640,260);
stage.setScene(myscene);
stage.setTitle("My Math Game");

We start declaring what type of Layout is, we define padding space between the difference controls.

Then we declare a new Scene and we add the scene to the Stage as represented in the line above.

Now that we have the main framework of the Application we start defining the major controls like below:

label one = new Label();
one.setFont(new Font(36));
one.setStyle("-fx-border-color:blue; -fx-background-color: aquamarine;");
one.setAlignment(Pos.CENTER);

Line 3 of the above block it is important : in JAVAFX you can use CSS file type in order to customize the control (function setStyle access CSS string to format the JAVAFX Control)

At this point we set all the others control for our Math Game

Math Game GUI

All controls are added to the Scene using this command

mybox.getChildren().addAll(one,two,three,four,confirm,sep,yourScore,showScore,endgame);     

Now the the GUI is explained let’s see what happen when the user press the Confirm Button (confirm)

confirm.setOnAction((event)->{
			printme(one,two,three,four,showScore,yourScore,endgame,confirm);
		});
	

As you can see when the button is pressed a function printme is called. We pass to the function:

Label one (first number)

Label two (math sign)

Label three (second number)

Label showScore (which report the level of the game)

Label yourScore (which show the actual score)

Label endgame (a label set to not visible)

Button (confirm – this button will get disable if the game is over)

The scope of the function printme is to retrieve the value from the GUI and verify whether the result is correct or not.

To values stores in each control are type String and therefore we need to cast it in integer

		int e1=Integer.parseInt(one.getText());
		int e2=Integer.parseInt(three.getText());
		int myresult =Integer.parseInt(four.getText());

Then we need to retrieve the sign of the operation (in the example below the code to test if the sign is equal to “+”

If that is the case we retrieve the value from the labels and check if the sum of the 2 values equals the input provided by the user

if (two.getText().equals("+")) {
if (e1+e2==myresult) {

If that is the case test is passed and therefore we can clear the TextField

            four.clear();

and we also increase the score variable totalcounter : This is a public variable for the class accessible by all functions of the class

				totalcounter++;

Then we have to generate 2 randoms number of the next question. We do that by calling the function genRandomNumber(one,two,three)

We have seen what happens if the user put the right answer. But what happens if the user put the wrong one?

If the test is failed we deduct the score with 5 points and set TextField with Red background color

if (e1+e2!=myresult) {
		four.setStyle("-fx-control-inner-background: red;");
		totalcounter-=5;
			}

But let’s go back and assume that the user put the right answer.

We call a function called genRandomNumber.

As you can see this function accepts 3 arguments (label one for the left number, label three for the second number and label two of the mathematical sign of the operation.

This function will generate

  1. Two random numbers
  2. One random number between 1 and 3 in order to select the math operation “+” or “-” or “*”
public void genRandomNumber(Label one,Label two,Label three) {
		levelchecker();
		Random r = new Random();
		int result = r.nextInt((max-min)+1)+min;
		one.setText(String.valueOf(result));
		result = r.nextInt((max-min)+1)+min;
		three.setText(String.valueOf(result));
		

The label one and three are both re-set showing the random number generated. The following part of the function will generate a random number between 1 and 3 and update label 2 with the corresponding sign

result = r.nextInt((maxsign-minsign)+1)+minsign;
		if (level2==true) {
			result=1;
		}
		if (result==1) {
			two.setText("*");
		}
		else if (result==2) {
			two.setText("+");
		}
		else {
			two.setText("-");
		}

As you might have noticed in the block above there is one condition relating level2. If the user has achieved the level 2 all operations will be multiplication to make it more challenging (this is achieved by setting result equal to 1).

level2 is another class variable type boolean that is used to test if the user has achieved the most difficult level. In order to check the current level there is another function that is called levelchecker()

Here is the function:

public void levelchecker() {
		if ( (totalcounter>=8) && (level1==false) ) {
			max = max + 4;
			min = min + 4;	
			level1=true;
			levelDesription="Level 1";
		}
		if ( (totalcounter>=16) && (level2==false) ) {
			max = max + 8;
			min = min + 4;	
			level2=true;
			levelDesription="Level 2";
		}
		if ( (totalcounter>=24) && (level2==false) ) {
			max = max + 4;
			min = min + 3;	
			level2=true;
			levelDesription="Level 2";
		}
	}

This function will be called any time the user input a correct answer to check the total number of points stored in the totalcounter variable.

If the points are between greater and 8 and the Level 1 has not been achieved yet the code will set the level1 equal to True and increase the class variable of 4 units each. So everytime a random number is generated the range of random number will pass from (0-20) to (4-24). This in fact will increase the complexity of the computation.

Once the next level is achieved there is not way to descend down to the more easier level because the boolean variable has been already turned equal to true. Therefore if I have 9 points and move to Level1 but if in the next question I make a mistake I will have only 5 points but I will stay in the Level 1 and not to regress to Level 0. Same thing happens for the other 2 levels

What happens if making a mistake brings negative the number of points? Well in that case GAME is OVER!

Let’s check how we do that:

if (totalcounter<=0) {
			endgame.setText("GAME OVEER!!!!!!");
			endgame.setVisible(true);
			confirm.setDisable(true);
		}

As you can see we will do 2 things: disable the confirm button using setDisable and set visible the GAME OVER label using the command endgame.setViisble(true)

For example i am in Level 1 and I have only 4 points. I introduce a wrong answer -5 points : Game is Over.

In this link here the source code of the program.

This little project is not over yet. I will add few functionalities in the fortcoming days.

JAVA Programming

This section of the Blog is for Java. Java in my view is a really intesting language. It is full of libraries to basically do anything.

Java is a commonly used for Android Application but also for Enterprise Application.

I can run as a web application and it is portable to many operating systems.

The structure of the Language is not too different from C or C++ although there are main differences in term of architecture and memory management.

Current Project:

Project 1 : JavaFX Math Game