예제 #1
0
class OthelloGame:
    def __init__(self, net, ai_side, Tau=0, mcts_times=100):
        self.ai_player = AiPlayer(net, ai_side, Tau, mcts_times)
        self.game = Othello()
        self.ai_side = ai_side

    def playgame(self):
        side = -1
        while not self.game.isover():
            self.game.show(side)
            print('score: ', self.game.getScore())
            if len(self.game.getchoices(side)) != 0:
                if (side == self.ai_side):
                    self.ai_player.get_move(self.game)
                else:
                    while True:
                        try:
                            x, y = input("please input the place").split()
                            print(x, y)
                            x, y = int(x), int(y)
                            if (x, y) in self.game.getchoices(side):
                                self.game.play(x, y, side)
                                break
                        except Exception as e:
                            print("error!", e)
            else:
                print("No where to put")
            side = -side
        print(self.game.getScore())
def _find_moves(game:Othello) -> list:
    """
    This function finds all available moves on the board for the AI and returns the result as a list of tuples.
    :rtype : list
    :param game: Othello
    """
    result = []
    for row in range(game.rows()):
        for column in range(game.columns()):
            if game.cell(row + 1, column + 1) == EMPTY:
                if othello_game_logic._check_move(row + 1, column + 1, game._game_state):
                    result.append((row + 1, column + 1))
    return result
예제 #3
0
def _find_moves(game: Othello) -> list:
    """
    This function finds all available moves on the board for the AI and returns the result as a list of tuples.
    :rtype : list
    :param game: Othello
    """
    result = []
    for row in range(game.rows()):
        for column in range(game.columns()):
            if game.cell(row + 1, column + 1) == EMPTY:
                if othello_game_logic._check_move(row + 1, column + 1,
                                                  game._game_state):
                    result.append((row + 1, column + 1))
    return result
예제 #4
0
def AI_move(event):
    #     if flag_start == 0: return
    color = int(R.color)
    if color == playermap[Pcolor.get()]: return
    if R.get_all_possible_moves() == []:
        R.chg_color()
        if R.get_all_possible_moves() == []:
            end_game()
            return
        Vtips.set('黑.白'[-R.color + 1] + '方无棋可下,' + '黑.白'[R.color + 1] + '继续')
        turn(Vcolor)
        return
    global img, iterI
    j = choose_iter(iterI)
    iterI += 100
    move = Othello.UCT(rootstate=R, itermax=j)
    reversible = R.do_move(move)
    chg_img(color, img, move, reversible)
    turn(Vcolor)
    tmp_R = R.Clone()
    if tmp_R.get_all_possible_moves() == []:
        tmp_R.chg_color()
        if tmp_R.get_all_possible_moves() == []:
            end_game()
            return
        Vtips.set('黑.白'[R.color + 1] + '方无棋可下,' + '黑.白'[-R.color + 1] + '继续')
        R.chg_color()
        AI_move(0)
        turn(Vcolor)
예제 #5
0
 def clicked(self, event):
     '''if the click valid then make the move and flip the discs'''
     x = event.x
     y = event.y
     width, height, row_height, col_width = self._get_width_and_height()
     pos_list = self._board.possible_move(self._board.turn)
     for position in pos_list:
         tlx = position[1] * col_width
         tly = position[0] * row_height
         brx = tlx + col_width
         bry = tly + row_height
         if x >= tlx and x <= brx and y >= tly and y <= bry:
             try:
                 self._board.make_a_move(position[0], position[1])
                 self._draw_board()
                 break
             except Othello.InvalidMoveError:
                 pass
             except Othello.InvalidOthelloInputError:
                 pass
             except Othello.OthelloGameOverError:
                 self._game_over()
     if self._board.possible_move(
             self._board.turn) == [] and self._board.possible_move(
                 Othello.opposite_turn(self._board.turn)):
         self._game_over
예제 #6
0
def _score_board(game: Othello) -> None:
    """
    This function prints out the score board with the current player.
    :rtype : None
    :param game: Othello
    """
    blackscore = 'Black:  ' + str(game.black_score())
    whitescore = "White:  " + str(game.white_score())
    print()
    print(''.center(50, '-'))
    print('|' + blackscore.center(24, ' ') + whitescore.center(24, ' ') + '|')
    if game.current_player() == Othello.BLACK:
        print('|' + "Black's turn".center(48, ' ') + '|')
    else:
        print('|' + "White's turn".center(48, ' ') + '|')
    print(''.center(50, '-'))
예제 #7
0
 def random_policy(self, state, flag):
     st = Env.judge(state, flag)
     l = len(st)
     if l == 0:
         return [0, 0]
     else:
         p = random.randint(0, l - 1)
         return [flag, st[p]]
예제 #8
0
def finJeu(couleurJoueur1, couleurJoueur2, plateau, N, experimentation):
    compteurScore = getScore(plateau, couleurJoueur1, couleurJoueur2, N)
    joueur1Gagne = True if compteurScore[0] > compteurScore[1] else False
    if not experimentation:
        print("Le joueur 1 a un score de %s" % compteurScore[0])
        print("Le joueur 2 a un score de  %s" % compteurScore[1])
        print("%s a gagné!" % ("Joueur 1" if joueur1Gagne else "Joueur 2"))
        recommencer = input(
            "Voulez-vous recommencer une partie (o pour oui, n pour non): ")
        if recommencer == 'o':
            Othello.othello(8, False, None, None)
        else:
            sys.exit(0)
    if joueur1Gagne:
        return couleurJoueur1
    else:
        return couleurJoueur2
def _determine_move(game:Othello, moves:list) -> tuple:
    """
    This function will simulate the opponent's move and return the move with the best result.
    :rtype : tuple
    :param game: Othello
    :param moves: list
    """
    computer_ai = game.current_player()
    result = moves[0]
    win_most = game._game_state.win_with_most
    if win_most:
        best_score = 0
    else:
        best_score = 256
    for move in moves:
        score = 0
        test = copy.deepcopy(game)
        test.move(move[0],move[1])
        if computer_ai == Othello.BLACK:
            score += test.black_score()
        else:
            score += test.white_score()
        if test.current_player() != computer_ai:
            opponent_moves = _find_moves(test)
            for opponent_move in opponent_moves:
                test2 = copy.deepcopy(test)
                test2.move(opponent_move[0], opponent_move[1])
                if win_most:
                    if computer_ai == Othello.BLACK:
                        if score + test.black_score() > best_score:
                            best_score = score + test.black_score()
                            result = move
                        elif score + test.black_score() == best_score:
                            choice = [result, move]
                            result = choice[random.randrange(len(choice))]
                    else:
                        if score + test.white_score() > best_score:
                            best_score = score + test.white_score()
                            result = move
                        elif score + test.white_score() == best_score:
                            choice = [result, move]
                            result = choice[random.randrange(len(choice))]
                else:
                    if computer_ai == Othello.BLACK:
                        if score + test.black_score() < best_score:
                            best_score = score + test.black_score()
                            result = move
                        elif score + test.black_score() == best_score:
                            choice = [result, move]
                            result = choice[random.randrange(len(choice))]
                    else:
                        if score + test.white_score() < best_score:
                            best_score = score + test.white_score()
                            result = move
                        elif score + test.white_score() == best_score:
                            choice = [result, move]
                            result = choice[random.randrange(len(choice))]
    return result
예제 #10
0
def _determine_move(game: Othello, moves: list) -> tuple:
    """
    This function will simulate the opponent's move and return the move with the best result.
    :rtype : tuple
    :param game: Othello
    :param moves: list
    """
    computer_ai = game.current_player()
    result = moves[0]
    win_most = game._game_state.win_with_most
    if win_most:
        best_score = 0
    else:
        best_score = 256
    for move in moves:
        score = 0
        test = copy.deepcopy(game)
        test.move(move[0], move[1])
        if computer_ai == Othello.BLACK:
            score += test.black_score()
        else:
            score += test.white_score()
        if test.current_player() != computer_ai:
            opponent_moves = _find_moves(test)
            for opponent_move in opponent_moves:
                test2 = copy.deepcopy(test)
                test2.move(opponent_move[0], opponent_move[1])
                if win_most:
                    if computer_ai == Othello.BLACK:
                        if score + test.black_score() > best_score:
                            best_score = score + test.black_score()
                            result = move
                        elif score + test.black_score() == best_score:
                            choice = [result, move]
                            result = choice[random.randrange(len(choice))]
                    else:
                        if score + test.white_score() > best_score:
                            best_score = score + test.white_score()
                            result = move
                        elif score + test.white_score() == best_score:
                            choice = [result, move]
                            result = choice[random.randrange(len(choice))]
                else:
                    if computer_ai == Othello.BLACK:
                        if score + test.black_score() < best_score:
                            best_score = score + test.black_score()
                            result = move
                        elif score + test.black_score() == best_score:
                            choice = [result, move]
                            result = choice[random.randrange(len(choice))]
                    else:
                        if score + test.white_score() < best_score:
                            best_score = score + test.white_score()
                            result = move
                        elif score + test.white_score() == best_score:
                            choice = [result, move]
                            result = choice[random.randrange(len(choice))]
    return result
예제 #11
0
def twoPlayerMode():
    game_field = Othello()
    while True:
        game_field.displayBoard()

        print("Enter move (eg. 'a6')")
        x, y = getComputerReadableNotation(input(">>> "))
        game_field.checkValidAndMove(x, y)

        winner = game_field.isGameOver()
        if winner:
            game_field.displayBoard()
            print(f"{'Black' if winner == BLACK else 'White'} won!")
            break
예제 #12
0
    def __init__(self, ip, username, id):
        self.ip = ip
        self.sio = socketio.Client()
        self.game = Othello()
        self.username = username
        self.id = id
        # self.columns = {
        #     1 : 'A',
        #     2 : 'B',
        #     3 : 'C',
        #     4 : 'D',
        #     5 : 'E',
        #     6 : 'F',
        #     7 : 'G',
        #     8 : 'H'
        # }
        

        self.connect(self.username, self.id)
예제 #13
0
def _win_board(game: Othello) -> None:
    """
    This function prints out the winner (or Tie) and the scores.
    :rtype : None
    :param game: Othello
    """
    blackscore = 'Black:  ' + str(game.black_score())
    whitescore = "White:  " + str(game.white_score())
    winner = game.win_result()
    print()
    print(''.center(50, '-'))
    print('|' + blackscore.center(24, ' ') + whitescore.center(24, ' ') + '|')
    if winner == Othello.BLACK:
        print('|' + "Black Won!".center(48, ' ') + '|')
    elif winner == Othello.WHITE:
        print('|' + "White Won!".center(48, ' ') + '|')
    elif winner == 'Tie':
        print('|' + "Tie!".center(48, ' ') + '|')
    print(''.center(50, '-'))
예제 #14
0
    def mousePressEvent(self, e):  # 玩家下棋
        if e.button() == Qt.LeftButton and self.ai_down == True:
            x, y = e.x(), e.y()  # 鼠标坐标
            i, j = self.coordinate_transform_pixel2map(x, y)  # 对应棋盘坐标
            if not i is None and not j is None:  # 棋子落在棋盘上,排除边缘
                st = []
                st = Env.judge(self.chessboard.lineboard(), self.piece_now)
                k = i * 8 + j
                if self.chessboard.get_xy_on_logic_state(
                        i, j) == EMPTY and k in st:  # 棋子落在空白处
                    if len(st) != 0:
                        self.draw(i, j)
                        self.env.state = self.chessboard.lineboard()
                        s, r, d = self.env._step([self.piece_now * -1, k])
                        self.drawState(s)
                        print('s:', s)
                        self.print_win(d, r, self.piece_now * -1)

                        self.ai_down = False
                        # AI_action = self.random_policy(s, self.piece_now)
                        # AI_action = Value_based.mid_policy(s, self.piece_now)
                        AI_action = test.make_epsilon_greedy_policy(
                            self.Q, s, self.piece_now, 0.1)
                        if AI_action == [0, 0]:
                            self.piece_now = self.piece_now * -1
                            self.ai_down = True
                        else:
                            s, r, d = self.env._step(AI_action)
                            self.drawState(s)
                            print('s:', s)
                            self.print_win(d, r, self.piece_now)
                            self.piece_now = self.piece_now * -1
                            self.ai_down = True
                    else:
                        self.piece_now = self.piece_now * -1
                        self.ai_down = False
                        # AI_action = self.random_policy(s, self.piece_now)
                        # AI_action = Value_based.mid_policy(s, self.piece_now)
                        AI_action = test.make_epsilon_greedy_policy(
                            self.Q, self.env.state, self.piece_now, 0.1)
                        if AI_action == [0, 0]:
                            self.piece_now = self.piece_now * -1
                            self.ai_down = True
                        else:
                            s, r, d = self.env._step(AI_action)
                            self.drawState(s)
                            print('s:', s)
                            self.print_win(d, r, self.piece_now)
                            self.piece_now = self.piece_now * -1
                            self.ai_down = True

                if self.piece_now == BLACK:
                    self.mouse_point.setPixmap(self.black)
                else:
                    self.mouse_point.setPixmap(self.white)
예제 #15
0
    def _get_game_setting(self) -> None:

        dialog = InitialSettingDialog()
        dialog.show()

        if dialog.was_ok_clicked():
            self._game_setting = dialog.get_game_setting()
            self._TopButtonStrVar.set('Enjoy the Game')
            row, col, first, topleft, win = self._game_setting
            newgame = Othello.Othello_game_state(col, row, first, win)
            OthelloGame = OthelloGameBoard(newgame, topleft)
예제 #16
0
 def display(self):
     '''Displays the game board in GUI'''
     self.row = self.row.get()
     self.col = self.col.get()
     self.first_color = self.first_color.get()
     self.TL_color = self.TL_color.get()
     self.win_method = self.win_method.get()
     self._design_window.destroy()
     game = Othello.Othello(self.row, self.col, self.first_color,
                            self.TL_color, self.win_method)
     Othello_GUI.Othello_GUI(game)
예제 #17
0
 def setUp(self):
     self.game = Othello.Othello([
         [None, None, None, None, None, None, None, None],
         [None, None, None, None, None, None, None, None],
         [None, None, None, None, None, None, None, None],
         [None, None, None, 1, 0, None, None, None],
         [None, None, None, 0, 1, None, None, None],
         [None, None, None, None, None, None, None, None],
         [None, None, None, None, None, None, None, None],
         [None, None, None, None, None, None, None, None],
     ])
예제 #18
0
def self_play(i, net):
    st = time.time()
    net.optimizer.zero_grad()
    batch_size = 128
    States = []
    game = Othello()
    mcts = MCTS(net, 1000)
    mcts.virtualLoss(game)
    side = -1
    Tau = 1
    while not game.isover():
        game.board *= -side
        probability = mcts.search(game, Tau)

        States.append([game.board.copy(), probability, side])

        if np.sum(probability) > 0:
            action = np.sum(np.random.rand() > np.cumsum(probability))
            game.board *= -side
            game.play(*index2tuple(action), side)
        else:
            game.play(-1, -1, -1)

        side = -side

    winner = game.get_winner()

    for state, _ in enumerate(States):
        States[state][2] *= -winner

    expand_data = []
    for s in States:
        for func_index in np.random.permutation(7)[:2]:
            expand_data.append(get_equal_board(s[0], s[1], s[2], func_index))
    np.random.shuffle(expand_data)
    batch_data = np.concatenate(
        [States, expand_data[:batch_size - len(States)]], axis=0)
    inputs = np.concatenate(batch_data[:, 0]).reshape(-1, 8,
                                                      8)[:, np.newaxis, :, :]
    rollout_prob = np.concatenate(batch_data[:, 1]).reshape(-1, 64)
    labels = batch_data[:, 2]

    my_probs, my_value = net(inputs)
    loss = cal_loss(my_value, labels, my_probs, rollout_prob)
    net.optimizer.zero_grad()  # clear gradients for next train
    loss.backward(retain_graph=True)
    net.optimizer.step()

    ed = time.time()
    print("%6d game, time=%4.4fs, loss = %5.5f" % (i, ed - st, float(loss)))
    return inputs, rollout_prob, labels
예제 #19
0
    def _start_game(self) -> None:
        """
        This method starts the game.
        """
        self._clear_intro()
        self._game = Othello.Game(self._rows, self._columns,
                                  self._black_plays_first,
                                  self._white_in_top_left, self._win_with_most)
        self._last_move = ''
        self._last_player = 'black'

        self._draw_game()
예제 #20
0
def restart_game():
    global R, iterI
    Vtips.set('')
    R = Othello.Othello()
    iterI = 100
    draw_board(R, img)
    Lcp.place_forget()
    Ldifficulty.place_forget()
    CBcolor.place(x=94 * 8, y=100)
    CBpriority.place(x=94 * 8, y=150)
    CBdifficulty.place(x=94 * 8, y=200)
    Bstart.place(x=94 * 8, y=250)
예제 #21
0
def play_game() -> None:
    """
    This function runs the othello game on the console.
    :rtype : None
    """
    while True:
        _banner()
        while True:
            try:
                game = Othello.Game(_get_rows(), _get_columns(),
                                    _black_plays_first(), _white_in_top_left(),
                                    _win_with_most())
                break

            except Othello.IncorrectNumberOfRows:
                print("\nNumber of rows is incorrect, please try again.")

            except Othello.IncorrectNumberOfColumns:
                print("\nNumber of columns is incorrect, please try again.")

        black_ai = _yes_no_to_bool(
            'Would you like the computer to control Black?  ')
        white_ai = _yes_no_to_bool(
            'Would you like the computer to control White?  ')

        while game.win_result() == "":
            _score_board(game)
            _board(game)
            if black_ai and game.current_player() == Othello.BLACK:
                move = othello_ai.move(game)
                game.move(move[0], move[1])
                print("Black plays Row {}, Column {}.".format(
                    move[0], move[1]))

            elif white_ai and game.current_player() == Othello.WHITE:
                move = othello_ai.move(game)
                game.move(move[0], move[1])
                print("White plays Row {}, Column {}.".format(
                    move[0], move[1]))

            else:
                try:
                    game.move(_play_row(), _play_column())

                except Othello.InvalidMove:
                    print('\nInvalid selection, please try again.')

        _win_board(game)
        _board(game)

        if not _yes_no_to_bool('Would you like to play again?'):
            break
예제 #22
0
def _board(game: Othello) -> None:
    """
    This function prints the game board to the console.
    :rtype : None
    :param game: Othello
    """
    rows = game.rows()
    columns = game.columns()
    for column in range(columns):
        if column < 1:
            print('{:>5}'.format(column + 1), end='')

        else:
            print('{:>3}'.format(column + 1), end='')

    print()

    for row in range(rows):
        print('{:>2}'.format(row + 1), end='')
        for column in range(columns):
            print('{:>3}'.format(game.cell(row + 1, column + 1)), end='')
        print()
예제 #23
0
class Communication:
    """ Aqui va a estar la comunicacion entre el player y el backend """

    def __init__(self, ip, username, id):
        self.ip = ip
        self.sio = socketio.Client()
        self.game = Othello()
        self.username = username
        self.id = id
        # self.columns = {
        #     1 : 'A',
        #     2 : 'B',
        #     3 : 'C',
        #     4 : 'D',
        #     5 : 'E',
        #     6 : 'F',
        #     7 : 'G',
        #     8 : 'H'
        # }
        

        self.connect(self.username, self.id)


    def connect(self, username, id):
        """ Connects and responds with signin """

        @self.sio.on('connect')
        def on_connect():
            self.sio.emit('signin', {
            'user_name': self.username,
            'tournament_id': self.id,
            'user_role': 'player'
            })

        @self.sio.on('ok_signin')
        def on_signin():
            print("Successfully signed in!")

        @self.sio.on('ready')
        def on_ready(data):
            print('ready!')
            gameID = data.get('game_id')
            playerTurnID = data.get('player_turn_id')
            board = data.get('board')
            print('GAMEID: {}'.format(playerTurnID))
            print('Recived board: ')
            self.game.setBoard(board)
            self.game.printBoard()
            # mini_max!
            mini_max = Minimax(player=(playerTurnID))
            # copy game
            newGame = copy.deepcopy(self.game)
            newGame.moves = []
            # Predicts future moves and gets the first one
            new = mini_max.minimax_a_b_p(newGame, maximizingPlayer=True, depth=50)
            # if it returns none, probably means there is no other position
            if new == None:
                print('NO MORE MOVES')
                positionAttack = None
                newGame.printBoard()
            elif new.moves == []:
                print('NO MORE MOVES')
                positionAttack = None
            else:
                x,y = new.moves[0]
                print('TESTING {} {}'.format(x,y))
                # if self.game.checkIfAvailable(x=(x+1), y=(y+1), player=1):
                #     positionAttack = ((y+1)-1)*8 + (x+1)
                # else:
                #     print('[-] THAT WAS NOT SUPPOSED TO HAPPEN!')
                #     newGame.printBoard()
                #     print('TESTING {} {}'.format(x,y))
                positionAttack = ((y+1)-1)*8 + (x+1) - 1

            # Mostramos el board
            print('Attack on : ({},{})'.format(x,y) )
            self.game.printBoard()

            self.sio.emit('play', {
                'tournament_id': self.id,
                'player_turn_id': playerTurnID,
                'game_id': gameID,
                'movement': positionAttack
                })

        @self.sio.on('finish')
        def on_finish(data):
            gameID = data.get('game_id')
            playerTurnID = data.get('player_turn_id')
            winnerTurnID = data.get('winner_turn_id')
            board = data.get('board')

            print('{},{},{},{}'.format(gameID, playerTurnID, winnerTurnID, board))
            print('GAME FINISH! Winner={}'.format(winnerTurnID))
            self.game.setBoard(board)
            self.game.printBoard()

            self.game.reset()

            self.sio.emit('player_ready', {
                'tournament_id': self.id,
                'player_turn_id': playerTurnID,
                'game_id': gameID
                })


        self.sio.connect(self.ip)
        self.sio.wait()
예제 #24
0
파일: MC.py 프로젝트: WangChen0902/Othello
def main():
    value_list = []
    env = Env.OthelloEnv()
    Value = mc_prediction(random_policy, env, num_episodes=10)
    Value[27] = 1
    Value[28] = 1
    Value[35] = 1
    Value[36] = 1
    for i in range(64):
        value_list.append(Value[i])
    # 现有的根据经验得到的矩阵
    # value_list = [10, -9, 8, 4, 4, 8, -9, 10,
    #               -9, -9, -4, -3, -3, -4, -9, -9,
    #               8, -4, 8, 2, 2, 8, -4, 8,
    #               4, 3, 2, 1, 1, 2, 3, 4,
    #               4, 3, 2, 1, 1, 2, 3, 4,
    #               8, -4, 8, 2, 2, 8, -4, 8,
    #               -9, -9, -4, -3, -3, -4, -9, -9,
    #               10, -9, 8, 4, 4, 8, -9, 10]

    # 打印state矩阵
    for i in range(0, 8):
        for j in range(0, 8):
            print(value_list[8 * i + j], end=' ')
            print()
        print()

    # 下棋开始
    def mid_policy(state, flag):
        st = judge(state, flag)
        l = len(st)
        if (l == 0):
            return [0, 0]
        else:
            action = []
            for i in range(l):
                action.append(value_list[i])
            num = max(action)
            p = action.index(num)
            return [flag, st[p]]

    def f(env):
        total = 0
        s = env._reset()
        flag = 1
        action = mid_policy(s, flag)
        d = False
        while not d:
            s, r, d = env._step(action)
            # for i in range(0,8):
            #             #     for j in range(0,8):
            #             #         if(s[8*i+j]==-1):
            #             #             print(s[8*i+j],end=' ')
            #             #         else:
            #             #             print(s[8*i+j],end='  ')
            #             #     print()
            #             # print()
            flag = -flag
            if (flag == 1):
                action = mid_policy(s, flag)
            else:
                action = random_policy(s, flag)
        for i in range(0, 8):
            for j in range(0, 8):
                total += s[8 * i + j]
        # print(total)
        if (total > 0):
            return 1
        else:
            return 0

    env = Env.OthelloEnv()
    f(env)
    win = 0
    for i in range(1000):
        win += f(env)
    print(win / 1000)
예제 #25
0
class Communication:
    def __init__(self):
        print("prueba")
        self.sio = socketio.Client()
        self.game = Othello()
        self.id = 142857

    def connect(self, ip):
        @self.sio.on('connect')
        def on_connect():
            self.sio.emit(
                'signin', {
                    'user_name': 'jenbarillas',
                    'tournament_id': self.id,
                    'user_role': 'player'
                })

        @self.sio.on('ok_signin')
        def on_signin():
            print('Success!')

        @self.sio.on('ready')
        def on_ready(data):
            gameID = data.get('game_id')
            playerTurnID = data.get('player_turn_id')
            board = data.get('board')

            print('Recived board: ')
            self.game.setBoard(board)
            # mini_max!
            mini_max = Minimax(player=(playerTurnID),
                               enemy=((playerTurnID % 2) + 1))
            # copy game
            newGame = copy.deepcopy(self.game)
            newGame.moves = []
            # Predicts future moves and gets the first one
            new = mini_max.minimax_a_b_p(newGame,
                                         maximizingPlayer=True,
                                         depth=50)
            # if it returns none, probably means there is no other position
            if new == None:
                print('NO MORE MOVES')
                positionAttack = 0
                newGame.printBoard()
            elif new.moves == []:
                print('NO MORE MOVES')
                positionAttack = 0
            else:
                x, y = new.moves[0]
                print('TESTING {} {}'.format(x, y))

                # if self.game.checkIfAvailable(x=(x+1), y=(y+1), player=1):
                #     positionAttack = ((y+1)-1)*8 + (x+1)
                # else:
                #     print('[-] THAT WAS NOT SUPPOSED TO HAPPEN!')
                #     newGame.printBoard()
                #     print('TESTING {} {}'.format(x,y))

                positionAttack = y * 8 + x

            print(positionAttack)
            # Mostramos el board
            # print('Attack on : ({},{})'.format(x,y) )
            self.game.printBoard()

            self.sio.emit(
                'play', {
                    'tournament_id': self.id,
                    'player_turn_id': playerTurnID,
                    'game_id': gameID,
                    'movement': positionAttack
                })

        @self.sio.on('finish')
        def on_finish(data):
            gameID = data.get('game_id')
            playerTurnID = data.get('player_turn_id')
            winnerTurnID = data.get('winner_turn_id')
            board = data.get('board')

            print('{},{},{},{}'.format(gameID, playerTurnID, winnerTurnID,
                                       board))
            print('GAME FINISH {}'.format(winnerTurnID))
            self.game.setBoard(board)
            self.game.printBoard()

            self.game.reset()

            self.sio.emit(
                'player_ready', {
                    'tournament_id': self.id,
                    'player_turn_id': playerTurnID,
                    'game_id': gameID
                })

        self.sio.connect(ip)
        self.sio.wait()
예제 #26
0
 def __init__(self):
     print("prueba")
     self.sio = socketio.Client()
     self.game = Othello()
     self.id = 142857
예제 #27
0
    CBdifficulty.place(x=94 * 8, y=200)
    Bstart.place(x=94 * 8, y=250)


def end_game():
    count = R.count()
    if R.get_result(1) == 1.0:
        Vtips.set('白:' + str(count[1]) + '黑:' + str(count[0]) + '---黑方胜!')
    elif R.get_result(R.color) == 0.0:
        Vtips.set('白:' + str(count[1]) + '黑:' + str(count[0]) + '---白方胜!')
    else:
        Vtips.set("平局!")
    return


R = Othello.Othello()
root = tk.Tk()
root.title('黑白棋')
root.geometry('1000x1000')
Pcolor = tk.StringVar()
Ppriority = tk.StringVar()
Pdifficulty = tk.StringVar()
Plcp = tk.StringVar()
retract_moves = deque(maxlen=5)
playermap = {'黑': 1, '白': -1}
diffmap = {'简单': 100, '容易': 1000, '困难': 2000}
flag_start = 0
img_file = ['w', 's', 'b']
Vcolor = tk.StringVar()
Vcolor.set('')
Vtips = tk.StringVar()
예제 #28
0
 def __init__(self):
     super().__init__()
     self.env = Env.OthelloEnv()
     self.initUI()
     self.i = 0
     self.Q = test.Q
예제 #29
0
파일: my.py 프로젝트: WangChen0902/Othello
import sys
import random

from collections import defaultdict
import Othello as Env
from Othello import judge


def random_policy(state, flag):
    st = judge(state, flag)
    l = len(st)
    if l == 0:
        return [0, 0]
    else:
        p = random.randint(0, l - 1)
        return [flag, st[p]]


def f(state, action):
    e = Env.OthelloEnv()
    e.state = state
    s, r, d = e._step(action)
    return s, d


env = Env.OthelloEnv()
env._reset()
ss, dd = f(env.state, random_policy(env.state, 1))
print(ss)
print(dd)
예제 #30
0
def nubmerLegalMove(board, neighbor, color):
    return len(Othello.legal_moves(board, neighbor, color))
예제 #31
0
def playGame(game_state:Othello):
    '''
    Plays the whole game. Will run until both players have no legal moves left.
    '''
    winningType=_winning_type()
    game_state.print_board()
    count=0
    while True:       
        checkMoves=game_state.getValidMoves()
        if(checkMoves==[]):
            print("No Valid Moves. Switching turns")
            count+=1
            if(count==2):
                print("Game Ended becasue there were no moves left")
                break
            game_state._turn=game_state._opposite_turn()
            continue
        else:
            try:
                print("Valid Moves:",checkMoves)
                print("Black:{} White:{}".format(game_state.countPieces("B"),game_state.countPieces("W")))
                print(game_state._turn,"It is your turn")
                row=int(input("Enter Row:"))
                col=int(input("Enter Col:"))
                game_state=game_state.place_piece(row-1,col-1)
                
                    
##                if(newState==game_state):
##                    print("asdfasdf")
##                    game_state.print_board()
##                    continue
##                else:                    
                game_state.print_board()
                #game_state=newState
                count=0
            except:
                print("Invalid Row or Column number")
    if(winningType=='MORE'):
       print(game_state.determineWinner())
    else:
       print(game_state.determineWinnerLeast())
def Othello_Game(x,y,action):

    #이곳에서 오델로 게임을 호출합니다. 호출은 신 4에 있는 고양이를 누르는것으로 되며 startgame중에 다시 startgame을 호출하는것은 불가능할듯 하여 
    #endgame을 하고 다시 startgame을 해야하지 않을까 싶습니다. 
    Othello.startGame(Othello.Main)
예제 #33
0
파일: my.py 프로젝트: WangChen0902/Othello
def f(state, action):
    e = Env.OthelloEnv()
    e.state = state
    s, r, d = e._step(action)
    return s, d