Game Development Reference
In-Depth Information
Logic Operators
In logical terms, a condition is also called a predicate . The operators that are used in logic to
connect predicates ( and , or , and not ) can also be used in JavaScript. They have a special notation:
&& is the logical and operator.
|| is the logical or operator.
! is the logical not operator.
You can use these operators to check for complicated logical statements so that you can execute
instructions only in very particular cases. For example, you can draw a “You win!” overlay only if
the player has more than 10,000 points, the enemy has a life force of 0, and the player's life force is
greater than 0:
if (playerPoints > 10000 && enemyLifeForce === 0 && playerLifeForce > 0)
Canvas2D.drawimage(winningOverlay, { x : 0, y : 0 }, 0, { x : 0, y : 0 });
The Boolean Type
Expressions that use comparison operators or that connect other expressions with logical operators
also have a type, just like expressions that use arithmetic operators. After all, the result of such an
expression is a value: one of the two truth values yes or no . In logic, these values are called true and
false . In JavaScript, these truth values are represented by the true and false keywords.
In addition to being used to express a condition in an if instruction, logical expressions can be
applied in a lot of different situations. A logical expression is similar to an arithmetic expression,
except that it has a different type. For example, you can store the result of a logical expression in a
variable, pass it as a parameter, or use that result again in another expression.
The type of logical values is Boolean , named after the English mathematician and philosopher George
Boole (1815-1864). Here is an example of a declaration and an assignment of a Boolean variable:
var test;
test = x > 3 && y < 5;
In this case, if x contains, for example, the value 6 and y contains the value 3, the Boolean expression
x > 3 && y < 5 will evaluate to true and this value will be stored in the variable test . You can also
store the Boolean values true and false directly in a variable:
var isAlive = false;
Boolean variables are extremely handy for storing the status of different objects in a game. For example,
you can use a Boolean variable to store whether the player is still alive, whether the player is currently
jumping, whether a level is finished, and so on. You can use Boolean variables as an expression in
an if instruction:
if (isAlive)
// do something
 
Search WWH ::




Custom Search