from myro import * ############################################################# def makeBoard(): # A 3x3 board is represented as a list of 9 elements. # We will use the following numbering to locate a square # 0 | 1 | 2 # ---|---|--- # 3 | 4 | 5 # ---|---|--- # 6 | 7 | 8 return [' ',' ',' ',' ',' ',' ',' ',' ',' '] def display(board): for i in range(0, 9, 3): if i > 0: print '---|---|---' print " %c | %c | %c "%(board[i],board[i+1],board[i+2]) def opponent(player): if player == "X": return "O" else: return "X" from random import choice You = 'X' Me = 'O' def move(board, player): if player == You: # user's move? square = input("Enter your move: ") - 1 else: # my turn # player is the computer, make a random choice print "My move:" # square = choice(possibleMoves(board, player)) square = bestMove(board,player,possibleMoves(board,player)) # place player's piece on the chosen square applyMove(board, player, square) def possibleMoves(board, player): # return possible moves for given player moves = [] for i in range(9): if board[i] == ' ': moves.append(i) return moves def applyMove(board, player, square): board[square] = player # These square triples represent wins (three in a row). WINS = [[0, 1, 2],[3, 4, 5],[6, 7, 8], # the rows [0, 3, 6],[1, 4, 7],[2, 5, 8], # the columns [0, 4, 8],[2, 4, 6]] # diagonals def winner(board): for win in WINS: posWinner = board[win[0]] if (posWinner != ' ' and posWinner == board[win[1]] and posWinner == board[win[2]]): return posWinner # No winner yet, are there empty squares left? for i in range(9): if board[i] == ' ': return ' ' # The board is full and no one has three in a row return 'Tie' def gameOver(board): return winner(board) != ' ' def play(): # Initialize board board = makeBoard() # set who moves first/next: X always moves first player = 'X' # Display the initial board display(board) # The game loop while (not gameOver(board)): move(board, player) display(board) player = opponent(player) # game over, show outcome winningPiece = winner(board) if winningPiece != 'Tie': print winningPiece, "won." else: print "It is a tie." ######################################## INFINITY = 10 def evaluate(board): # if board is a win for player, return INFINITY piece = winner(board) if piece == Me: return INFINITY elif piece == You: return -INFINITY else: return openWins(board, Me) - openWins(board, You) def openWins(board, player): possWins = 0 for position in WINS: n = 0 for i in range(3): if ((board[position[i]] == player) or (board[position[i]] == ' ')): n += 1 if n == 3: possWins += 1 return possWins def bestMove(board, player, moves): scores = [] for move in moves: b = copy(board) applyMove(b, player, move) scores.append(evaluate(b)) return moves[scores.index(max(scores))] ##############################################