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

Now let’s add even more realism to this auto-attack game play, by randomizing which side the Enemy sprite<br />

emerges from, so that the game player does not know what to expect. Currently, we are alternating sides, so we need<br />

to add a randomization of the takeSides boolean flag at the strategic place within our code. Let’s write this code next.<br />

Randomizing an Auto-Attack: Using .nextBoolean with takeSides<br />

Even though we set the takeSides boolean flag right before we exit our initiateAttack() method after completing an<br />

attack, there is nothing that says we can’t set it again before we call an attack by setting callAttack equal to true in the<br />

if(attackCounter >= attackFrequency) structure, which you can see I have done in Figure 17-54, using the following<br />

<strong>Java</strong> statement:<br />

takeSides = randomNum.nextBoolean;<br />

Figure 17-54. Set the boolean takeSides variable to use a .nextBoolean() method call off a randomNum Random object<br />

Now that you have set the takeSides boolean flag variable in this way inside the Enemy .update() method, you<br />

can further optimize your code by removing the takeSides = true; and takeSides = false; statements, which are<br />

currently located inside your if(onScreen && launchIt) else statement (reference Figure 17-45).<br />

Since those alternating boolean values will now be subsequently replaced by the .nextBoolean() method call in<br />

the if(!callAttack) structure, they can be safely removed, because the if(!callAttack) conditional structure randomly<br />

sets these two boolean values. The result of this is that now the iBeagle Enemy Actor object will randomly appear from<br />

out of either side of the screen, and the game player cannot anticipate where the attack is coming from anymore.<br />

www.it-ebooks.info<br />

447

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

Saved successfully!

Ooh no, something went wrong!