Pro Java 9 Games Development Leveraging the JavaFX APIs

(Michael S) #1

© Wallace Jackson 2017 465
W. Jackson, Pro Java 9 Games Development, https://doi.org/10.1007/978-1-4842-0973-8_19


CHAPTER 19


Game Content Engine: AI Logic


with Random Content Selection


Methods


Now that you have your game board animated and randomly selecting a quadrant on each click of the 3D
spinner UI element, we need to figure out how to track these spins in some way that will consistently tell
us which quadrant we have landed on. That way, we can map the correct diffuse texture maps onto that
quadrant’s game board squares. We will do this using simple math, using int (integers) no less, as the 360
degrees in a circle and the 90 degrees in a quadrant are all evenly divisible. This will be a fun chapter, as AI
can often be coded using compact Java code! A lot of thinking about logic will be involved with some testing
to refine the values once an approach has been determined.
During the chapter, we will create two new int (integer) variables: spinDeg for spin degrees, which
will be an accumulator (or total) of the rotational degrees that have been spun by the players, and
quadrantLanding, which will hold the latest result of a simple yet powerful calculation that will always tell
us what quadrant the latest spin landed on.
We’ll create six new methods including a calculateQuadrantLanding() method to ascertain what the
current quadrant is, a resetTextureMaps() method to reset the game board square texture maps to their
defaults before each new spin, and populateQuadrantOne() through populateQuadrantFour() to hold
random number generation and the conditional if() processing that picks the mixture of game board square
content for each of the player’s random spins.


Coding a Random Spin Tracker: Remainder Operator


To get the result of the latest quadrant that a player has landed on after a spin, we need to track the percentage
after the whole number of spins, especially as we are spinning three times plus the offset. So, for 45 + 1080 in
if() condition 1, this will be Quadrant One. For 45 + 1170 in if() condition 2, this will be Quadrant Two. For 45



  • 1260 in if() condition 3, this will be Quadrant Three. For if() condition 4, this will be 45 + 1350, for Quadrant
    Four. However, for subsequent spins, this will not always be the same offset starting at 45 degrees, so we need
    to keep a spinDeg total variable and add each spin angle to get a total, which we can divide by 360 to get the
    full rotations and then use the remainder % operand in Java to get the angle rotation past the full turns that the
    game board quadrant has landed on. The equation looks something like the following in Java code:


int spinDeg = 45 ; // Initialize at 45 degrees
int quadrantLanding; // Initialize at zero
spinDeg = spinDeg + lastSpinRotation; // Total Spin Angle Accumulator
quadrantLanding = spinDeg % 360; // Resting Angle Offset Calculation

Free download pdf