Exemple #1
0
def go():

    GUI = GuiComm()
    receivedPacket = GUI.receive_gui_mode()
    GUI.send_gui_packet()
    mode = receivedPacket[0]
    Human = receivedPacket[5]
    PreviousHumanMove = [-2, -2]
    PreviousAIMove = [-2, -2]
    SuggestedAIMove = [-1, -1]

    if mode == 1:  # AI vs Human
        Time = [900000, 900000]

        initial_locations = input(
            "Is there an initial move log Json file: (1 = yes, 0 = no)? ")
        if int(initial_locations) == 1:
            file_name = input("Enter the JSON file name: ")
            game = server_config(None, FileName=file_name, GuiObject=GUI)
        else:
            game = Game(GuiObject=GUI, mode=0)

        game.setOurTurn(Human)
        game_end = False
        turn = game.turn
        while not game_end:
            valid = False
            if turn == Human:
                # Receive from GUI a packet
                a = datetime.datetime.now()
                receivedPacket = GUI.receive_gui_mode()
                GUI.send_gui_packet()
                b = datetime.datetime.now()
                c = b - a
                Time[turn] = Time[turn] - int(c.total_seconds() * 1000)
                valid, game_end = game.play(receivedPacket, turn, Time=Time)
                game.Drawboard()
                while not valid:
                    # send a packet back to GUI
                    dummy = GUI.receive_gui()
                    GUI.send_gui_packet(moveValidation=False)
                    # receive another one
                    a = datetime.datetime.now()
                    receivedPacket = GUI.receive_gui_mode()
                    GUI.send_gui_packet()
                    b = datetime.datetime.now()
                    c = b - a
                    Time[turn] = Time[turn] - int(c.total_seconds() * 1000)
                    valid, game_end = game.play(receivedPacket,
                                                turn,
                                                Time=Time)
                PreviousHumanMove = receivedPacket[1:3]
                # a = datetime.datetime.now()
                AI_move = game.getMove(turn=Human, previousMove=PreviousAIMove)
                # b = datetime.datetime.now()
                # c = b - a
                tempGame = copy.deepcopy(game.game)
                valid = tempGame.AddStone(AI_move, turn)
                while not valid:
                    # a = datetime.datetime.now()
                    AI_move = game.getMove(turn=Human,
                                           previousMove=PreviousAIMove)
                    # b = datetime.datetime.now()
                    # c = c + (b - a)
                    valid = tempGame.AddStone(AI_move, turn)
                SuggestedAIMove = AI_move
                AI_score = tempGame.getScoreAndTerrBoard()[0]

                score = game.game.getScoreAndTerrBoard()[0]
                if SuggestedAIMove == 0 or SuggestedAIMove == 1:
                    SuggestedAIMove = [-1, -1]

                # print("Human Score Diff :", score[Human] - score[1 - Human])
                # print("AI Score Diff :", AI_score[Human] - AI_score[1 - Human])
                if score[Human] - score[
                        1 - Human] >= AI_score[Human] - AI_score[1 - Human]:
                    dummy = GUI.receive_gui()
                    GUI.send_gui_packet(theBetterMove=1,
                                        betterMoveCoord=SuggestedAIMove)
                else:
                    dummy = GUI.receive_gui()
                    GUI.send_gui_packet(theBetterMove=-1,
                                        betterMoveCoord=SuggestedAIMove)

            else:
                a = datetime.datetime.now()
                AI_move = game.getMove(turn=1 - Human,
                                       previousMove=PreviousHumanMove)
                b = datetime.datetime.now()
                c = (b - a)
                Time[turn] = Time[turn] - int(c.total_seconds() * 1000)
                valid, game_end = game.play(AI_move,
                                            turn,
                                            mode=True,
                                            Time=Time)
                while not valid:
                    a = datetime.datetime.now()
                    AI_move = game.getMove(turn=1 - Human,
                                           previousMove=PreviousHumanMove)
                    b = datetime.datetime.now()
                    c = b - a
                    Time[turn] = Time[turn] - int(c.total_seconds() * 1000)
                    valid, game_end = game.play(AI_move,
                                                turn,
                                                mode=True,
                                                Time=Time)
                PreviousAIMove = AI_move

            turn = 1 - turn  # White turn = 0 , Black Turn = 0

    else:
        # os.system('python CommunicationSamadoni.py BS ws://127.0.0.1:8080')
        name = None
        url = None

        x = input(
            "Would you like to enter client name: (1 = yes, 0 = no) (default = GG)? "
        )
        if int(x) == 1:
            name = input("Please enter the client name: ")

        y = input(
            "Would you like to enter client url: (1 = yes, 0 = no) (default = ws://localhost:8080)? "
        )
        if int(y) == 1:
            url = input("Please enter the client url: ")

        loop = asyncio.get_event_loop()
        asyncio.ensure_future(main2(GUI, name, url))
        loop.run_forever()

    return True
def server_config(GameConfig, FileName=None, mode=1, GuiObject=None):
    if (FileName is None):
        GameConfig = GameConfig
    else:
        with open(FileName, 'r') as f:
            GameConfig = json.load(f)
    #print("1")
    #print(GameConfig)
    # TODO DO we need reamining time of anything at the initalization state(begining of the game from a certain stage)
    GameState = GameConfig["initialState"]
    moveLogJsonArr = GameConfig["moveLog"]

    wloc = list(zip(*np.where((np.array(GameState["board"])) == "W")))
    bloc = list(zip(*np.where((np.array(GameState["board"])) == "B")))
    bCaptured = GameState["players"]["W"]["prisoners"]
    wCaptured = GameState["players"]["B"]["prisoners"]

    gameArgs = {
        "wloc": wloc,
        "bloc": bloc,
        "wCapturedStones": wCaptured,
        "bCapturedStones": bCaptured
    }

    # TODO  Check for any misplaced argument and if initialization of any argument can affect other class members
    """
    instance of backend game supposed to be only one instance
    """
    if mode == 1:
        backEndGame = Game(**gameArgs)
    else:
        backEndGame = Game(**gameArgs, GuiObject=GuiObject, mode=mode)

    turn = Turn.black if GameState["turn"] == "B" else Turn.white
    #print("1.1")
    #print(turn)
    """
    logically speaking Yahia should not send resign move at the beginning
    """
    """
        Taking the move log and adding stones till we reach final state to begin with
    """
    for move in moveLogJsonArr:

        if move["move"]["type"] == "place":
            print("location", (move["move"]["point"]["row"],
                               move["move"]["point"]["column"]), turn)
            x = backEndGame.play((move["move"]["point"]["row"],
                                  move["move"]["point"]["column"], turn))
            # gameBoard = backEndGame.getBoard()
            # print(gameBoard)
            if (not x):
                print("Error in location", (move["move"]["point"]["row"],
                                            move["move"]["point"]["column"]),
                      turn)
                backEndGame.Drawboard()
                # input('Press any key ...')
        elif (move["move"]["type"] == "pass"):
            backEndGame.play(1, turn)
        elif (move["move"]["type"] == "resign"):
            # TODO handle resign at game config(illogical)
            print("Error in parsing JSON FILE AT GAME INIT CONFIG")
        else:
            # TODO handle error at game config
            pass
            print("Error in parsing JSON FILE AT GAME INIT CONFIG")
        turn = 1 - turn
        # backEndGame.Drawboard()
        # input('Press any key ...')

    # score, TerrBoard = backEndGame.getScoreAndTerrBoard()
    # print(score)
    """"
    NOW instance backEnd stage is initialized with the data parsed
    """
    #print("2")
    return backEndGame