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

Function doPlayerMove

src/gamesbyexample/hexapawn.py:159–224  ·  view source on GitHub ↗

Ask the player for a move and carry it out on the board.

(player, board)

Source from the content-addressed store, hash-verified

157
158
159def doPlayerMove(player, board):
160 """Ask the player for a move and carry it out on the board."""
161 validMoves = getValidMoves(player, board)
162
163 print('It is player ' + player.upper() + '\'s turn.')
164 print('Select which pawn you want to move:', ' '.join(validMoves))
165 print('(Or enter QUIT to quit.)')
166 while True: # Keep looping until the player enters a valid move.
167 selectedPawn = input('> ').upper()
168
169 if selectedPawn == 'QUIT':
170 print('Thanks for playing!')
171 sys.exit()
172
173 if selectedPawn in validMoves:
174 break # The user entered a valid move, so break.
175 print('That is not a valid move.')
176
177 # Figure out which moves the selected pawn can make:
178 x = getNumberForNthLetter(selectedPawn[0])
179 y = int(selectedPawn[1]) - 1
180 possibleMoves = []
181 if pieceCanCaptureLeft(player, x, y, board):
182 possibleMoves.append('L')
183 if pieceCanAdvance(player, x, y, board):
184 possibleMoves.append('A')
185 if pieceCanCaptureRight(player, x, y, board):
186 possibleMoves.append('R')
187
188 if len(possibleMoves) != 1:
189 # There are multiple possible moves, so ask the player which
190 # move they want to make:
191 print('Enter the move this pawn will make:')
192 if 'L' in possibleMoves:
193 print('(L)eft Capture ', end='')
194 if 'A' in possibleMoves:
195 print('(A)dvance Forward ', end='')
196 if 'R' in possibleMoves:
197 print('(R)ight Capture', end='')
198 print()
199 while True: # Ask until the player until enters a valid move.
200 move = input('> ').upper()
201 if move in possibleMoves:
202 break
203 print('Enter which move this pawn will take.')
204 elif len(possibleMoves) == 1:
205 # There's only one possible move, so automatically select it.
206 move = possibleMoves[0]
207
208 # Carry out this pawn's move:
209 board[(x, y)] = EMPTY_SPACE
210 if move == 'A':
211 if player == X_PLAYER:
212 board[(x, y + 1)] = X_PLAYER
213 elif player == O_PLAYER:
214 board[(x, y - 1)] = O_PLAYER
215 elif move == 'L':
216 if player == X_PLAYER:

Callers 1

mainFunction · 0.70

Calls 5

getNumberForNthLetterFunction · 0.85
pieceCanCaptureLeftFunction · 0.85
pieceCanAdvanceFunction · 0.85
pieceCanCaptureRightFunction · 0.85
getValidMovesFunction · 0.70

Tested by

no test coverage detected