Game Development Reference
In-Depth Information
The first step to allow typing is to start with an empty string. Every time the player
types in a letter, we can then append the appropriate character to said string. But
in order to do this, we need to determine the correct character. Recall that
Chapter
5
also discussed the idea of virtual keys (how every key on the keyboard corres-
ponds to an index in an
enum
). So, for example,
K_A
might correspond to the “A”
key on the keyboard. Conveniently, in a typical system, the letter virtual keys are
sequential within the
enum
. This means that that
K_B
would be one index after
K_A
,
K_C
would be an index after
K_B
, and so on. It just so happens that the
ASCII character “B” is also sequentially after the ASCII character “A.” Taking
advantage of this parallel allows us to implement a function that converts from a
letter key code to a particular character:
function
KeyCodeToChar(
int
keyCode
)
// Make sure this is a letter key
if
keyCode
>= K_A &&
keyCode
<= K_Z
// For now, assume upper case.
// Depending on language, may have to cast to
a char
return
('A' + (
char
)(
keyCode
- K_A))
else if
keyCode
== K_SPACE
return
' '
else
return
''
end
end
Let's test out this code with a couple examples. If
keyCode
is
K_A
, the result of
the subtraction should be 0, which means the letter returned is simply “A.” If in-
stead
keyCode
is
K_C
, the subtraction would yield 2, which means the function
would return A + 2, or the letter “C.” These examples prove that the function gives
the results we expect.
Once we've implemented this conversion function, the only other code that needs
to be written is the code that checks whether any key from
K_A
to
K_Z
was
“just pressed.” If this happens, we convert that key to its appropriate code and ap-
pend said character to our string. If we wanted to, we could also further extend
KeyCodeToChar
to support upper- and lowercase by defaulting to lowercase