| 213 | |
| 214 | |
| 215 | def getValidMoves(board, player, flipTally): |
| 216 | validMoves = [] # Contains the spaces with tokens that can move. |
| 217 | if player == X_PLAYER: |
| 218 | opponent = O_PLAYER |
| 219 | track = X_TRACK |
| 220 | home = X_HOME |
| 221 | elif player == O_PLAYER: |
| 222 | opponent = X_PLAYER |
| 223 | track = O_TRACK |
| 224 | home = O_HOME |
| 225 | |
| 226 | # Check if the player can move a token from home: |
| 227 | if board[home] > 0 and board[track[flipTally]] == EMPTY: |
| 228 | validMoves.append('home') |
| 229 | |
| 230 | # Check which spaces have a token the player can move: |
| 231 | for trackSpaceIndex, space in enumerate(track): |
| 232 | if space == 'H' or space == 'G' or board[space] != player: |
| 233 | continue |
| 234 | nextTrackSpaceIndex = trackSpaceIndex + flipTally |
| 235 | if nextTrackSpaceIndex >= len(track): |
| 236 | # You must flip an exact number of moves onto the goal, |
| 237 | # otherwise you can't move on the goal. |
| 238 | continue |
| 239 | else: |
| 240 | nextBoardSpaceKey = track[nextTrackSpaceIndex] |
| 241 | if nextBoardSpaceKey == 'G': |
| 242 | # This token can move off the board: |
| 243 | validMoves.append(space) |
| 244 | continue |
| 245 | if board[nextBoardSpaceKey] in (EMPTY, opponent): |
| 246 | # If the next space is the protected middle space, you |
| 247 | # can only move there if it is empty: |
| 248 | if nextBoardSpaceKey == 'l' and board['l'] == opponent: |
| 249 | continue # Skip this move, the space is protected. |
| 250 | validMoves.append(space) |
| 251 | |
| 252 | return validMoves |
| 253 | |
| 254 | |
| 255 | if __name__ == '__main__': |