Game Development Reference
In-Depth Information
As you can see, you may use single quotes without a backslash in a string delimited by double quotes,
and vice versa. The syntax diagram for representing all these symbols is given in Figure 12-2 .
symbol
\
n
r
t
b
'
\
digit
character
Figure 12-2. The syntax diagram for symbols
String Operations
In the Painter game, you use string values in combination with the drawText method to draw text of
a certain color in a desired font somewhere on the screen. In this case, you want to write the current
score at upper left on the screen. The score is maintained in a member variable called score . This
variable is increased or decreased in the update method of PaintCan . How can you construct the text
that should be printed on the screen, given that part of this text (the score) is changing all the time?
The solution is called string concatenation , which means gluing one piece of text after another.
In JavaScript (and in many other programming languages), this is done using the plus sign. For
example, the expression "Hi, my name is " + "Arjan" results in the string "Hi, my name is Arjan" .
In this case, you concatenate two pieces of text. It's also possible to concatenate a piece of text and
a number. For example, the expression "Score: " + 200 results in the string "Score: 200" . Instead
of using a constant, you can use a variable. So if the variable score contains the value 175, then the
expression "Score: " + score evaluates to "Score: 175" . By writing this expression as a parameter
of the drawText method, you always draw the current score on the screen. The final call to the
drawText method then becomes (see the PainterGameWorld class)
Canvas2D.drawText("Score: " + this.score, new Vector2(20, 22), Color.white);
Watch out: concatenation only makes sense when you're dealing with text. For example, it isn't
possible to “concatenate” two numbers: the expression 1 + 2 results in 3 , not 12 . Of course, you can
concatenate numbers represented as text : "1" + "2" results in "12" . Making the distinction between
text and numbers is done by using single or double quotes.
In fact, what is secretly done in the expression "Score: " + 200 is a type conversion or cast .
The numerical value 200 is automatically cast to the string "200" before being concatenated to the
other string.
 
 
Search WWH ::




Custom Search