Game Development Reference
In-Depth Information
Deciding Which Cave has the Friendly Dragon
28. friendlyCave = random.randint(1, 2)
Now we are going to have the program randomly chose which cave had the friendly
dragon in it. Our call to the
random.randint()
function will return either the integer
1
or the integer
2
, and store this value in a variable called
friendlyCave
.
30. if chosenCave == str(friendlyCave):
31. print('Gives you his treasure!')
Here we check if the integer of the cave we chose (
'1'
or
'2'
) is equal to the cave
randomly selected to have the friendly dragon. But wait, the value in
chosenCave
was a
string (because
input()
returns strings) and the value in
friendlyCave
is an integer
(because
random.randint()
returns integers). We can't compare strings and integers
with the
==
sign, because they will always be different (
'1'
does not equal
1
).
Comparing values of different data types with the
==
operator will always evaluate to
False
.
So we are passing
friendlyCave
to the
str()
function, which returns the string
value of friendlyCave.
What the condition in this
if
statement is really comparing is the string in
chosenCave
and the string returned by the
str()
function. We could have also had this
line instead:
if int(chosenCave) == friendlyCave:
Then the
if
statement's condition would compare the integer value returned by the
int
()
function to the integer value in
friendlyCave
. The return value of the
int()
function is the integer form of the string stored in
chosenCave
.
If the
if
statement's condition evaluates to
True
, we tell the player they have won the
treasure.
32. else:
33. print('Gobbles you down in one bite!')
Line 32 has a new keyword. The
else
keyword always comes after the if-block. The
else-block that follows the else keyword executes if the condition in the
if
statement was