コード例 #1
0
def play(playerInfo, currentSocket):
    state = tictactoe.getNewPlayer(playerInfo["player"])

    if playerInfo["player"] == "O":
        print("Waiting on opponent's move...")
        receiveMessage = currentSocket.recv(1024).decode("utf-8")
        state = json.loads(receiveMessage)
        state["player"] = playerInfo["player"]

    while not tictactoe.isGameOver(state):
        print(tictactoe.printBoard(state))
        state = tictactoe.userTurn(state)
        state["player"] = playerInfo["player"]
        print(tictactoe.printBoard(state))

        sendMessage = json.dumps(state).encode("utf-8")
        currentSocket.send(sendMessage)

        if not tictactoe.isGameOver(state):
            receiveMessage = currentSocket.recv(1024).decode("utf-8")
            state = json.loads(receiveMessage)
            state["player"] = playerInfo["player"]
        if tictactoe.isGameOver(state):
            print(tictactoe.printBoard(state))

    print(tictactoe.isGameOver(state))
    print("Client closed")
    currentSocket.close()
コード例 #2
0
def minimaxGenBoardScores(inBoard, myPlayer, inPlayer):
    stack = []
    boardScores = {}

    stack.append({'board': inBoard, 'player': inPlayer})

    while len(stack) > 0:
        args = stack[-1]
        board = args['board']
        player = args['player']

        maximizing = False
        if player == myPlayer:
            maximizing = True

        #   base case, end board
        winner = tt.getWinner(board)
        if winner:
            boardScores[tt.hash(board)] = tt.scoreEndBoard(
                board, winner, myPlayer)
            print("###########")
            tt.printBoard(board)
            print(boardScores[tt.hash(board)])

            stack.pop()
        elif tt.noMoreMoves(board):
            boardScores[tt.hash(board)] = tt.scoreEndBoard(
                board, winner, myPlayer)
            stack.pop()

        else:  #   nobody won yet, and there are move moves
            nextBoards = tt.listNextBoards(board, player)
            allPresent = True
            for nextBoard in nextBoards:
                if not (tt.hash(nextBoard) in boardScores):
                    allPresent = False
                    newArgs = {
                        'board': nextBoard,
                        'player': tt.togglePlayer(player),
                    }
                    stack.append(newArgs)
            if allPresent:
                scores = [
                    boardScores[tt.hash(nextBoard)] for board in nextBoards
                ]
                if maximizing:
                    boardScores[tt.hash(board)] = max(scores)
                else:
                    boardScores[tt.hash(board)] = min(scores)
                stack.pop()

    return boardScores
コード例 #3
0
def playGame():
    board = tt.genBoard()
    movesLeft = True
    winner = False
    player = 2
    computersPlayer = 2  #random.randint(1,2)
    turn = 0

    print("NEW GAME")
    if computersPlayer == 2:
        print("COMPUTER GOES FIRST...")
    while (movesLeft and not winner):
        if player == 2:
            print("X's Turn")
        else:  # player == 1
            print("O's Turn")
        tt.printBoard(board)

        if player == computersPlayer:
            board = pickBestNextBoard(board, player, computersPlayer)
            player = tt.togglePlayer(player)
        elif player == tt.togglePlayer(computersPlayer):
            validMove = False
            while validMove == False:
                move = input("input move of form 'y x' ")
                y = int(move[0])
                x = int(move[2])
                #   validate move
                if board[y][x] is not 0:
                    print("!!!INVALID MOVE!!!")
                    continue
                else:
                    validMove = True
                board[y][x] = tt.togglePlayer(computersPlayer)
                player = tt.togglePlayer(player)
        turn += 1

        winner = tt.getWinner(board)
        movesLeft = not tt.noMoreMoves(board)

    tt.printBoard(board)

    if winner:
        if winner == 2:
            print("WINNER: X")
        else:  # winner == 1
            print("WINNER: O")
    else:
        print("TIE")
コード例 #4
0
def computerVsHuman():
    # Initialize the game.
    board = [[" ", " " ," "], [" ", " " ," "], [" ", " " ," "]]
    turns = 0
    ttt.printBoard(board)
    # Let the computer and user alternate turns.
    while turns < 5 and not ttt.hasWon(board, "X") and not ttt.hasWon(board, "O"):
        s,m = ttt.move(board, "O",True)
        board[m[0]][m[1]] = "O"
        print
        ttt.printBoard(board)
        turns = turns + 1
        if turns < 5 and not ttt.hasWon(board, "X") and not ttt.hasWon(board, "O"):
            m = userMove(board)
            board[m[0]][m[1]] = "X"
            print
            ttt.printBoard(board)
    # Finish the game.
    if ttt.hasWon(board, "O"):
        print "O wins."
    elif ttt.hasWon(board, "X"):
        print "X wins."
    else:
        print "Draw."
コード例 #5
0
def playGame():
    saveQTables = False
    fileName = 'qTables.pickle'

    qTables = {}

    keysSoFar = []
    movesSoFar = []
    tryHard = 0
    alpha = 0.9
    numTrials = 1000000

    if saveQTables:
        train(qTables, numTrials, alpha, tryHard)
        f = open(fileName, 'wb')
        pickle.dump(qTables, f, pickle.HIGHEST_PROTOCOL)
        f.close()
    else:
        f = open(fileName, 'rb')
        qTables = pickle.load(f)
        f.close()

    numWins, numLosses, numTies = test(qTables, 1000)
    print("VS RANDOM OPPONENT...")
    print("numWins:" + str(numWins))
    print("numLosses:" + str(numLosses))
    print("numTies:" + str(numTies))
    quit()

    board = tt.genBoard()
    movesLeft = True
    winner = False
    player = 2
    computersPlayer = random.randint(1, 2)

    print("NEW GAME")
    if computersPlayer == 2:
        print("COMPUTER GOES FIRST...")
    while (movesLeft and not winner):
        if player == 2:
            print("X's Turn")
        else:  # player == 1
            print("O's Turn")
        tt.printBoard(board)

        if player == computersPlayer:
            bestMove = pickBestNextMove(qTables,
                                        keysSoFar,
                                        board,
                                        player,
                                        computersPlayer,
                                        tryHard=1.0,
                                        verbose=True)
            movesSoFar.append(bestMove)
            tt.applyMove(player, bestMove, board)
            player = tt.togglePlayer(player)
        elif player == tt.togglePlayer(computersPlayer):
            validMove = False
            while validMove == False:
                move = input("input move of form 'y x' ")
                y = int(move[0])
                x = int(move[2])
                #   validate move
                if board[y][x] is not 0:
                    print("!!!INVALID MOVE!!!")
                    continue
                else:
                    validMove = True
                board[y][x] = tt.togglePlayer(computersPlayer)
                player = tt.togglePlayer(player)

        winner = tt.getWinner(board)
        movesLeft = not tt.noMoreMoves(board)

    tt.printBoard(board)

    score = scoreEndBoard(board, winner, computersPlayer)
    updateQTable(score, qTables, keysSoFar, movesSoFar, alpha)
    for key in keysSoFar:
        pprint(key)
        pprint(qTables[key])

    if winner:
        if winner == 2:
            print("WINNER: X")
        else:  # winner == 1
            print("WINNER: O")
    else:
        print("TIE")
コード例 #6
0
from tictactoe import printBoard
from fatorial import fatorial

theBoard = {
    'top-L': ' ',
    'top-M': ' ',
    'top-R': ' ',
    'mid-L': ' ',
    'mid-M': ' ',
    'mid-R': ' ',
    'low-L': ' ',
    'low-M': ' ',
    'low-R': ' '
}

printBoard(theBoard)

theBoard[0, 0] = 'x'

printBoard(theBoard)

print(fatorial(5))
コード例 #7
0
def playGame():
    mct = {}
    board = tt.genBoard()
    player = 2
    computersPlayer = 2
    numSimsPreGame = 100000
    numSimsOnline = 100

    saveMCTree = False
    fileName = 'mct.pickle'

    if saveMCTree:
        simulateChildren(mct,
                         board,
                         player,
                         computersPlayer,
                         numSimsPreGame,
                         verbose=True)
        f = open(fileName, 'wb')
        pickle.dump(mct, f, pickle.HIGHEST_PROTOCOL)
        f.close()
        quit()
    else:
        f = open(fileName, 'rb')
        mct = pickle.load(f)
        f.close()

    # mct = {}
    # numTrials = 100
    # numWins, numLosses, numTies = test(mct, numTrials, numSimsOnline)
    # print("VS RANDOM OPPONENT...")
    # print("numWins:"  + str(numWins))
    # print("numLosses:"  + str(numLosses))
    # print("numTies:"  + str(numTies))
    # quit()

    #   w 0.6, t 0.11, l 0.3

    board = tt.genBoard()
    movesLeft = True
    winner = False
    player = 2
    computersPlayer = random.randint(1, 2)

    print("NEW GAME")
    if computersPlayer == 2:
        print("COMPUTER GOES FIRST...")
    while (movesLeft and not winner):
        if player == 2:
            print("X's Turn")
        else:  # player == 1
            print("O's Turn")
        tt.printBoard(board)

        if player == computersPlayer:
            simulateChildren(mct,
                             board,
                             player,
                             computersPlayer,
                             numSimsOnline,
                             verbose=True)
            bestBoard = pickBestNextMove(mct, board, player)
            board = bestBoard
        elif player == tt.togglePlayer(computersPlayer):
            validMove = False
            while validMove == False:
                move = input("input move of form 'y x' ")
                y = int(move[0])
                x = int(move[2])
                #   validate move
                if board[y][x] is not 0:
                    print("!!!INVALID MOVE!!!")
                    continue
                else:
                    validMove = True
                board[y][x] = tt.togglePlayer(computersPlayer)
        player = tt.togglePlayer(player)

        winner = tt.getWinner(board)
        movesLeft = not tt.noMoreMoves(board)

    tt.printBoard(board)

    score = scoreEndBoard(board, winner, computersPlayer)

    if winner:
        if winner == 2:
            print("WINNER: X")
        else:  # winner == 1
            print("WINNER: O")
    else:
        print("TIE")
コード例 #8
0
        winner = False
        player = 2
        computersPlayer = random.randint(1,2)

        playerOneTrainingSessions = []
        playerTwoTrainingSessions = []

        if verbose and i % logInterval == 0:
            print("NEW GAME")
        while(movesLeft and not winner):
            if verbose and i % logInterval == 0:
                if player == 2:
                    print("X's Turn")
                else: # player == 1
                    print("O's Turn")
                tt.printBoard(board)

            nextMoves = tt.listNextBoards(board, player)
            if makeRandomMoves:
                randomMove = random.randint(0, len(nextMoves)-1)
                randomMove = nextMoves[randomMove]
                oneHot = oneHotTicTacToe(randomMove, tt.togglePlayer(player), computersPlayer)
                trainingSession = forward(network, oneHot, dropout=True)
                bestMove = randomMove
            else:
                bestMoveDict = pickBestMove(nextMoves, player, computersPlayer)
                bestMove = bestMoveDict['move']
                score = bestMoveDict['score']
                trainingSession = bestMoveDict['trainingSession']

            if player == 1:
コード例 #9
0
def playWithUser(net, online=True):
    while(True):
        board = genBoard()
        movesLeft = True
        winner = False
        player = 2
        computersPlayer = 2 #random.randint(1,2)

        print()
        print("NEW GAME")
        if computersPlayer == 2:
            print("COMPUTER GOES FIRST...")

        moves = []
        outputs = []
        while(movesLeft and not winner):
            if player == 2:
                print("X's Turn")
            else: # player == 1
                print("O's Turn")
            tt.printBoard(board)

            if player == computersPlayer:
                move = None
                moveValid = False
                while not moveValid:
                    #   generate a move
                    oneHot = oneHotTicTacToe(board, computersPlayer).view(1, 1, 18)
                    output = net(oneHot)
                    values, index = output.view(9).max(0)
                    if board.flatten()[index] == 0: #   if move is valid
                        moveValid = True

                        #   apply the move
                        move = index
                        board = board.flatten()
                        board[move] = computersPlayer
                        board = board.reshape(3, 3)
                        
                        #   store for later
                        moves.append(move)
                        outputs.append(output)
                    else:   #   invalid move, prime the whip
                        print("invalid move")
                        optimizer.zero_grad()
                        validMoves = np.where(board == 0, 1, 0)
                        target = torch.tensor(validMoves, dtype=torch.float).view(1, 1, 9)
                        loss = criterion(output, target)
                        loss.backward()
                        optimizer.step()
            elif player == tt.togglePlayer(computersPlayer):
                validMove = False
                while validMove == False:
                    move = input("input move of form 'y x' ")
                    y = int(move[0])
                    x = int(move[2])
                    #   validate move
                    if not board[y][x] == 0:
                        print("!!!INVALID MOVE!!!")
                        continue
                    else:
                        validMove = True
                    board[y][x] = tt.togglePlayer(computersPlayer)
            player = tt.togglePlayer(player)
            
            winner = tt.getWinner(board)
            movesLeft = not tt.noMoreMoves(board)

        tt.printBoard(board)

        if online:
            score = scoreEndBoard(board, winner, computersPlayer)
            for i, move in enumerate(moves):
                output = outputs[i]
                target = output.clone().view(9)
                target[move] = score
                target = target.view(1, 1, 9)

                optimizer.zero_grad()
                loss = criterion(output, target)
                loss.backward()
                optimizer.step()

        if winner:
            if winner == 2:
                print("WINNER: X")
            else: # winner == 1
                print("WINNER: O")
        else:
            print("TIE")