Game Development Reference
In-Depth Information
Letting the Player Enter Their Move
75. def getPlayerMove(board):
76. # Let the player type in his move.
77. move = ' '
78. while move not in '1 2 3 4 5 6 7 8 9'.split() or not
isSpaceFree(board, int(move)):
79. print('What is your next move? (1-9)')
80. move = input()
81. return int(move)
The getPlayerMove() function asks the player to enter the number for the space
they wish to move. The function makes sure that they enter a space that is a valid space (an
integer 1 through 9). It also checks that the space that is not already taken, given the Tic
Tac Toe board passed to the function in the board parameter.
The two lines of code inside the while loop simply ask the player to enter a number
from 1 to 9. The loop's condition will keep looping, that is, it will keep asking the player
for a space, as long as the condition is True . The condition is True if either of the
expressions on the left or right side of the or keyword is True .
The expression on the left side checks if the move that the player entered is equal to '1' ,
'2' , '3' , and so on up to '9' by creating a list with these strings (with the split()
method) and checking if move is in this list. '1 2 3 4 5 6 7 8 9'.split()
evaluates to be the same as ['1', '2', '3', '4', '5', '6', '7', '8',
'9'] , but it easier to type.
The expression on the right side checks if the move that the player entered is a free space
on the board. It checks this by calling the isSpaceFree() function we just wrote.
Remember that isSpaceFree() will return True if the move we pass is available on
the board. Note that isSpaceFree() expects an integer for move , so we use the int()
function to evaluate an integer form of move .
We add the not operators to both sides so that the condition will be True when both of
these requirements are unfulfilled. This will cause the loop to ask the player again and
again until they enter a proper move.
Finally, on line 81, we will return the integer form of whatever move the player entered.
Remember that input() returns a string, so we will want to use the int() function to
evaluate the string as an integer.
Short-Circuit Evaluation
You may have noticed there is a possible problem in our getPlayerMove() function.
What if the player typed in 'X' or some other non-integer string? The move not in
Search WWH ::




Custom Search