Game Development Reference
In-Depth Information
In this case, if
x
contains, for example, the value 6 and
y
contains the value 3, then
the boolean expression
x>3 && y<5
will evaluate to
true
and this value will be stored
in the variable
test
. We can also store the boolean values
true
and
false
directly in a
variable:
bool
isAlive =
false
;
Boolean variables are extremely handy to store the status of different objects in the
game. For example, you could use a boolean variable to store whether or not the
player is still alive, or if the player is currently jumping, or if a level is finished, and
so on. We can use boolean variables as an expression in an
if
-instruction:
if
(isAlive)
dosomething
In this case, if the expression
isAlive
evaluates to
true
, the body of the
if
-instruction
is executed. You might think that this code generates a compiler error, and that we
need to do a comparison of the boolean variable, like this:
if
(isAlive ==
true
)
dosomething
However, this extra comparison is not necessary. A conditional expression like in
the
if
-instruction
has to evaluate to
true
or
false
. Since a boolean variable already
represents either one of these two values, we do not need to perform the comparison
anymore. In fact, if the previous comparison would be needed, then we also would
need to compare that outcome again with a boolean value:
if
((isAlive ==
true
)==
true
)
dosomething
And this gets worse:
if
(((((((isAlive ==
true
)==
true
)==
true
)==
true
)==
true
)==
true
)==
true
)
dosomething
In summary: do not make things more complicated than they are. If the outcome is
already a boolean value, we do not have to compare it to anything anymore.
We can use the
bool
type to store complex expressions that are either
true
or
false
.
Let us look at a few additional examples:
bool
a=12>5;
bool
b = a && 3+4==8;
bool
c=a||b;
if
(!c)
a=
false
;