Game Development Reference
In-Depth Information
Using List References in makeMove()
Let's go back to the makeMove() function:
47. def makeMove(board, letter, move):
48. board[move] = letter
When we pass a list value as the argument for the board parameter, the function's local
variable is a copy of the reference, not a copy of the list itself. The letter and move
parameters are copies of the string and integer values that we pass. Since they are copies, if
we modify letter or move in this function, the original variables we used when we
called makeMove() would not be modified. Only the copies would be modified.
But a copy of the reference still refers to the same list that the original reference refers to.
So if we make changes to board in this function, the original list is modified. When we
exit the makeMove() function, the copy of the reference is forgotten along with the other
parameters. But since we were actually changing the original list, those changes remain
after we exit the function. This is how the makeMove() function modifies the list that a
reference of is passed.
Checking if the Player Has Won
50. def isWinner(bo, le):
51. # Given a board and a player's letter, this function
returns True if that player has won.
52. # We use bo instead of board and le instead of letter
so we don't have to type as much.
53. return ((bo[7] == le and bo[8] == le and bo[9] == le)
or # across the top
54. (bo[4] == le and bo[5] == le and bo[6] == le) or #
across the middle
55. (bo[1] == le and bo[2] == le and bo[3] == le) or #
across the bottom
56. (bo[7] == le and bo[4] == le and bo[1] == le) or #
down the left side
57. (bo[8] == le and bo[5] == le and bo[2] == le) or #
down the middle
58. (bo[9] == le and bo[6] == le and bo[3] == le) or #
down the right side
59. (bo[7] == le and bo[5] == le and bo[3] == le) or #
diagonal
60. (bo[9] == le and bo[5] == le and bo[1] == le)) #
diagonal
Lines 53 to 60 in the isWinner() function are actually one very long if statement. We
use bo and le for the board and letter parameters so that we have less to type in this
Search WWH ::




Custom Search