Game Development Reference
In-Depth Information
15 - Reversi
When we start a new game of Reversi, it isn't enough to have a completely blank board.
At the very beginning, each player has two tiles already laid down in the very center, so we
will also have to set those.
We do not have to return the board variable, because board is a reference to a list.
Even when we make changes inside the local function's scope, these changes happen in the
global scope to the list that was passed as an argument. (Remember, this is one way list
variables are different from non-list variables.)
Creating a New Game Board Data Structure
36. def getNewBoard():
37. # Creates a brand new, blank board data structure.
38. board = []
39. for i in range(8):
40. board.append([' '] * 8)
41.
42. return board
The getNewBoard() function creates a new board data structure and returns it. Line
38 creates the outer list and assigns a reference to this list to board . Line 40 create the
inner lists using list replication. ( [' '] * 8 is the same as [' ', ' ', ' ', ' ',
' ', ' ', ' ', ' '] but with less typing.) The for loop here runs line 40 eight
times to create the eight inner lists. The spaces represent a completely empty game board.
Checking if a Move is Valid
45. def isValidMove(board, tile, xstart, ystart):
46. # Returns False if the player's move on space xstart,
ystart is invalid.
47. # If it is a valid move, returns a list of spaces
that would become the player's if they made a move here.
48. if board[xstart][ystart] != ' ' or not isOnBoard
(xstart, ystart):
49. return False
50.
51. board[xstart][ystart] = tile # temporarily set the
tile on the board.
52.
53. if tile == 'X':
54. otherTile = 'O'
55. else:
56. otherTile = 'X'
57.
58. tilesToFlip = []
isValidMove() is one of the more complicated functions. Given a board data
Search WWH ::




Custom Search