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

Function askForPlayerMove

src/gamesbyexample/chancecheckers.py:187–231  ·  view source on GitHub ↗

Ask the player to select a move.

(board, player, moves)

Source from the content-addressed store, hash-verified

185
186
187def askForPlayerMove(board, player, moves):
188 """Ask the player to select a move."""
189
190 # Present the player with valid moves and ask them to choose one:
191 assert player in ('X', 'O')
192 print('Moves for ' + player + ': ' + ' '.join(moves))
193
194 # Get possible "source" spaces to select:
195 checkersThatCanMove = []
196 for row in range(1, 9): # Loop over all the spaces on the board.
197 for column in ALL_COLUMNS:
198 thisSpace = column + str(row)
199 checkerAtSpace = board.get(thisSpace, '')
200 cantMove = checkerAtSpace.lower() not in moves
201 isPromoted = checkerAtSpace == otherCheckers(player)[1]
202 if cantMove or isPromoted:
203 continue # This is not a checker the player can move.
204
205 # See where the checker at this space can move:
206 dstMoves, dstCaptures = getPossibleDstMoves(board, thisSpace)
207 if dstMoves != [] or dstCaptures != []:
208 checkersThatCanMove.append(thisSpace)
209
210 if checkersThatCanMove == []:
211 return (None, None) # There are no valid moves.
212
213 while True: # Loop until a valid "source" space is selected.
214 print('Player', player, 'select the checker to move:')
215 print(' '.join(checkersThatCanMove), 'QUIT')
216 srcMove = input('> ').upper().strip()
217 if srcMove == 'QUIT':
218 sys.exit()
219 if srcMove in checkersThatCanMove:
220 break
221
222 while True: # Loop until a valid "destination" space is selected.
223 dstMoves, dstCaptures = getPossibleDstMoves(board, srcMove)
224 dstMoves += dstCaptures
225 print('Enter the space to move', srcMove, 'to:')
226 print(' '.join(dstMoves))
227 dstMove = input('> ').upper().strip()
228 if dstMove in dstMoves:
229 break
230
231 return (srcMove, dstMove)
232
233
234def makeMove(board, srcMove, dstMove):

Callers 1

mainFunction · 0.70

Calls 2

otherCheckersFunction · 0.70
getPossibleDstMovesFunction · 0.70

Tested by

no test coverage detected