MCPcopy Create free account
hub / github.com/asweigart/PythonStdioGames / isValidMove

Function isValidMove

src/gamesbyexample/reversegam.py:87–135  ·  view source on GitHub ↗

Returns False if the player's move on xstart, ystart is invalid. If it is a valid move, returns a list of spaces that would become the player's if they made a move here.

(board, tile, xstart, ystart)

Source from the content-addressed store, hash-verified

85
86
87def isValidMove(board, tile, xstart, ystart):
88 """Returns False if the player's move on xstart, ystart is invalid.
89 If it is a valid move, returns a list of spaces that would become
90 the player's if they made a move here."""
91 if board[(xstart, ystart)] != ' ' or not isOnBoard(xstart, ystart):
92 return False
93
94 board[(xstart, ystart)] = tile # Set the tile on the board.
95
96 if tile == 'X':
97 otherTile = 'O'
98 else:
99 otherTile = 'X'
100
101 tilesToFlip = []
102 for xdirection, ydirection in ALL_DIRECTIONS:
103 x, y = xstart, ystart
104 x += xdirection # First step in the x direction.
105 y += ydirection # First step in the y direction.
106 if isOnBoard(x, y) and board[(x, y)] == otherTile:
107 # Find if the other player's tile next to our tile.
108 x += xdirection
109 y += ydirection
110 if not isOnBoard(x, y):
111 continue
112 while board[(x, y)] == otherTile:
113 x += xdirection
114 y += ydirection
115 # Break out of while loop, then continue in for loop:
116 if not isOnBoard(x, y):
117 break
118 if not isOnBoard(x, y):
119 continue
120 if board[(x, y)] == tile:
121 # Found tiles to flip over. Go in reverse direction
122 # until we reach the original space, noting all the
123 # tiles along the way.
124 while True:
125 x -= xdirection
126 y -= ydirection
127 if x == xstart and y == ystart:
128 break
129 tilesToFlip.append([x, y])
130
131 board[(xstart, ystart)] = ' ' # Restore the original empty space.
132 # If no tiles were flipped, this is not a valid move:
133 if len(tilesToFlip) == 0:
134 return False
135 return tilesToFlip
136
137
138def isOnBoard(x, y):

Callers 3

getValidMovesFunction · 0.70
askForPlayerMoveFunction · 0.70
makeMoveFunction · 0.70

Calls 1

isOnBoardFunction · 0.70

Tested by

no test coverage detected