"""
Mini-max Tic-Tac-Toe Player
"""

import poc_ttt_gui
import poc_ttt_provided as provided

# Set timeout, as mini-max can take a long time
import codeskulptor
codeskulptor.set_timeout(150)

# SCORING VALUES - DO NOT MODIFY
SCORES = {provided.PLAYERX: 1,
          provided.DRAW: 0,
          provided.PLAYERO: -1}

def mm_move(board, player):
    """
    Make a move on the board.
    
    Returns a tuple with two elements.  The first element is the score
    of the given board and the second element is the desired move as a
    tuple, (row, col).
    """
    
    winner = board.check_win()

    #base case
    if winner != None:
    
        #check winner and return score based on SCORES dictionary
        return (SCORES[winner], (-1,-1))
        
    #recursive case
    else:
        best_score = -10
        best_move = (-1,-1)
        empty_squares = board.get_empty_squares()

        for square in empty_squares:
            board_copy = board.clone()
            board_copy.move(square[0],square[1],player)
            
            result = mm_move(board_copy, provided.switch_player(player))
            
            modified_score = result[0] * SCORES[player]

            if modified_score == 1:
                return result[0], square
            elif modified_score >= best_score:
                best_score = modified_score
                best_move = square
        return (SCORES[player] * best_score) , best_move
    

def move_wrapper(board, player, trials):
    """
    Wrapper to allow the use of the same infrastructure that was used
    for Monte Carlo Tic-Tac-Toe.
    """
    move = mm_move(board, player)
    assert move[1] != (-1, -1), "returned illegal move (-1, -1)"
    return move[1]

# Test game with the console or the GUI.
# Uncomment whichever you prefer.
# Both should be commented out when you submit for
# testing to save time.

provided.play_game(move_wrapper, 1, False)        
poc_ttt_gui.run_gui(3, provided.PLAYERO, move_wrapper, 1, False)
Status API Training Shop Blog About © 2014 GitHub, Inc. Terms Privacy Security Contact
