Game Development Reference
In-Depth Information
that they are of the same type. Again, watch out that testing the equality of two val-
ues is done using a double equals sign ( == ). This is needed, because the single equals
sign is already used for assignments. The difference between these two operators is
very important:
x=5;
this instruction means: assign the value 5 to x !
this expression means: is x equal to 5?
x==5
6.3.2 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 C#. These
operators have a special notation in C#:
&& is the logical 'and' operator
|| is the logical 'or' operator
! is the logical 'not' operator
We can use these operators to check for complicated logical statements, so that we
can execute instructions only in very particular cases. For example, we 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 life force is larger than 0:
if (playerPoints > 10000 && enemyLifeForce == 0 && playerLifeForce > 0)
spriteBatch.Draw(winningOverlay, Vector2.Zero, Color.White);
6.3.3 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 C#, these truth values
are represented by the true and false keywords.
Next to being used for expression a condition in an if -instruction, logical expres-
sions can be applied for a lot of different things. 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 called bool . This is one of the primitive types of C#.
The type is 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:
bool test;
test = x>3 && y<5;
Search WWH ::




Custom Search