28.04.2019 Views

[JAVA][Beginning Java 8 Games Development]

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 3 ■ A <strong>Java</strong> 8 Primer: An Introduction to <strong>Java</strong> 8 Concepts and Principles<br />

<strong>Java</strong> Logical Operators:<br />

The <strong>Java</strong> logical operators are similar to the boolean operations (union, intersection, etc.) that you learned about<br />

in school, and allow you to determine if both boolean variables hold the same value (AND), or if one of the boolean<br />

variables is different (OR), from the other. There’s also a NOT operator that reverses the value of any of the compared<br />

boolean operands. Table 3-4 shows <strong>Java</strong>’s three logical operators, and an example of each, along with a description.<br />

Table 3-4. <strong>Java</strong> Logical Operators, an Example in Which A = True and B = False, and a Description of Logical Operation<br />

Operator Example Description<br />

&& (A && B) is false A logical AND operator equates to true when BOTH operands are the same value.<br />

|| (A || B) is true A logical OR operator equates to true when EITHER operand is the same value.<br />

! !(A && B) is true A logical NOT operator reverses the logical state of the operator (or set) it is<br />

applied to.<br />

Let’s use logical operators to enhance the game logic example in the previous section by including the direction<br />

in which the InvinciBagel is moving on the screen. The existing facingDirection String variable will control the<br />

direction the InvinciBagel is facing (and moving in, if in motion). You can now use the following logical operator to<br />

determine if the InvinciBagel is facing left (W, or West); if the travelingWest boolean variable is true; AND if the hit<br />

(or passed) boolean variable on the left-hand side of the screen, hitLeftSideScrn, is also equal to true. The modified<br />

code for doing this will include two more boolean variable declarations and initializations and will look like this:<br />

boolean changeDirection = false; // Create boolean variable changeDirection, initialize to false<br />

boolean hitLeftSideScrn = false; // Create boolean variable hitLeftSideScrn, initialize to false<br />

boolean travelingWest = false; // Create boolean variable travelingWest, initialize to false<br />

hitLeftSideScrn = (invinciBagelX

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

Saved successfully!

Ooh no, something went wrong!