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

The Random class has two constructors, a Random() constructor, which we will be using, and an overloaded<br />

Random(long seed) constructor, where you can specify the seed value for the Random Number Generator that this<br />

class implements. Once you have a Random object, you can call one of almost two dozen (22) methods that generate<br />

different types of random values. The method calls we’ll be using during this chapter are the .nextInt(int bound) and<br />

.nextBoolean() method calls. In case you are wondering, there is also a .nextInt() method, but we need to generate a<br />

random number inside of a specific range (zero to bottom of screen), and the .nextInt(int bound) allows generation<br />

of a random number range from zero to the specified integer bound (boundary) passed over inside of the method call.<br />

We will be using the Random class for our Enemy attack strategy (and code) in the Enemy.java class. Let’s go<br />

ahead and declare and instantiate a Random object named randomNum at the top of the Enemy.java class, as shown<br />

in Figure 17-28, using the following compound (declaration plus instantiation) <strong>Java</strong> 8 programming statement:<br />

protected static final Random randomNum = new Random();<br />

Figure 17-28. Declare and instantiate a Random Number Generator at the top of the Enemy.java class using Random()<br />

We will be using this Random (number generator) object throughout the remainder of this chapter to add<br />

random attack positions, sides, and bullets for our Enemy iBeagle object, so that he can try his best to take down the<br />

InvinciBagel character (the game player), or at least cause him to generate lots of negative scoring points if he can!<br />

Mounting the Attack: Coding the Enemy Onslaught<br />

First we need to declare counter variables, seen highlighted in Figure 17-29, using the following two <strong>Java</strong> statements:<br />

int attackCounter = 0;<br />

int attackFrequency = 250;<br />

www.it-ebooks.info<br />

417

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

Saved successfully!

Ooh no, something went wrong!