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

Function getComputerMove

src/gamesbyexample/reversegam.py:222–245  ·  view source on GitHub ↗

Given a board and the computer's tile, determine where to move and return that move as a [x, y] list.

(board)

Source from the content-addressed store, hash-verified

220
221
222def getComputerMove(board):
223 """Given a board and the computer's tile, determine where to move
224 and return that move as a [x, y] list."""
225 possibleMoves = getValidMoves(board, COMPUTER)
226
227 # Randomize the order of the possible moves so that if there are
228 # multiple best scoring moves, a random one is selected.
229 random.shuffle(possibleMoves)
230
231 # Always go for a corner if available:
232 for x, y in possibleMoves:
233 if isOnCorner(x, y):
234 return (x, y)
235
236 # Go through all possible moves and remember the best scoring move:
237 bestScore = -1
238 for x, y in possibleMoves:
239 duplicateBoard = copy.copy(board)
240 makeMove(duplicateBoard, COMPUTER, x, y)
241 score = getScoreOfBoard(duplicateBoard)[COMPUTER]
242 if score > bestScore:
243 bestMove = [x, y]
244 bestScore = score
245 return bestMove
246
247
248def isOnCorner(x, y):

Callers 1

mainFunction · 0.70

Calls 4

getValidMovesFunction · 0.70
isOnCornerFunction · 0.70
makeMoveFunction · 0.70
getScoreOfBoardFunction · 0.70

Tested by

no test coverage detected