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

Function getPieceMovements

src/gamesbyexample/barca.py:247–315  ·  view source on GitHub ↗

Return a list of (x, y) tuples representing spaces that hold pieces that the player can move according to Barca rules.

(player, board)

Source from the content-addressed store, hash-verified

245
246
247def getPieceMovements(player, board):
248 """Return a list of (x, y) tuples representing spaces that hold
249 pieces that the player can move according to Barca rules. """
250
251 # Figure out which pieces can move (afraid ones must move first).
252 afraidPiecePositions = [] # List of (x, y) tuples of pieces.
253 unafraidPiecePositions = [] # List of (x, y) tuples of pieces.
254 for y in range(BOARD_HEIGHT):
255 for x in range(BOARD_WIDTH):
256 if board[(x, y)] in PLAYER_PIECES[player]:
257 # Check if the animal is afraid or not:
258 if getAnimalStr(board, x, y).endswith('!'):
259 afraidPiecePositions.append((x, y))
260 else:
261 unafraidPiecePositions.append((x, y))
262
263 if len(afraidPiecePositions) != 0:
264 # Unafraid pieces can't move if there are afraid pieces.
265 unafraidPiecePositions = []
266
267 # Go through all of the pieces and get their valid moves:
268
269 # The keys are (x, y) tuples, values are list of (x, y) tuples of
270 # where they can move:
271 validMoves = {}
272 for piecePosition in afraidPiecePositions + unafraidPiecePositions:
273 x, y = piecePosition
274 piece = board[(x, y)]
275 # This list will contain this piece's valid move locations:
276 validMoves[(x, y)] = []
277 # Check the cardinal directions to see where this mouse can move:
278 for offsetX, offsetY in ANIMAL_DIRECTIONS[piece]:
279 checkX, checkY = x, y # Start at the piece's location.
280 while True:
281 # The space check moves further in the current direction:
282 checkX += offsetX
283 checkY += offsetY
284 if not isOnBoard(checkX, checkY) or board[(checkX, checkY)] != EMPTY_SPACE:
285 # This space is off-board or blocked by another
286 # animal, so stop checking.
287 break
288 elif board[(checkX, checkY)] == EMPTY_SPACE:
289 validMoves[(x, y)].append((checkX, checkY))
290
291 # Remove the possible moves that would end up putting the piece into
292 # a feared position:
293 for piecePosition, possibleMoves in validMoves.items():
294 x, y = piecePosition
295 piece = board[(x, y)]
296
297 # List of (x, y) tuples where this piece doesn't want to move:
298 fearedPositions = []
299 for moveToX, moveToY in possibleMoves:
300 # Simulate what would happen if we move the piece to
301 # moveToX, moveToY:
302 movePiece(piecePosition, (moveToX, moveToY), board)
303 if getAnimalStr(board, moveToX, moveToY).endswith('!'):
304 # Moving here would make the piece afraid, so don't let

Callers 1

doPlayerMoveFunction · 0.85

Calls 3

getAnimalStrFunction · 0.85
movePieceFunction · 0.85
isOnBoardFunction · 0.70

Tested by

no test coverage detected