Ask the player to select a move. Returns a tuple with the board space label of the piece to move, followed by where to move it. If there are no valid moves, returns (None, None).
(board, player)
| 181 | |
| 182 | |
| 183 | def askForPlayerMove(board, player): |
| 184 | """Ask the player to select a move. Returns a tuple with the board |
| 185 | space label of the piece to move, followed by where to move it. |
| 186 | If there are no valid moves, returns (None, None).""" |
| 187 | assert player in ('X', 'O') |
| 188 | |
| 189 | # Get possible "source" spaces to select: |
| 190 | checkersThatCanMove = [] |
| 191 | checkersThatCanJump = [] |
| 192 | for row in range(1, 9): # Loop over all the spaces on the board. |
| 193 | for column in ALL_COLUMNS: |
| 194 | thisSpace = column + str(row) |
| 195 | checkerAtThisSpace = board.get(thisSpace, '') |
| 196 | if checkerAtThisSpace.upper() != player: |
| 197 | continue # This is empty or the other player's checker. |
| 198 | |
| 199 | # See where the checker at this space can move: |
| 200 | dstMoves, dstCaptures = getPossibleDstMoves(board, thisSpace) |
| 201 | if dstMoves != []: |
| 202 | checkersThatCanMove.append(thisSpace) |
| 203 | if dstCaptures != []: |
| 204 | checkersThatCanJump.append(thisSpace) |
| 205 | |
| 206 | if checkersThatCanMove + checkersThatCanJump == []: |
| 207 | return (None, None) # There are no valid moves. |
| 208 | |
| 209 | if checkersThatCanJump == []: |
| 210 | # There are no captures, only moves, so use the "move" list: |
| 211 | possibleSrcSelection = checkersThatCanMove |
| 212 | else: |
| 213 | # Capturing is mandatory, so use the "jump" list: |
| 214 | possibleSrcSelection = checkersThatCanJump |
| 215 | |
| 216 | while True: # Loop until a valid "source" space is selected. |
| 217 | print('Player', player, 'select the checker to move:') |
| 218 | print(' '.join(possibleSrcSelection), 'QUIT') |
| 219 | srcSpace = input('> ').upper().strip() |
| 220 | if srcSpace == 'QUIT': |
| 221 | print('Thanks for playing!') |
| 222 | sys.exit() |
| 223 | if srcSpace in possibleSrcSelection: |
| 224 | break # Exit loop when a valid space is entered. |
| 225 | |
| 226 | dstMoves, dstCaptures = getPossibleDstMoves(board, srcSpace) |
| 227 | if dstCaptures == []: |
| 228 | # There are no captures, only moves, so use the "move" list: |
| 229 | possibleDstSelection = dstMoves |
| 230 | else: |
| 231 | # Capturing is mandatory, so use the "jump" list: |
| 232 | possibleDstSelection = dstCaptures |
| 233 | while True: # Loop until a valid "destination" space is selected. |
| 234 | print('Enter the space to move', srcSpace, 'to:') |
| 235 | print(' '.join(possibleDstSelection)) |
| 236 | dstSpace = input('> ').upper().strip() |
| 237 | if dstSpace in possibleDstSelection: |
| 238 | break # Exit loop when a valid space is entered. |
| 239 | |
| 240 | return (srcSpace, dstSpace) |
no test coverage detected