Pro Java 9 Games Development Leveraging the JavaFX APIs

(Michael S) #1
Chapter 5 ■ a Java primer: introduCtion to Java ConCepts and prinCiples

Let’s use logical operators to enhance the game logic example I used in the previous section to ascertain
whether a player has fallen off of the game board (moved beyond the edge) while they are moving the game
piece (that is, while it is their turn).
The modified code for doing this will include a logical AND operator, which will set the fellOffBoard
boolean variable to a value of true, if gameBoardEdge = true AND turnActive = true. The Java code to
ascertain this will look like the following Java statements:


boolean gameBoardEdge = false; // boolean variable gameBoardEdge is initialized to be false
gameBoardEdge = (GamePieceX < 0); // boolean gameBoardEdge set TRUE if past (before) left side
fellOffBoard = (gameBoardEdge && turnActive) // It's your turn, but you fell off the left edge!


Now you have a little practice declaring and initializing variables and using relational and logical
operators to determine the turn, boundary, and location of your game pieces. Next, let’s take a look at Java
assignment operators.


Java Assignment Operators: Assigning a Result to a Variable


The Java assignment operators assign a value from a logic construct on the right side of the assignment
operator to a variable on the left side of the assignment operator. The most common assignment operator is
also the most commonly used operator in the Java programming language, the equals operator. The equals
operator can be prefixed with any of the arithmetic operators to create an assignment operator that also
performs an arithmetic operation, as shown in Table 5-5. This allows a “denser” programming statement to
be created when the variable itself is going to be part of the equation. Thus, instead of having to write
C = C + A;, you can simply use C+=A; and achieve the same end result. We’ll be using this assignment
operator shortcut often during our game logic design.


Table 5-5. Java Assignment Operators, What That Assignment Is Equal to in Code, and a Description of the
Operator


Operator Example Description


= C=A+B Basic assignment operator: assign value from right-side operands
to left-side operand


+= C+=A equals C=C+A ADD assignment operator: add right operand to left operand; put
result in left operand


-= C-=A equals C=C-A SUB assignment operator: subtract right operand from left
operand; put result in left operand


= C=A equals C=C*A MULT assignment: multiply right operand and left operand; put
result in left operand


/= C/=A equals C=C/A DIV assignment operator: divide left operand with right operand;
result in left operand


%= C%=A equals C=C%A MOD assignment: divide left operand with right operand; put
remainder in left operand


Finally, we’re going to take a look at conditional operators, which also allow us to code powerful
game logic.

Free download pdf