Example #1
0
def Game(red=AI.Strategy, black=Tonto.Strategy, init=None, maxplies=8, verbose=False):
    sharedBoard = checkerboard.CheckerBoard()
    redplayer = red('r',checkerboard.CheckerBoard(), maxplies)
    blackplayer = black('b',checkerboard.CheckerBoard(), maxplies)
    moveCount = 0
    gameComplete = False 
    winner = None
    move = None
    while not gameComplete:
        if (moveCount % 2) == 0:
            sharedBoard, move = redplayer.play(sharedBoard)
        else:
            sharedBoard, move = blackplayer.play(sharedBoard)
        moveCount += 1
        print sharedBoard
        gameComplete, winner = sharedBoard.is_terminal()
        if not gameComplete:
            if move == []:
                gameComplete = True
                if (moveCount % 2) == 0:
                    winner = 'r'
                else:
                    winner = 'b'
    print sharedBoard
    if winner is None:
        print 'Tie in ' + str(moveCount) + ' moves.'
    else:
        print 'The winner is: ' + winner + ' in ' + str(moveCount) + ' moves.'
def Game(red=AI.Strategy,
         black=Human.Strategy,
         init=None,
         maxplies=8,
         verbose=False):
    game_board = checkerboard.CheckerBoard()
    redplayer = red('r', game_board, maxplies)
    blackplayer = black('b', game_board, maxplies)
    turn_tracker = 1
    players = [redplayer, blackplayer]

    while True:
        turn_tracker = turn_tracker % 2 - 1

        game_board = players[turn_tracker].play(game_board)[0]
        print "RED MOVED\n", game_board

        turn_tracker = turn_tracker % 2 - 1

        game_board = players[turn_tracker].play(game_board)[0]
        print "BLACK MOVED\n", game_board

        if game_board.is_terminal()[0]:
            print "GAME OVER\n"
            break
Example #3
0
def Game(red=human.Strategy,
         black=tonto.Strategy,
         maxplies=5,
         init=None,
         verbose=True,
         firstmove=0):
    """Game(red, black, maxplies, init, verbose, turn)
    Start a game of checkers
    red,black - Strategy classes (not instances)  # Not invoked
    maxplies - # of turns to explore (default 10)
    init - Start with given board (default None uses a brand new game)
    verbose - Show messages (default True)
    firstmove - Player N starts 0 (red) or 1 (black).  Default 0. 
    """

    # Example of creating a game
    # ai_player = ai.strategy('r', checkerboard.CheckerBoard, maxplies)  # todo
    #  create a checkerboard with this particular state
    red_player = red('r', checkerboard.CheckerBoard, maxplies)
    black_player = black('b', checkerboard.CheckerBoard, maxplies)

    board = checkerboard.CheckerBoard()

    board.turncount = 0
    while board.is_terminal()[0] is False:
        if board.turn_count % 2 == 0:
            [board, red_action] = red_player.play(board)
            print("Red player moved {}".format(red_action))
            print(board)
        if board.turn_count % 2 != 0:
            [board, black_action] = black_player.play(board)
            print("Black player moved {}".format(black_action))
            print(board)
        board.turn_count += 1
    print("Winner chicken dinner is: " + str(board.is_terminal()[1]))
Example #4
0
def Game(red=human.Strategy,
         black=ai.Strategy,
         maxplies=5,
         init=None,
         verbose=False,
         firstmove=0):
    """Game(red, black, maxplies, init, verbose, turn)
    Start a game of checkers
    red,black - Strategy classes (not instances)
    maxplies - # of turns to explore (default 10)
    init - Start with given board (default None uses a brand new game)
    verbose - Show messages (default True)
    firstmove - Player N starts 0 (red) or 1 (black).  Default 0. 
    """

    red_player = red('r', checkerboard.CheckerBoard, maxplies)  #human player
    black_player = black('b', checkerboard.CheckerBoard,
                         maxplies)  #computer player

    board = checkerboard.CheckerBoard(
    )  #instance of checkerboard used to play games

    game_start = time.time()  #start timer for start of game
    while not board.is_terminal(
    )[0]:  #continue taking turns until a player has won
        if verbose:
            print(board)
        move_start = time.time(
        )  #start timer to show how long red takes to make a move
        [red_board, red_action
         ] = red_player.play(board)  #allow red player, a human, to make a move
        current = time.time(
        )  #end timer to show how long red takes to make a move
        if verbose:
            print("Red player moved {}".format(red_action))
            print("Move time: {} Game time: {}".format(
                elapsed(move_start, current), elapsed(game_start, current)))

        #use board returned after red_player has made a move
        move_start = time.time(
        )  #start timer to show how long black takes to make a move
        [black_board, black_action] = black_player.play(
            red_board)  #allow black player, the computer, to make a move
        current = time.time(
        )  #mark time for how long black player took to make a turn
        if verbose:
            print("Black player moved {}".format(black_action))
            print("Move time: {} Game time: {}".format(
                elapsed(move_start, current), elapsed(game_start, current)))
        board = black_board  #copy board for red player to play with at next turn of loop

    #while loop ends when a player has won
    print("Congratulations to player %c!", board.is_terminal()[1])
Example #5
0
def Game(red=human.Strategy, black=ai.Strategy, maxplies=8, init=None, verbose=True, firstmove=0):
    """Game(red, black, maxplies, init, verbose, turn)
    Start a game of checkers
    red,black - Strategy classes (not instances)
    maxplies - # of turns to explore (default 10)
    init - Start with given board (default None uses a brand new game)
    verbose - Show messages (default True)
    firstmove - Player N starts 0 (red) or 1 (black).  Default 0. 
    """
    # Don't forget to create instances of your strategy,
    # e.g. black('b', checkerboard.CheckerBoard, maxplies)

    turns = 0
    if init is None:
        board = checkerboard.CheckerBoard()
    else: 
        board = init
    red_Player = red('r', board, maxplies)
    black_Player = black('b', board, maxplies)
    while not board.is_terminal()[0] and turns < 40:
        board.update_counts()
        #if red is first
        if firstmove == 0:
            board.update_counts()
            [board, red] = red_Player.play(board)    
            print(board)
            if red is None: #Player forfeits
                print("Red player forfeits. Black player WON!!!")
                break
            [board, black] = black_Player.play(board)
            print(board)
            board.update_counts()
            
        elif firstmove == 1:
            [board2, black] = black_Player.play(board)
            print(board2)
            [board1, red] = red_Player.play(board2)    
            print(board1)
            board = board1
        turns += 1
        if board.is_terminal()[0]:
            #game is finish
            print (board.is_terminal()[1],'WINNER')
            break
        if turns == 40:
            print('DRAW!!')
            break
Example #6
0
def Game(red=human.Strategy,
         black=tonto.Strategy,
         maxplies=10,
         init=None,
         verbose=True,
         firstmove=0):
    """Game(red, black, maxplies, init, verbose, turn)
    Start a game of checkers
    red,black - Strategy classes (not instances)
    maxplies - # of turns to explore (default 10)
    init - Start with given board (default None uses a brand new game)
    verbose - Show messages (default True)
    firstmove - Player N starts 0 (red) or 1 (black).  Default 0. 
    """
    my_board = checkerboard.CheckerBoard() if (init is None) else init

    print("Initial state of the board:")
    print(my_board)

    red_player = red('r', checkerboard.CheckerBoard, maxplies)
    print(black)
    black_player = black.Strategy('b', checkerboard.CheckerBoard, maxplies)

    players = (red_player, black_player)
    i = 1
    game_over = False
    winner = None
    print("Game begins now!")
    current_board = my_board
    while not game_over:
        i += 1
        new_board, best_move = players[i % 2].play(current_board)
        print(new_board)
        print(best_move)
        (game_over, winner) = new_board.is_terminal()
        current_board = new_board

    # Output statement for the winner declarations
    if winner in ['r', 'R']:
        print("The winner is RED player")
    elif winner in ['b', 'B']:
        print("The winner is BLACK player")
    else:
        print("The game ended in a draw")
def Game(red=human.Strategy, black=ai.Strategy,
         maxplies=10, init=None, verbose=True, firstmove=0):
    """Game(red, black, maxplies, init, verbose, turn)
    Start a game of checkers
    red,black - Strategy classes (not instances)
    maxplies - # of turns to explore (default 10)
    init - Start with given board (default None uses a brand new game)
    verbose - Show messages (default True)
    firstmove - Player N starts 0 (red) or 1 (black).  Default 0. 
    """

    # Don't forget to create instances of your strategy,
    # e.g. black('b', checkerboard.CheckerBoard, maxplies)
    game = checkerboard.CheckerBoard()
    black_player = black('b', game, maxplies)
    red_player = red('r', game, maxplies)
    moves = 0
    while not game.is_terminal()[0]:
        print(game.__repr__())
        if firstmove == 0:
            if moves % 2 == 0:
                new_game, move = red_player.play(game)
                moves += 1
                game = new_game
            else:
                new_game, move = black_player.play(game)
                moves += 1
                game = new_game
        else:
            if moves % 2 == 0:
                new_game, move = black_player.play(game)
                moves += 1
                game = new_game
            else:
                new_game, move = red_player.play(game)
                moves += 1
                game = new_game
    print(f"Winner is: {game.is_terminal()[1]}")
Example #8
0
    def setUp(self):
        boardlibrary.init_boards()
        self.Pristine = boardlibrary.boards["Pristine"]
        # initial board
        self.SingleHopsRed = boardlibrary.boards["SingleHopsRed"]
        # Set up for two red single hops
        #           0  1  2  3  4  5  6  7
        #        0  .  b  .  b  .  b  .  b
        #        1  b  .  b  .  b  .  b  .
        #        2  .  b  .  .  .  .  .  b
        #        3  .  .  .  .  .  .  b  .
        #        4  .  .  .  b  .  .  .  r
        #        5  r  .  r  .  r  .  .  .
        #        6  .  r  .  r  .  r  .  r
        #        7  r  .  r  .  r  .  r  .
        self.SingleHopsBlack = boardlibrary.boards["SingleHopsBlack"]
        # Set up for black single hops
        #     0  1  2  3  4  5  6  7
        #  0  .  b  .  b  .  b  .  b
        #  1  b  .  b  .  b  .  b  .
        #  2  .  b  .  .  .  .  .  b
        #  3  .  .  .  .  .  .  r  .
        #  4  .  .  .  b  .  .  .  r
        #  5  r  .  r  .  r  .  .  .
        #  6  .  .  .  r  .  r  .  r
        #  7  r  .  r  .  r  .  r  .
        self.multihop = boardlibrary.boards["multihop"]
        # multihop
        #     0  1  2  3  4  5  6  7
        #  0  .  b  .  b  .  b  .  b
        #  1  b  .  r  .  b  .  .  .
        #  2  .  r  .  .  .  b  .  b
        #  3  .  .  .  .  .  .  .  .
        #  4  .  .  .  r  .  b  .  .
        #  5  .  .  .  .  .  .  r  .
        #  6  .  r  .  r  .  r  .  r
        #  7  r  .  .  .  r  .  .  .
        self.KingBlack = boardlibrary.boards["KingBlack"]
        # KingBlack
        # Black can move to become a King but should
        # not be able to move after being kinged
        #    0  1  2  3  4  5  6  7
        #    0  .  .  .  .  .  .  .  .
        #    1  .  .  .  .  .  .  .  .
        #    2  .  .  .  .  .  .  .  .
        #    3  .  .  .  .  b  .  .  .
        #    4  .  .  .  r  .  r  .  .
        #    5  .  .  .  .  .  .  .  .
        #    6  .  .  .  r  .  r  .  .
        #    7  .  .  .  .  .  .  .  .
        self.BlackKingTour = boardlibrary.boards["BlackKingTour"]
        # BlackKingTour
        #    0  1  2  3  4  5  6  7
        #    0  .  .  .  .  .  .  .  .
        #    1  .  .  .  .  .  .  .  .
        #    2  .  .  .  .  .  .  .  .
        #    3  .  .  .  .  B  .  .  .
        #    4  .  .  .  r  .  r  .  .
        #    5  .  .  .  .  .  .  .  .
        #    6  .  .  .  r  .  r  .  .
        #    7  .  .  .  .  .  .  .  .
        self.RedKingTour = boardlibrary.boards["RedKingTour"]
        # RedKingTour
        # Probably don't need to test this one as rules similar, but...
        #    0  1  2  3  4  5  6  7
        #    0  .  .  .  .  .  .  .  .
        #    1  .  .  .  .  .  .  .  .
        #    2  .  .  .  .  .  .  .  .
        #    3  .  .  .  .  R  .  .  .
        #    4  .  .  .  b  .  b  .  .
        #    5  .  .  .  .  .  .  .  .
        #    6  .  .  .  b  .  b  .  .
        #    7  .  .  .  .  .  .  .  .
        self.StrategyTest1 = boardlibrary.boards["StrategyTest1"]
        # ???
        self.EndGame1 = boardlibrary.boards["EndGame1"]
        # EndGame 1 - Red can easily win
        #       0  1  2  3  4  5  6  7
        #    0     .     .     R     b
        #    1  .     .     .     .
        #    2     .     .     .     .
        #    3  .     .     .     .
        #    4     .     .     .     .
        #    5  .     .     .     .
        #    6     .     .     .     R
        #    7  .     .     .     .
        self.boards = [self.Pristine, self.SingleHopsRed, self.SingleHopsBlack, self.multihop,
                       self.KingBlack, self.BlackKingTour, self.RedKingTour, self.EndGame1]
        self.my_checkerboard = checkerboard.CheckerBoard()
        self.my_ai_red = ai.AI('r', checkerboard.CheckerBoard, 10)
        self.my_ai_black = ai.AI('b', checkerboard.CheckerBoard, 10)

        self.minimax_red = ai.Minimax('r', 'b', 10, self.my_ai_red)
        self.minimax_black = ai.Minimax('b', 'r', 10, self.my_ai_red)
Example #9
0
def init_boards():
    """Set up a library of board positions for test purposes
    WARNING:  Some components of the checkers program rely on this library
    for testing.  Changing board configurations will result in breakage of
    tests if the tests are not updated.  Adding new tests is fine.
    """

    # Initial board
    boards["Pristine"] = checkerboard.CheckerBoard()

    # Set up for two red single hops
    #           0  1  2  3  4  5  6  7
    #        0  .  b  .  b  .  b  .  b
    #        1  b  .  b  .  b  .  b  .
    #        2  .  b  .  .  .  .  .  b
    #        3  .  .  .  .  .  .  b  .
    #        4  .  .  .  b  .  .  .  r
    #        5  r  .  r  .  r  .  .  .
    #        6  .  r  .  r  .  r  .  r
    #        7  r  .  r  .  r  .  r  .
    b = checkerboard.CheckerBoard()
    b.place(2, 3, None)
    b.place(2, 5, None)
    b.place(3, 6, 'b')
    b.place(4, 3, 'b')
    b.place(5, 6, None)
    b.place(4, 7, 'r')
    boards["SingleHopsRed"] = b

    # Set up for black single hops
    #     0  1  2  3  4  5  6  7
    #  0  .  b  .  b  .  b  .  b
    #  1  b  .  b  .  b  .  b  .
    #  2  .  b  .  .  .  .  .  b
    #  3  .  .  .  .  .  .  r  .
    #  4  .  .  .  b  .  .  .  r
    #  5  r  .  r  .  r  .  .  .
    #  6  .  .  .  r  .  r  .  r
    #  7  r  .  r  .  r  .  r  .
    b = copy.deepcopy(b)
    b.place(6, 1, None)
    b.place(3, 6, 'r')
    boards["SingleHopsBlack"] = b

    # multihop
    #     0  1  2  3  4  5  6  7
    #  0  .  b  .  b  .  b  .  b
    #  1  b  .  r  .  b  .  .  .
    #  2  .  r  .  .  .  b  .  b
    #  3  .  .  .  .  .  .  .  .
    #  4  .  .  .  r  .  b  .  .
    #  5  .  .  .  .  .  .  r  .
    #  6  .  r  .  r  .  r  .  r
    #  7  r  .  .  .  r  .  .  .
    b = checkerboard.CheckerBoard()
    b.place(7, 2, None)
    b.place(7, 6, None)
    b.place(5, 0, None)
    b.place(5, 2, None)
    b.place(5, 4, None)
    b.place(4, 3, 'r')
    b.place(4, 5, 'b')
    b.place(2, 1, 'r')
    b.place(2, 3, None)
    b.place(1, 2, 'r')
    b.place(1, 6, None)
    b.recount_pieces()
    boards["multihop"] = b

    # KingBlack
    # Black can move to become a King but should
    # not be able to move after being kinged
    #    0  1  2  3  4  5  6  7
    #    0  .  .  .  .  .  .  .  .
    #    1  .  .  .  .  .  .  .  .
    #    2  .  .  .  .  .  .  .  .
    #    3  .  .  .  .  b  .  .  .
    #    4  .  .  .  r  .  r  .  .
    #    5  .  .  .  .  .  .  .  .
    #    6  .  .  .  r  .  r  .  .
    #    7  .  .  .  .  .  .  .  .
    b = checkerboard.CheckerBoard()
    # clear the board
    for r in xrange(b.rows):
        for c in range(b.coloffset[r], b.cols, 2):
            b.place(r, c, None)
    # Set up for tour by black
    b.place(3, 4, 'b')  # pawn that will be making partial tour
    b.place(4, 3, 'r')
    b.place(6, 3, 'r')  # king black after this jump
    b.place(6, 5, 'r')  # or this one depending on path
    b.place(6, 5, 'r')
    b.place(4, 5, 'r')
    b.recount_pieces()
    boards["KingBlack"] = b

    # BlackKingTour
    #    0  1  2  3  4  5  6  7
    #    0  .  .  .  .  .  .  .  .
    #    1  .  .  .  .  .  .  .  .
    #    2  .  .  .  .  .  .  .  .
    #    3  .  .  .  .  B  .  .  .
    #    4  .  .  .  r  .  r  .  .
    #    5  .  .  .  .  .  .  .  .
    #    6  .  .  .  r  .  r  .  .
    #    7  .  .  .  .  .  .  .  .
    b = copy.deepcopy(b)
    b.place(3, 4, 'B')  # king that will make tour
    b.recount_pieces()
    boards["BlackKingTour"] = b

    # RedKingTour
    # Probably don't need to test this one as rules similar, but...
    #    0  1  2  3  4  5  6  7
    #    0  .  .  .  .  .  .  .  .
    #    1  .  .  .  .  .  .  .  .
    #    2  .  .  .  .  .  .  .  .
    #    3  .  .  .  .  R  .  .  .
    #    4  .  .  .  b  .  b  .  .
    #    5  .  .  .  .  .  .  .  .
    #    6  .  .  .  b  .  b  .  .
    #    7  .  .  .  .  .  .  .  .
    b = copy.deepcopy(b)
    b.place(3, 4, 'R')  # pawn that will be making partial tour
    b.place(4, 3, 'b')
    b.place(6, 3, 'b')  # king red after this jump
    b.place(6, 5, 'b')  # or this one depending on path
    b.place(6, 5, 'b')
    b.place(4, 5, 'b')
    b.recount_pieces()
    boards["RedKingTour"] = b

    b = checkerboard.CheckerBoard()
    b.clearboard()
    b.place(0, 1, 'b')
    b.place(0, 7, 'b')
    b.place(1, 6, 'r')
    b.place(2, 1, 'r')
    b.place(2, 3, 'b')
    b.place(2, 5, 'b')
    b.place(4, 3, 'r')
    b.place(5, 4, 'r')
    b.place(6, 1, 'b')
    b.place(6, 3, 'r')
    b.recount_pieces()
    boards["StrategyTest1"] = b
def Game(red=ai.Strategy,
         black=tonto.Strategy,
         init=None,
         maxplies=10,
         verbose=True,
         firstmove=0):
    """
    Game(red, black, maxplies, init, verbose, turn)
        Start a game of checkers
        red,black - Strategy classes (not instances)
        maxplies - # of turns to explore (default 10)
        init - Start with given board (default None uses a brand new game)
        verbose - Show messages (default True)
        firstmove - Player N starts 0 (red) or 1 (black).  Default 0. 
    """

    # Print the current board, action taken, piece count, and number of moves
    def printMove():
        if len(action[1]) == 3:
            capture = "Capturing" + str(action[1][1])
            print("Move %s by %s: from %s to %s capturing %s  Result:" %
                  (game_board.movecount, players[turn], action[0],
                   (action[1][0], action[1][1]), action[1][2]))
        else:
            print("Move %s by %s: from %s to %s  Result:" %
                  (game_board.movecount, players[turn], action[0], action[1]))
        print(game_board)
        print(
            "Pawn/King count: r %d R %d b %d B %d  Time - move: %d s, game %.1f min"
            % (game_board.get_pawnsN()[0], game_board.get_kingsN()[0],
               game_board.get_pawnsN()[1], game_board.get_kingsN()[1],
               t_move.elapsed_s(), t_game.elapsed_min()))
        print("Moves since last capture %d last pawn advance %d" %
              (game_board.lastcapture, game_board.lastpawnadvance))
        print()

    # Inialize board library and timer
    boardlibrary.init_boards()
    t_game = Timer()

    if init:
        game_board = init
    else:
        game_board = checkerboard.CheckerBoard()

    # Initialize players and maxplies values
    red = red('r', game_board, maxplies)
    black = black('b', game_board, maxplies)

    # Initialize play lists and print start statement
    print("How about a nice game of checkers?")
    turn = firstmove
    players = ['r', 'b']
    board_states = []
    r_moves = []
    b_moves = []
    move_times = [r_moves, b_moves]

    # Has red and black players call their play functions until game is in terminal state
    while not game_board.is_terminal()[0]:

        # Sets timer to determine how many seconds it takes for a player to make a move
        t_move = Timer()

        print("Player %s turn" % players[turn])

        # Black player makes a move, then appends move to black moves list
        if turn:
            game_board, action = black.play(game_board)
            b_moves.append(t_move.elapsed_s())

        # Red player makes a move, then appends move to red moves list
        else:
            game_board, action = red.play(game_board)
            r_moves.append(t_move.elapsed_s())

        # If logging is enabled, then print the move made by the player
        if verbose:
            printMove()

        # Determines whether to draw the current board and whether to break
        n = 0
        draw = False
        for state in board_states:
            if game_board.board == state:
                n += 1
            if n >= 3:
                draw = True
                break

        # Append the new board state to the list of previous states
        board_states.append(game_board.board)

        # Switch turn
        turn = not turn

    # Prints final board, endgame message, and stats for each player
    print("Final board")
    print(game_board)
    if draw:
        print("Game is a draw")
    else:
        print("The winner is %s!" % players[not turn])

    for i, player in enumerate(players):
        time = mean(move_times[i])
        print("%s Average move time: %d:%d:%d" %
              (player, time / 60 / 60, time / 60, time))
Example #11
0
def Game(red=human.Strategy,
         black=tonto.Strategy,
         maxplies=10,
         init=None,
         verbose=True,
         firstmove=0):
    """Game(red, black, maxplies, init, verbose, turn)
    Start a game of checkers
    red,black - Strategy classes (not instances)
    maxplies - # of turns to explore (default 10)
    init - Start with given board (default None uses a brand new game)
    verbose - Show messages (default True)
    firstmove - Player N starts 0 (red) or 1 (black).  Default 0.
    """

    # Don't forget to create instances of your strategy,
    # e.g. black('b', checkerboard.CheckerBoard, maxplies)

    print("How about a nice game of checkers?")
    if init is not None:
        board = init
    else:
        board = checkerboard.CheckerBoard()
    red_player = red('r', board, maxplies)
    black_player = black('b', board, maxplies)
    turn = firstmove
    moves = 0
    players = [red_player, black_player]
    game_time = Timer()
    winner = None
    rplayer_time = list()
    bplayer_time = list()
    while not board.is_terminal()[0]:
        if turn == 0:
            print("Player r turn\n", board)
            red_time = Timer()
            board, action = red_player.play(board)
            if action is None:
                winner = 'b'
                break
            if verbose:
                print("Move {} by r: {}  Result: ".format(
                    moves, board.get_action_str(action)))
                moves += 1
                print(board)
                print(
                    "Pawn/King count: r {} R {} b {} B {} Time - move: {:.0f}s / game: {:.1f}min"
                    .format(board.get_pawnsN()[0],
                            board.get_kingsN()[0],
                            board.get_pawnsN()[1],
                            board.get_kingsN()[1], red_time.elapsed_s(),
                            game_time.elapsed_min()))
                print(
                    "Moves since last capture {} last pawn advance {}".format(
                        moves - board.lastcapture,
                        moves - board.lastpawnadvance))
                if action is None:
                    print("Player r has Forfeited")
            rplayer_time.append(red_time.elapsed_s())
        else:
            print("Player b turn\n", board)
            black_time = Timer()
            board, action = black_player.play(board)
            if action is None:
                winner = 'r'
                break
            if verbose:
                print("Move {} by b: {}  Result: ".format(
                    moves, board.get_action_str(action)))
                moves += 1
                print(board)
                print(
                    "Pawn/King count: b {} R {} b {} B {} Time - move: {:.0f}s / game: {:.1f}min"
                    .format(board.get_pawnsN()[0],
                            board.get_kingsN()[0],
                            board.get_pawnsN()[1],
                            board.get_kingsN()[1], black_time.elapsed_s(),
                            game_time.elapsed_min()))
                print(
                    "Moves since last capture {} last pawn advance {}".format(
                        moves - board.lastcapture,
                        moves - board.lastpawnadvance))
            bplayer_time.append(black_time.elapsed_s())
        turn = (turn + 1) % 2
    # determine each state and print out output
    if board.is_terminal()[0]:
        print("Final Board")
        print(board)
        winner = board.is_terminal()[1]
        if winner is None:
            print("Game is a draw")
            print("r Average move time: {:.2f}s".format(mean(rplayer_time)))
            print("b Average move time: {:.2f}s".format(mean(bplayer_time)))
        else:
            print("Player {} WINS!!! ".format(winner))
    else:
        print("player Forfeit - {} wins!".format(winner))
Example #12
0
def Game(red=ai.Strategy,
         black=tonto.Strategy,
         maxplies=5,
         init=None,
         verbose=True):
    """Game(red, black, maxplies, init, verbose, turn)
    Start a game of checkers
    red,black - Strategy classes (not instances)
    maxplies - # of turns to explore (default 10)
    init - Start with given board (default None uses a brand new game)
    verbose - Show messages (default True)
    """

    #* set gameBoard to inital checker board,
    if init == None: init = checkerboard.CheckerBoard()
    gameBoard = init

    #* create instances of strategies
    black = black('b', checkerboard.CheckerBoard, maxplies)
    red = red('r', checkerboard.CheckerBoard, maxplies)

    print("Welcome to the wonderous world of checkers!")
    gameTime = Timer()

    move = 1
    rMoveTimeList = []
    bMoveTimeList = []

    while (True):
        #* Check for winner
        if gameOver(gameBoard, rMoveTimeList, bMoveTimeList): break

        #* R's Turn
        if verbose:
            print("\nR Turn:")
            print(gameBoard)
        moveTime = Timer()
        gameBoard, action = red.play(board=gameBoard)  #make move
        rMoveTimeList.append(
            moveTime.elapsed_s())  # create a list of move times
        move += 1
        if verbose:
            print("move", move, "by r:", gameBoard.get_action_str(action),
                  " Result:")
            print(gameBoard)
            print("Time - move:", round(rMoveTimeList[-1], 2), "s, game:",
                  round(gameTime.elapsed_min(), 2), "min")

        #* Check for winner
        if gameOver(gameBoard, rMoveTimeList, bMoveTimeList): break

        #* B's Turn
        if verbose:
            print("\nB Turn:")
            print(gameBoard)
        moveTime = Timer()
        gameBoard, action = black.play(board=gameBoard)  #make move
        bMoveTimeList.append(moveTime.elapsed_s())  #add move time to list
        move += 1
        if verbose:
            print("move", move, "by b:", gameBoard.get_action_str(action),
                  " Result:")
            print(gameBoard)
            print("Time - move:", round(bMoveTimeList[-1], 2), "s, game:",
                  round(gameTime.elapsed_min(), 2), "min")
def init_starts():
    """Set up a list of starting moves"""

    start.append((checkerboard.CheckerBoard(), ([(2, 5), (3, 4)], [(5, 2),
                                                                   (4, 3)])))
    # Initial board

    #           0  1  2  3  4  5  6  7
    #        0  .  b  .  b  .  b  .  b
    #        1  b  .  b  .  b  .  b  .
    #        2  .  b  .  b  .  .  .  b
    #        3  .  .  .  .  b  .  .  .
    #        4  .  .  .  .  .  .  .  .
    #        5  r  .  r  .  r  .  r  .
    #        6  .  r  .  r  .  r  .  r
    #        7  r  .  r  .  r  .  r  .
    b = checkerboard.CheckerBoard()
    b.place(2, 5, None)
    b.place(3, 4, 'b')
    b.recount_pieces()  # Update pawn/king counts
    start.append((b, [(5, 2), (4, 1)]))

    #           0  1  2  3  4  5  6  7
    #        0  .  b  .  b  .  b  .  b
    #        1  b  .  b  .  b  .  b  .
    #        2  .  b  .  b  .  b  .  b
    #        3  .  .  .  .  .  .  .  .
    #        4  .  .  .  r  .  .  .  .
    #        5  r  .  .  .  r  .  r  .
    #        6  .  r  .  r  .  r  .  r
    #        7  r  .  r  .  r  .  r  .
    b = checkerboard.CheckerBoard()
    b.place(5, 2, None)
    b.place(4, 3, 'r')
    b.recount_pieces()  # Update pawn/king counts
    start.append((b, [(2, 5), (3, 6)]))

    #           0  1  2  3  4  5  6  7
    #        0  .  b  .  b  .  b  .  b
    #        1  b  .  b  .  b  .  b  .
    #        2  .  .  .  b  .  b  .  b
    #        3  .  .  b  .  .  .  .  .
    #        4  .  .  .  .  .  .  .  .
    #        5  r  .  r  .  r  .  r  .
    #        6  .  r  .  r  .  r  .  r
    #        7  r  .  r  .  r  .  r  .
    b = checkerboard.CheckerBoard()
    b.place(2, 1, None)
    b.place(3, 2, 'b')
    b.recount_pieces()  # Update pawn/king counts
    start.append((b, [(2, 5), (3, 4)]))

    #           0  1  2  3  4  5  6  7
    #        0  .  b  .  b  .  b  .  b
    #        1  b  .  b  .  b  .  b  .
    #        2  .  b  .  b  .  b  .  b
    #        3  .  .  .  .  .  .  .  .
    #        4  .  .  .  .  .  r  .  .
    #        5  r  .  r  .  r  .  .  .
    #        6  .  r  .  r  .  r  .  r
    #        7  r  .  r  .  r  .  r  .
    b = checkerboard.CheckerBoard()
    b.place(5, 6, None)
    b.place(4, 5, 'r')
    b.recount_pieces()  # Update pawn/king counts
    start.append((b, [(5, 2), (4, 3)]))

    #           0  1  2  3  4  5  6  7
    #        0  .  b  .  b  .  b  .  b
    #        1  b  .  b  .  b  .  b  .
    #        2  .  b  .  b  .  .  .  b
    #        3  .  .  .  .  .  .  b  .
    #        4  .  .  .  .  .  .  .  .
    #        5  r  .  r  .  r  .  r  .
    #        6  .  r  .  r  .  r  .  r
    #        7  r  .  r  .  r  .  r  .
    b = checkerboard.CheckerBoard()
    b.place(2, 5, None)
    b.place(3, 6, 'b')
    b.recount_pieces()  # Update pawn/king counts
    start.append((b, [(2, 3), (3, 4)]))

    #           0  1  2  3  4  5  6  7
    #        0  .  b  .  b  .  b  .  b
    #        1  b  .  b  .  b  .  b  .
    #        2  .  b  .  b  .  b  .  b
    #        3  .  .  .  .  .  .  .  .
    #        4  .  r  .  .  .  .  .  .
    #        5  r  .  .  .  r  .  r  .
    #        6  .  r  .  r  .  r  .  r
    #        7  r  .  r  .  r  .  r  .
    b = checkerboard.CheckerBoard()
    b.place(5, 2, None)
    b.place(4, 1, 'r')
    b.recount_pieces()  # Update pawn/king counts
    start.append((b, [(5, 4), (4, 3)]))

    #           0  1  2  3  4  5  6  7
    #        0  .  b  .  b  .  b  .  b
    #        1  b  .  b  .  b  .  b  .
    #        2  .  b  .  .  .  b  .  b
    #        3  .  .  .  .  b  .  .  .
    #        4  .  .  .  .  .  .  .  .
    #        5  r  .  r  .  r  .  r  .
    #        6  .  r  .  r  .  r  .  r
    #        7  r  .  r  .  r  .  r  .
    b = checkerboard.CheckerBoard()
    b.place(2, 3, None)
    b.place(3, 4, 'b')
    b.recount_pieces()  # Update pawn/king counts
    start.append((b, [(2, 7), (3, 6)]))

    #           0  1  2  3  4  5  6  7
    #        0  .  b  .  b  .  b  .  b
    #        1  b  .  b  .  b  .  b  .
    #        2  .  b  .  b  .  b  .  b
    #        3  .  .  .  .  .  .  .  .
    #        4  .  .  .  r  .  .  .  .
    #        5  r  .  r  .  .  .  r  .
    #        6  .  r  .  r  .  r  .  r
    #        7  r  .  r  .  r  .  r  .
    b = checkerboard.CheckerBoard()
    b.place(5, 4, None)
    b.place(4, 3, 'r')
    b.recount_pieces()  # Update pawn/king counts
    start.append((b, [(5, 0), (4, 1)]))

    #           0  1  2  3  4  5  6  7
    #        0  .  b  .  b  .  b  .  b
    #        1  b  .  b  .  b  .  b  .
    #        2  .  b  .  .  .  b  .  b
    #        3  .  .  b  .  .  .  .  .
    #        4  .  .  .  .  .  .  .  .
    #        5  r  .  r  .  r  .  r  .
    #        6  .  r  .  r  .  r  .  r
    #        7  r  .  r  .  r  .  r  .
    b = checkerboard.CheckerBoard()
    b.place(2, 3, None)
    b.place(3, 2, 'b')
    b.recount_pieces()  # Update pawn/king counts
    start.append((b, [(2, 1), (3, 2)]))

    #           0  1  2  3  4  5  6  7
    #        0  .  b  .  b  .  b  .  b
    #        1  b  .  b  .  b  .  b  .
    #        2  .  b  .  b  .  b  .  b
    #        3  .  .  .  .  .  .  .  .
    #        4  .  .  .  .  .  r  .
    #        5  r  .  r  .  .  .  r  .
    #        6  .  r  .  r  .  r  .  r
    #        7  r  .  r  .  r  .  r  .
    b = checkerboard.CheckerBoard()
    b.place(5, 4, None)
    b.place(4, 5, 'r')
    b.recount_pieces()  # Update pawn/king counts
    start.append((b, [(5, 6), (4, 5)]))

    #           0  1  2  3  4  5  6  7
    #        0  .  b  .  b  .  b  .  b
    #        1  b  .  b  .  b  .  b  .
    #        2  .  b  .  b  .  b  .  .
    #        3  .  .  .  .  .  .  b  .
    #        4  .  .  .  .  .  .  .  .
    #        5  r  .  r  .  r  .  r  .
    #        6  .  r  .  r  .  r  .  r
    #        7  r  .  r  .  r  .  r  .
    b = checkerboard.CheckerBoard()
    b.place(2, 7, None)
    b.place(3, 6, 'b')
    b.recount_pieces()  # Update pawn/king counts
    start.append((b, [(2, 1), (3, 0)]))

    #           0  1  2  3  4  5  6  7
    #        0  .  b  .  b  .  b  .  b
    #        1  b  .  b  .  b  .  b  .
    #        2  .  b  .  b  .  b  .  b
    #        3  .  .  .  .  .  .  .  .
    #        4  .  r  .  .  .  .  .  .
    #        5  .  .  r  .  r  .  r  .
    #        6  .  r  .  r  .  r  .  r
    #        7  r  .  r  .  r  .  r  .
    b = checkerboard.CheckerBoard()
    b.place(5, 0, None)
    b.place(4, 1, 'r')
    b.recount_pieces()  # Update pawn/king counts
    start.append((b, [(5, 6), (4, 7)]))

    #           0  1  2  3  4  5  6  7
    #        0  .  b  .  b  .  b  .  b
    #        1  b  .  b  .  b  .  b  .
    #        2  .  .  .  b  .  b  .  b
    #        3  b  .  .  .  .  .  .  .
    #        4  .  .  .  .  .  .  .  .
    #        5  r  .  r  .  r  .  r  .
    #        6  .  r  .  r  .  r  .  r
    #        7  r  .  r  .  r  .  r  .
    b = checkerboard.CheckerBoard()
    b.place(2, 1, None)
    b.place(3, 0, 'b')
    b.recount_pieces()  # Update pawn/king counts
    start.append((b, [(2, 5), (3, 4)]))

    #           0  1  2  3  4  5  6  7
    #        0  .  b  .  b  .  b  .  b
    #        1  b  .  b  .  b  .  b  .
    #        2  .  b  .  b  .  b  .  b
    #        3  .  .  .  .  .  .  .  .
    #        4  .  .  .  .  .  .  .  r
    #        5  r  .  r  .  r  .  .  .
    #        6  .  r  .  r  .  r  .  r
    #        7  r  .  r  .  r  .  r  .
    b = checkerboard.CheckerBoard()
    b.place(5, 6, None)
    b.place(4, 7, 'r')
    b.recount_pieces()  # Update pawn/king counts
    start.append((b, [(5, 2), (4, 3)]))
def main():
    mycheckerboard = checkerboard.CheckerBoard()
    print("testing")
    print(mycheckerboard.get_pawnsN())
def Game(red=ai.Strategy,
         black=tonto.Strategy,
         maxplies=2,
         init=None,
         verbose=True,
         firstmove=0):
    """Game function for playing checkers"""
    # Initialize variables and data structures
    movenum, lastcap, pawn_move, count = 1, 0, 0, 0
    movetimes = [[], []]
    players = ['r', 'b']
    # Define board and instances of the strategy and dictionarys for the players
    board = checkerboard.CheckerBoard()
    redplayer, blackplayer = red('r', board,
                                 maxplies), black('b', board, maxplies)
    player_strategies = {'r': redplayer, 'b': blackplayer}
    strategies = {'r': "AI", 'b': "tonto"}

    # print out games initial information
    print("Invoked Game(", "red=", redplayer.__module__, ".Strategy", ",",
          "black=", blackplayer.__module__, ".Strategy", ",", "maxplies =",
          maxplies, ")\n\n")
    print("How about a nice game of checkers?")

    # Determine which player starts the game
    current_player = players[firstmove]

    tm = Timer()  # Timer for game in minutes
    time_min = 0
    finished = False
    while not finished:  # While game is not finished keep looping
        # Check if the game is over
        terminal, winner = board.is_terminal()
        if terminal:
            gameover(movetimes, winner, time_min)
            return

        print("Player", current_player, "turn")
        print(board)
        if current_player == players[0]:
            print(current_player, "thinking using",
                  strategies.get(current_player), "strategy...")

        t = Timer()  # Timer for player moves
        move = player_strategies.get(current_player).play(
            board)  # get action from current player strategy
        piece = board.get(move[1][0][0], move[1][0][1])
        # determine if the move is from a pawn
        if board.ispawn(piece):
            pawn_move = 0
        else:
            pawn_move += 1

        action_str = board.get_action_str(
            move[1])  # get action string then display data
        if len(action_str) > 23:  # Check if there is a capture
            lastcap = 0
        else:
            lastcap += 1

        print("move", movenum, "by", current_player, ":", action_str,
              " Result:")
        board = board.move(move[1])
        movenum += 1
        ts = round(t.elapsed_s(), 2)
        if current_player == players[0]:
            movetimes[0].append(ts)
        else:
            movetimes[1].append(ts)
        time_min = round(tm.elapsed_min(), 2)

        # Display data from the action and about the state of the game
        print(board)
        print("Pawn/King count: r",
              board.get_pawnsN()[0], "R",
              board.get_kingsN()[0], "b",
              board.get_pawnsN()[1], "B",
              board.get_kingsN()[1], "Time - move:", ts, "s", "game", time_min,
              "m")
        print("Moves since last capture", lastcap, "last pawn advance",
              pawn_move, "\n")
        current_player = board.other_player(current_player)
Example #16
0
def Game(red=ai.Strategy,
         black=tonto.Strategy,
         maxplies=3,
         init=None,
         verbose=True,
         firstmove=0):
    """Game(red, black, maxplies, init, verbose, turn)
    Start a game of CS550Assignment3
    red,black - Strategy classes (not instances)
    maxplies - # of turns to explore (default 10)
    init - Start with given board (default None uses a brand new game)
    verbose - Show messages (default True)
    firstmove - Player N starts 0 (red) or 1 (black).  Default 0. 
    """

    # Don't forget to create instances of your strategy,
    # e.g. black('b', checkerboard.CheckerBoard, maxplies)

    print(
        "================================ Checkers ================================="
    )
    print(
        "CS 550 Artificial Intelligence | Prof. Roch | Assignment 3 | kingofthenorth"
    )
    print(
        "============================= Creating game... ============================"
    )

    game_board = checkerboard.CheckerBoard()
    red_player = red('r', game_board, maxplies)
    black_player = black('b', game_board, maxplies)
    turn_counter = 1
    players = [red_player, black_player]
    game_start = time.time()

    while True:
        turn_start = time.time()

        turn_counter = turn_counter % 2 - 1

        game_board = players[turn_counter].play(game_board)[0]
        print("RED MADE A MOVE!\n", game_board)

        current = time.time()

        print("Turn time: {} | Game time: {}".format(
            elapsed(turn_start, current), elapsed(game_start, current)))

        turn_start = time.time()

        turn_counter = turn_counter % 2 - 1

        game_board = players[turn_counter].play(game_board)[0]
        print("BLACK MADE A MOVE!\n", game_board)

        current = time.time()

        print("Turn time: {} | Game time: {}".format(
            elapsed(turn_start, current), elapsed(game_start, current)))

        if game_board.is_terminal()[0]:
            print("Game finished!\n")
            break