Pro Java 9 Games Development Leveraging the JavaFX APIs

(Michael S) #1

Chapter 24 ■ Optimizing game assets and COde, and game prOfiling Using netBeans


if (spin == 3) {
rotGameBoard.setByAngle(1350); rotSpinner.setByAngle(-1350); spinDeg += 1350;
}
rotGameBoard.play();
rotSpinner.play();
calculateQuadrantLanding();
}


The following block of Java code is array-based and is equivalent to the previous code. It is much
shorter, at 10 lines of Java 9 code, which is a reduction of 41 percent to 60 percent (depending on how you
write the code inside if (spin == n) { ... } ):


if (picked == spinner) {
int spin = random.nextInt(4);
double[] angles = { 1080, 1170, 1260, 1350 };
rotGameBoard.setByAngle(angles[spin]);
rotSpinner.setByAngle(-angles[spin]);
spinDeg += angles[spin];
rotGameBoard.play();
rotSpinner.play();
calculateQuadrantLanding();
}


After calculating your random spin value, this code fragment declares a four-element array of double
values, which represent quadrant landing angles. I then used the spin value (random.nextInt(4) outputs one
of four random quadrant values, ranging from 0 through 3) to access an angle value (via angles[spin]), which
is passed to setByAngle and which is also added to the spinDeg variable.
Notice that if spinDeg is of the int (32-bit integer) type, you must cast the double angle value to
(int) before the assignment or face a Java compiler error. In this case, you would replace spinDeg +=
angle[spin]; with the Java 9 code spinDeg += (int) angle[spin]; to avoid this Java compiler error.
If you don’t want to specify angles[spin] three times, you can alternately store the value in an angle
variable and use this double angle variable instead, as is shown in the following Java code:


if (picked == spinner) {
int spin = random.nextInt(4);
double[] angles = { 1080, 1170, 1260, 1350 };
double angle = angles[spin];
rotGameBoard.setByAngle(angle);
rotSpinner.setByAngle(-angle);
spinDeg += angle;
rotGameBoard.play();
rotSpinner.play();
calculateQuadrantLanding();
}


As you can see, there are a number of ways you can write the Java code for this game that will reduce the
lines of code used and possibly even slightly reduce a few percentage points of CPU usage that the game is
using, as was shown in the NetBeans 9 profiling section of this chapter. Since everyone has their own coding
optimization style and approach, I will leave the Java 9 code optimization to you and utilize the (longer)
prototyping code for the book material. This will allow you to better visualize what I am doing with the new
media assets within the gameplay design and development work process and focus the book content on Pro
Game Design and Development using Java 9 and its powerful JavaFX 9 API.

Free download pdf