28.04.2019 Views

[JAVA][Beginning Java 8 Games Development]

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 17 ■ Enhancing Game Play: Creating a Scoring Engine, Adding Treasure and an Enemy Auto-Attack Engine<br />

Creating the Score UI Design: Text and Font Objects<br />

The first thing that we need to do to implement a display for our scoring engine is to open the InvinciBagel.java tab in<br />

NetBeans, and add an integer variable to hold a numeric score accumulation, and a Text UI element object, to display<br />

the score on the bottom of the screen, alongside our other UI elements. The Text class in <strong>Java</strong>FX is used to work with<br />

text elements in your games, and even has its own javafx.scene.text package, because text is an important element in<br />

applications. The integer data type allows your game players to score well into the billions of points, so this should be<br />

adequate for holding any magnitude of numeric score your game player can rack up. We will place these <strong>Java</strong> variable<br />

and object declarations, which can be seen highlighted in Figure 17-1, at the very top of the InvinciBagel.java class,<br />

right after the WIDTH and HEIGHT constant declarations, and the <strong>Java</strong> code should look like the following:<br />

int gameScore = 0;<br />

Text scoreText;<br />

Figure 17-1. Add an integer variable named gameScore and initialize it to 0, then add a Text object named scoreText<br />

Mouse-over the wavy red error highlighting, and click next to the line of code containing this error, to select it<br />

(which is shown using a light blue color). Next, use an Alt-Enter work process to bring up the error resolution helper<br />

pop-up, shown at the bottom of Figure 17-1, and double-click on the “Add import for javafx.scene.text.Text” option to<br />

have NetBeans write this Text class import statement for you.<br />

Now we are ready to open the .createSplashScreenNodes() method, and instantiate this Text object named<br />

scoreText, using a <strong>Java</strong> new keyword and the Text() constructor method. After you do this, you can call the .setText()<br />

method, and reference the gameScore integer, using the String.valueOf() method, as well as positioning it in your UI<br />

layout design, using the .setLayoutX() and .setLayoutX() methods, using the following <strong>Java</strong> code shown in Figure 17-2:<br />

scoreText = new Text();<br />

scoreText.setText(String.valueOf(gameScore));<br />

scoreText.setLayoutY(365);<br />

scoreText.setLayoutX(565);<br />

394

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!