Esempio n. 1
0
    def __init__(self, board, **kwargs):
        super(UCT, self).__init__(board, **kwargs)
        self.stats = {}

        self.max_depth = 0
        self.data = {}
        time = 30    # should be 1 min but in case that time is over
        self.calculation_time = float(time)
        # self.calculation_time = float(kwargs.get('time', 3))  # @ST @NOTE Here calculation_time should be 1 min
        self.max_actions = int(kwargs.get('max_actions', 64))

        # Exploration constant, increase for more exploratory actions,
        # decrease to prefer actions with known higher win rates.
        self.C = float(kwargs.get('C', 1.96)) #Original1.4

        self.plugged_in_minimax = minimax.MiniMax(reversi.Board())
        self.minimax_max_depth = 1
Esempio n. 2
0
    def __init__(self, evaluators, pieces=None, side=BLACK):
        """
        Searcher instance: an engine which finds the "best" move for the current
        board state.
        :param pieces: 2d list <- arrangement of pieces on the board
        :param side: side to play next
        """

        if pieces is None:
            pieces = START_POSITION

        self.fully_expanded = 0
        self.tree_depth = 0
        self.pieces = 4

        self.evaluators = evaluators
        self.board = reversi.Board(pieces, side)
        self.game_tree = anytree.Node(self.board)

        self.caught_up = True
Esempio n. 3
0
def game_play_human():
    """
    This is the main mechanism of the human vs. human game play.
    """
    
    banner = """
     _____                         _ 
    |  __ \                       (_)
    | |__) |_____   _____ _ __ ___ _ 
    |  _  // _ \ \ / / _ \ '__/ __| |
    | | \ \  __/\ V /  __/ |  \__ \ |
    |_|  \_\___| \_/ \___|_|  |___/_|
    
    Developed by The Students Inc.
    CSE231 Spring Semester 2018
    Michigan State University
    East Lansing, MI 48824, USA.
    """

    prompt = "[{:s}'s turn] :> "
    print(banner)
   
    # Choose the color here
    (my_color, opponent_color) = choose_color()
    
    # Take a board of size 8x8
    # Prompt for board size
    size = input("Input a board size: ")
    board = reversi.Board(int(size))
    initialize(board)
    
    # Decide on whose turn, use a variable called 'turn'.
    turn = my_color if my_color == 'white' else opponent_color
    
    # loop until the game is finished
    while not is_game_finished(board):
        try:
            # Count the pieces and assign into piece_count
            piece_count = count_pieces(board)
            
            print("Current board:")
            board.display(piece_count)    
            
            # Get a piece according to turn
            piece = reversi.Piece(turn)

            # Get the command from user using input
            command = input(prompt.format(turn)).lower()
            
            # Now decide on different commands
            if command == 'exit':
                break
            elif command == 'hint':
                print("\tHint: " + ", ".join(get_hint(board, piece)))
            elif command == 'pass':
                hint = get_hint(board, piece)
                if len(hint) == 0:
                    turn = my_color if turn == opponent_color \
                                        else opponent_color
                    print("\tHanded over to \'{:s}\'.".format(turn))
                else:
                    print("\tCan't hand over to opponent, you have moves," + \
                          " type \'hint\'.")
            else:
                    (row, col) = indexify(command)
                    t = place_and_flip(board, row, col, piece)
                    if "Error:" in t:
                        print(t)
                        continue
                    else:
                        print("\t{:s} played {:s}.".format(turn, command))
                        turn = my_color if turn == opponent_color \
                                            else opponent_color
        except Exception as err:
            print("Error:", err)
    
    # The loop is over.
    piece_count = count_pieces(board)
    print("Current board:")
    board.display(piece_count)    
    winner = get_winner(board)
    if winner != 'draw':
        diff = abs(piece_count[0] - piece_count[1])
        print("\'{:s}\' wins by {:d}! yay!!".format(winner, diff))
    else:
        print("This game ends in a draw.")
Esempio n. 4
0
        size_data = sock_data = ''
        recv_size = expected_size
        while total_len < size:
            sock_data = socket.recv(recv_size)
            if not total_data:
                if len(sock_data) > 4:
                    size_data += sock_data
                    size = struct.unpack('>i', size_data[:4])[0]
                    recv_size = size
                    if recv_size > 524288:
                        recv_size=524288
                    total_data.append(size_data[4:])
                else:
                    size_data += sock_data
            else:
                total_data.append(sock_data)
            total_len=sum([len(i) for i in total_data ])
        return ''.join(total_data)

if __name__ == '__main__':
    parser = argparse.ArgumentParser(
        description="A server for board game with/without gui")
    parser.add_argument('-g', '--gui', action = 'store_true', dest = 'use_gui', default = False)
    parser.add_argument('address', nargs='?')
    parser.add_argument('port', nargs='?', type=int)

    args = parser.parse_args()

    reversiServer = Server(reversi.Board(), args.address, args.port, args.use_gui)
    reversiServer.run()
Esempio n. 5
0
        data = {}
    sys.stdout.flush()

    try:
        sys.stdout.write("Loading test file... ")
        sys.stdout.flush()
        test = datafile_manager.load_data(TEST_FILE)
        sys.stdout.write("Done\n")
    except IOError:
        sys.stdout.write("test file not found, starting with empty dataset.\n")
        test = {}
    sys.stdout.flush()

    try:
        while True:
            b = reversi.Board()
            first = True

            while not b.is_over() and len(b.available_positions) > 8:
                if random.choice(RANDOM_ARRAY) or first:
                    move = random.choice(b.legal_moves_notation)
                    first = False
                else:
                    move = edax_wrapper.best_move()
                b.move(move)

                position = b.get_pieces()
                sys.stdout.write("New position: {}\n".format(position))

                sys.stdout.write("Evaluating position... ")
                score = edax_wrapper.get_evaluation(position, depth=DEPTH)
Esempio n. 6
0
import reversi
import myPlayer
import humanPlayer
import time

b = reversi.Board(10)

players = []
player1 = myPlayer.myPlayer()
player1.newGame(b._BLACK)
players.append(player1)
player2 = humanPlayer.myPlayer()
player2.newGame(b._WHITE)
players.append(player2)

totalTime = [0, 0]  # total real time for each player
nextplayer = 0
nextplayercolor = b._BLACK
nbmoves = 1

print(b.legal_moves())
while not b.is_game_over():
    print("Referee Board:")
    print(b)
    print("Before move", nbmoves)
    print("Legal Moves: ", b.legal_moves())
    nbmoves += 1
    otherplayer = (nextplayer + 1) % 2
    othercolor = b._BLACK if nextplayercolor == b._WHITE else b._WHITE

    currentTime = time.time()
Esempio n. 7
0
def PLAY_GAME(no, debug, game_mode, deep):
    '''
    # = black piece - random_player
    o = white piece - our bot
    Result is + for whites
    '''

    white_win, black_win = 0, 0
    for game_no in range(1, no + 1):
        player = True
        B = reversi.Board(debug)

        cnt = 1
        while True:
            # B.draw()
            if debug:
                print(f'Move: {cnt}')
                B.draw()
                B.show()

            if player:
                m = B.random_move(player)
                B.do_move(m, player)
            else:
                if game_mode == 1:
                    m = B.random_move(player)
                    B.do_move(m, player)
                if game_mode == 2:
                    best_move = B.find_best(deep, player)
                    B.do_move(best_move, player)
                    # print('Min max best = ', best_move)

            player = not player

            if debug:
                # time.sleep(0.01)
                input()

            if B.terminal():
                break
            cnt += 1

        if debug:
            print('End of game')
            B.draw()
            B.show()
            input()

        if B.result() > 0:
            white_win += 1

        if B.result() < 0:
            black_win += 1

        # B.draw()

        print(f'Game: {game_no}, result: {B.result()}')
        # B.finish()
    print('-' * 20)
    print(f'Whites won {white_win} / {no} games')
    print(f'It is : {white_win / (white_win + black_win) * 100}%')
Esempio n. 8
0
if not Highscore.load(score_path):
    print("High score kunde inte läsas in. Sätter till 0 poäng.\n")

try:
    size = interface.get_int(
        "Skriv storleken på brädet (måste vara delbart med två och ligga mellan 4 och 26): ",
        "Du måste skriva ett tal!")
    while not 4 <= size <= 26 or size % 2 == 1:
        print("Måste vara delbart med två och ligga mellan 4 och 26!")
        size = interface.get_int(
            "Skriv storleken på brädet (måste vara delbart med två och ligga mellan 4 och 26): ",
            "Du måste skriva ett tal!")
    print()

    board = reversi.Board(size)
    game = reversi.Reversi(board)
    bot = Bot(game, -player)

    winner = None
    while not winner:
        interface.display_board(board)

        if game.get_turn() == player:
            print("Din tur (%s) att spela!" % colors[player])

            if interface.should_skip():
                game.skip()
            else:
                success = False
                while not success: