示例#1
0
def main():
    """main function which handles loading up the AI each turn and communicating with the game server"""
    #allow optional command line argument to overwrite AIMode (allows for local testing without risk of forgetting to change AIMode back)
    if (len(sys.argv) > 1):
        #use exec here so that python does not have a problem with falling back to the AIMode declaration above
        exec("AIMode = sys.argv[1]", locals(), globals())

    print("Starting AI: '" + AIMode + "' from " +
          ("command line argument."
           if len(sys.argv) > 1 else "main file declaration."))

    gameMode = util.selectGameMode()
    #special mode: generate a single move by reading gameState from JSON file
    if (gameMode == "0"):
        if (
                not os.path.isfile("gameState.txt")
        ):  #verify that the gameState file actually exists before trying to open it
            raise Exception(
                "Error: game state file 'gameState.txt' does not exist.")
        with open('gameState.txt'
                  ) as infile:  #load game state from gameState.txt
            jsonData = json.load(infile)
        util.startGame(
            jsonData
        )  #don't bother to store gameID or playerID here, as we are just running locally in mode 0, so we don't need these networking constants
        board = util.populateBoard(jsonData)
        util.printBoard(board)
        moveChoice = eval(AIMode + ".chooseMove(board,jsonData)")
        print("move choice:", moveChoice)
        print("json data:", jsonData)
        return

    jsonData = requests.post(qualifierURL if gameMode == "1" else rankedURL,
                             data={
                                 'devkey': devkey,
                                 'username': username
                             }).json()  # search for new game
    # when request comes back, that means you've found a match! (validation if server goes down?)
    gameID, playerID = util.startGame(jsonData)
    while jsonData['state'] != 'complete':
        if (
                debugMode
        ):  #when debug mode is enabled, we output the current game state to gameState.txt each turn
            with open('gameState.txt', 'w') as outfile:
                json.dump(jsonData, outfile)
        board = util.populateBoard(jsonData)
        util.printBoard(board)
        moveChoice = eval(AIMode + ".chooseMove(board,jsonData)")
        print("move choice:", moveChoice)
        jsonData = requests.post('http://aicomp.io/api/games/submit/' + gameID,
                                 data={
                                     'playerID': playerID,
                                     'move': moveChoice,
                                     'devkey': devkey
                                 }).json()  # submit sample move
        print("json data:", jsonData)
def playerVersusMinimax(save):
    print("Tic Tac Toe")
    print("Players: 1")

    board = 0
    boards = []
    win = UNFINISHED
    while (win == UNFINISHED):
        valid = False
        while not valid:
            print()
            printBoard(board)
            print()
            print("Column:")
            col = input()
            print("Row:")
            row = input()

            if len(col) == 0 or len(row) == 0:
                break

            board, valid = move(board, int(col), int(row), X)
            if not valid:
                print("That space is taken")

        _, bestMove, _ = minimax(board, 0, 2, findEmptySpaces(board), False)

        boards.append(str(board) + "\n")

        board, valid = move(board, bestMove[0], bestMove[1], O)

        boards.append(str(board) + "\n")

        win = checkForWin(board)

    if save:
        writeGame(boards)

    print()
    printBoard(board)
    print()

    print("**************")
    print(win + " wins!")
    print("**************")
示例#3
0
def main():
    fileName = input('Enter file name : ')
    # Used variables
    pawnAmountBW = {'WHITE': 0, 'BLACK': 0}  # number of pawns for each side
    dataSplitted = []
    readFile(fileName, dataSplitted)  # parse user's input into array

    # Algorithms option
    print("Choose Algorithm By Input The Number :")
    print("1. Hill Climbing")
    print("2. Simulated Annealing")
    print("3. Genetic Algorithm")
    chosenAlgo = int(input("Choose : "))
    while (chosenAlgo > 3 or chosenAlgo < 1):
        print("Choose The Correct Number Please...")
        chosenAlgo = int(input("Choose : "))

    # Execute the chosen algorithm
    if (chosenAlgo == 1):
        state = parseState(dataSplitted,
                           pawnAmountBW)  # generate an initial state
        result = hillClimbing(state, pawnAmountBW)
    elif (chosenAlgo == 2):
        temperature = int(input('Temperature: '))
        decreaseRate = int(input('Decrease Rate: '))
        iteration = int(input('Maximum Iteration: '))
        state = parseState(dataSplitted,
                           pawnAmountBW)  # generate an initial state
        result = simulatedAnnealing(state, pawnAmountBW, temperature,
                                    decreaseRate, iteration)
    elif (chosenAlgo == 3):
        populationAmount = int(input('Number Of Population: '))
        limit = int(input('Maximum generation: '))
        listOfStates = createListOfStates(dataSplitted, pawnAmountBW,
                                          populationAmount)
        result = geneticAlgorithm(listOfStates, pawnAmountBW, populationAmount,
                                  limit)

    # Print the result
    attackNum = countAtack(
        result)  # Get the number of attack from the result state
    printBoard(result)
    print(attackNum['friend'], end='')
    print(' ', end='')
    print(attackNum['enemy'])
def playerVersusRandom(save):
    print("Tic Tac Toe")
    print("Players: 1")

    board = 0
    boards = []
    win = UNFINISHED
    while (win == UNFINISHED):
        valid = False
        while not valid:
            print()
            printBoard(board)
            print()
            print("Column:")
            col = input()
            print("Row:")
            row = input()

            if len(col) == 0 or len(row) == 0:
                break

            board, valid = move(board, int(col), int(row), X)
            if not valid:
                print("That space is taken")

        boards.append(str(board) + "\n")

        board = randomMove(board, O)

        boards.append(str(board) + "\n")

        win = checkForWin(board)

    if save:
        writeGame(boards)

    print()
    printBoard(board)
    print()

    print("**************")
    print(win + " wins!")
    print("**************")
def computerVsComputer(gameTypes, save):
    print("Tic Tac Toe")
    print("{} versus {}".format(selectDescription[gameTypes[0]],
                                selectDescription[gameTypes[1]]))
    print("Players: 0")

    board = 0
    boards = []
    win = UNFINISHED
    currentTurn = (X, True, gameTypes[0])
    nextTurn = (O, False, gameTypes[1])
    boards.append(str(board) + "\n")
    while (win == UNFINISHED):
        startTime = time()
        bestMove, statistic = selectAlgorithm[currentTurn[2]](board,
                                                              currentTurn[1])
        duration = time() - startTime
        board, _ = move(board, bestMove[0], bestMove[1], currentTurn[0])

        boards.append(str(board) + "\n")

        print()
        printBoard(board)
        if statistic != str():
            print(statistic)
        print("Time: {} seconds".format(round(duration, 4)))
        print()

        win = checkForWin(board)
        currentTurn, nextTurn = nextTurn, currentTurn

    if save:
        writeGame(boards)

    print()
    print("**************")
    print(win + " wins!")
    print("**************")
示例#6
0
文件: pawn.py 项目: srivatsa11/Chess
    def __init__(self):
        super().__init__((-1, -1), -1, [])

    def calculateValidMoves(self):
        x, y = self.position
        self.validMoves = []
        if x == 1 and self.color == utilities.pieceColor.WHITE:
            self.validMoves.append((x + 1, y))
            self.validMoves.append((x + 2, y))
        elif self.color == utilities.pieceColor.WHITE and x < 7:
            print("reached cond 2")
            self.validMoves.append((x + 1, y))
        elif x == 6 and self.color == utilities.pieceColor.BLACK:
            self.validMoves.append((x - 1), y)
            self.validMoves.append((x - 2), y)
        elif self.color == utilities.pieceColor.BLACK and x > 0:
            self.validMoves.append((x - 1, y))


if __name__ == "__main__":
    cp = Pawn()
    cp.setInitialPosition((3, 4))
    cp.setColor(utilities.pieceColor.BLACK)
    cp.calculateValidMoves()
    utilities.printBoard(cp.validMoves)
    input("Press enter to try the other side")
    cp.setColor(utilities.pieceColor.WHITE)
    cp.calculateValidMoves()
    utilities.printBoard(cp.validMoves)