Game Development Reference
In-Depth Information
10 - Tic Tac Toe
False
and lets the program execution continue.
29. # the first element in the tuple is the player's
letter, the second is the computer's letter.
30. if letter == 'X':
31. return ['X', 'O']
32. else:
33. return ['O', 'X']
This function returns a list with two items. The first item (that is, the string at index
0
)
will be the player's letter, and the second item (that is, the string at index
1
) will be the
computer's letter. This if-else statement chooses the appropriate list to return.
Deciding Who Goes First
35. def whoGoesFirst():
36. # Randomly choose the player who goes first.
37. if random.randint(0, 1) == 0:
38. return 'computer'
39. else:
40. return 'player'
The
whoGoesFirst()
function does a virtual coin flip to determine who goes first,
the computer or the player. Instead of flipping an actual coin, this code gets a random
number of either
0
or
1
by calling the
random.randint()
function. If this function call
returns a 0, the
whoGoesFirst()
function returns the string
'computer'
. Otherwise,
the function returns the string
'player'
. The code that calls this function will use the
return value to know who will make the first move of the game.
Asking the Player to Play Again
42. def playAgain():
43. # This function returns True if the player wants to
play again, otherwise it returns False.
44. print('Do you want to play again? (yes or no)')
45. return input().lower().startswith('y')
The
playAgain()
function asks the player if they want to play another game. The
function returns
True
if the player types in
'yes'
or
'YES'
or
'y'
or anything that
begins with the letter Y. For any other response, the function returns
False
. The order of
the method calls on line 151 is important. The return value from the call to the
input()
function is a string that has its
lower()
method called on it. The
lower()
method
returns another string (the lowercase string) and that string has its
startswith()
method called on it, passing the argument
'y'
.