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 />

Figure 17-11. Use Run ➤ Project to test the game, and collide with the objects on the screen, updating your scoreboard<br />

Optimizing the scoringEngine() Method: Using Logical If Else If<br />

Although the previous series of if() statements will do the job that we are trying to do here, we really need to emulate<br />

the break; statement that we would have at our disposal if we were using the <strong>Java</strong> switch-case statement type. To<br />

optimize this method, we want to break out of this evaluation series once the object type that is involved in the<br />

collision has been determined. We can do this by attaching all of these conditional if() statements together, using the<br />

<strong>Java</strong> else-if capability. If a condition in this structure is satisfied, the rest of the if-else-if structure is not evaluated,<br />

which is the equivalent of a break; statement in a switch-case structure. To optimize this even further, you would<br />

want to place the most common (the highest number of collidable objects in the Scene of that object type) objects at<br />

the top of this if-else-if structure, and the least common objects at the bottom of the structure. All you have to do to<br />

accomplish this is tie your if() condition blocks together by using the <strong>Java</strong> else keyword, as shown in Figure 17-12. This<br />

creates a more compact and processing-optimized conditional evaluation structure, and uses fewer lines of <strong>Java</strong> code:<br />

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

if(object instanceof Prop) {<br />

invinciBagel.gameScore+=5;<br />

invinciBagel.playiSound0();<br />

} else if(object instanceof PropV) {<br />

invinciBagel.gameScore+=4;<br />

invinciBagel.playiSound1();<br />

} else if(object instanceof PropH) {<br />

invinciBagel.gameScore+=3;<br />

invinciBagel.playiSound2();<br />

} else if(object instanceof PropB) {<br />

invinciBagel.gameScore+=2;<br />

invinciBagel.playiSound3(); }<br />

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

}<br />

402<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!