28.04.2019 Views

[JAVA][Beginning Java 8 Games Development]

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

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

Creating the Scoring Engine Logic: .scoringEngine( )<br />

What I want to base scoring on in this game is the type of Object, as we are going to have fixed Actor subclass objects<br />

for the InvinciBagel to score against, such as Prop, PropV, PropH, PropB, Treasure, Projectile, Enemy, and similar.<br />

Since the switch-case structure does not support using an Object in its evaluation logic, we are going to have to use<br />

conditional if() statements, along with the <strong>Java</strong> instanceof operator, which, as you can tell from its name, is used to<br />

determine object type or instance; in this particular case, to start with, if the Actor object is an instance of the Prop,<br />

PropV, PropH, or PropB class. The basic <strong>Java</strong> code structure for the scoringEngine() method evaluates one if() for<br />

each Actor object type, and then sets the gameScore variable, which is displayed by the scoreText Text object, inside<br />

of the invinciBagel object. This programming logic can all be seen in Figure 17-9. The <strong>Java</strong> code should look like this:<br />

private void scoringEngine(Actor object){<br />

if(object instanceof Prop) { invinciBagel.gameScore+=5; }<br />

if(object instanceof PropV) { invinciBagel.gameScore+=4; }<br />

if(object instanceof PropH) { invinciBagel.gameScore+=3; }<br />

if(object instanceof PropB) { invinciBagel.gameScore+=2; }<br />

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

}<br />

Figure 17-9. Code basic conditional if() statements inside of the .scoringEngine() method using instanceof<br />

399<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!