예제 #1
0
 def test_3(self):
     bstr = "...o......,....x.....,.....x....,..o...o..."
     b = Board()
     b.set_board(bstr)
     self.assertCountEqual([(3, 0, Checker(BLACK)), (2, 3, Checker(BLACK)),
                            (6, 3, Checker(BLACK)), (4, 1, Checker(WHITE)),
                            (5, 2, Checker(WHITE))], b.get_checkers())
예제 #2
0
 def test5(self):
     b = Board()
     b.set_board(",.o.o......,..x.......,,,,,,,")
     moves = str(b.legal_moves())
     # note: promotion happens after move is pushed, not when listing legal moves
     self.assertEqual(
         moves, "[[Move<x,f(2, 2),t(0, 0)>], [Move<x,f(2, 2),t(4, 0)>]]")
예제 #3
0
def runGame():
    pygame.init()
    screen = pygame.display.set_mode(size)
    board = Board()

    selected = None
    team = False
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            elif event.type == pygame.MOUSEBUTTONDOWN:
                pos = event.dict['pos']
                
                # convert to i,j
                i,j = pos[0]//dx, pos[1]//dy
                
                # check if this matches an actual piece
                if board.grid[i][j] is not None and board.grid[i][j].color == team:
                    selected = (i,j)
                    
            elif event.type == pygame.MOUSEBUTTONUP and selected is not None:
                pos = event.dict['pos']
                
                # convert to i,j
                i,j = pos[0]//dx, pos[1]//dy
                if board.executeMove(selected, (i,j)):
                    team = not team
                selected = None
            
            drawBoard(screen, team, board, selected)
            pygame.display.flip()
예제 #4
0
 def test_middle(self):
     # This is correct becuase implementation doesn't actually check if all checkers are on black fields only
     # (as it's per rules of checkers).
     bstr = ",,,,...xoxo...,...oxox...,,,,"
     b = Board()
     b.set_board(bstr)
     self.assertEqual(bstr, b.get_board())
예제 #5
0
 def test_1(self):
     bstr = "x"
     b = Board()
     b.set_board(bstr)
     # https://docs.python.org/3.2/library/unittest.html#unittest.TestCase.assertCountEqual
     # tests if list have same elements
     self.assertCountEqual([(0, 0, Checker(WHITE))], b.get_checkers())
예제 #6
0
 def test8(self):
     b = Board()
     b.set_board(",...o.o....,,...o......,....x.....,...o......,,,,")
     moves = str(b.legal_moves())
     self.assertEqual(
         moves,
         "[[Move<x,f(4, 4),t(2, 2)>, Move<x,f(2, 2),t(4, 0)>, Move<x,f(4, 0),t(6, 2)>]]"
     )
예제 #7
0
 def test1(self):
     b = Board()
     b.set_board(",.x,,.x,,,,,........o,")
     moves = str(b.legal_moves())
     # note: promotion happens after move is pushed, not when listing legal moves
     self.assertEqual(
         moves, "[[Move<x,f(1, 1),t(0, 0)>], [Move<x,f(1, 1),t(2, 0)>], "
         "[Move<x,f(1, 3),t(0, 2)>], [Move<x,f(1, 3),t(2, 2)>]]")
예제 #8
0
 def test_move_king_white(self):
     b = Board()
     b.set_board(",,.......X")
     self.assertEqual(
         "[[Move<X,f(7, 2),t(6, 1)>], [Move<X,f(7, 2),t(5, 0)>], [Move<X,f(7, 2),t(8, 1)>], "
         "[Move<X,f(7, 2),t(9, 0)>], [Move<X,f(7, 2),t(6, 3)>], [Move<X,f(7, 2),t(5, 4)>], "
         "[Move<X,f(7, 2),t(4, 5)>], [Move<X,f(7, 2),t(3, 6)>], [Move<X,f(7, 2),t(2, 7)>], "
         "[Move<X,f(7, 2),t(1, 8)>], [Move<X,f(7, 2),t(0, 9)>], [Move<X,f(7, 2),t(8, 3)>], "
         "[Move<X,f(7, 2),t(9, 4)>]]", str(b.legal_moves()))
예제 #9
0
 def test_longest_chain(self):
     b = Board()
     b.set_board(
         ",...,.o.o,.....,.o...o,.......,...o...o,....x....,.o.o,...")
     self.assertEqual(
         "[[Move<x,f(4, 7),t(2, 5)>, Move<x,f(2, 5),t(0, 3)>, "
         "Move<x,f(0, 3),t(2, 1)>, Move<x,f(2, 1),t(4, 3)>, "
         "Move<x,f(4, 3),t(6, 5)>, Move<x,f(6, 5),t(8, 7)>]]",
         str(b.legal_moves()))
예제 #10
0
 def test_crowned_double_jump(self):
     b = Board()
     b.set_board(",,......o...,,....o.....,,....o.....,,..X.......,")
     self.assertEqual(
         "[[Move<X,f(2, 8),t(5, 5)>, Move<X,f(5, 5),t(3, 3)>], "
         "[Move<X,f(2, 8),t(5, 5)>, Move<X,f(5, 5),t(2, 2)>], "
         "[Move<X,f(2, 8),t(5, 5)>, Move<X,f(5, 5),t(1, 1)>], "
         "[Move<X,f(2, 8),t(5, 5)>, Move<X,f(5, 5),t(0, 0)>], "
         "[Move<X,f(2, 8),t(7, 3)>, Move<X,f(7, 3),t(5, 1)>], "
         "[Move<X,f(2, 8),t(7, 3)>, Move<X,f(7, 3),t(4, 0)>]]",
         str(b.legal_moves()))
예제 #11
0
 def test_turns(self):
     b = Board()
     self.assertTrue(b.color)
     b.legal_moves()
     self.assertTrue(b.color)
     b.legal_moves()[0]
     self.assertTrue(b.color)
     b.push(b.legal_moves()[0])
     self.assertTrue(not b.color)
예제 #12
0
def main():
    run = True
    clock = pygame.time.Clock()
    board = Board()

    while run:
        clock.tick(FPS)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
            if event.type == pygame.MOUSEBUTTONDOWN:
                pass

        board.draw_squares(WIN)
        pygame.display.update()
    pygame.quit()
예제 #13
0
파일: server.py 프로젝트: YGeeneY/Checkers
 def open(self, game_id):
     room = rooms.get(game_id, False)
     self.game_id = game_id
     if not room:
         rooms[game_id] = dict(game=Board(), clients=[self])
     else:
         rooms[game_id]['clients'].append(self)
     self.write_message(json.dumps(rooms[game_id]['game'].serialize()))
예제 #14
0
def allowed_moves(board, color):
    b = Board(8)
    initialize(b, board)
    if color == 'b':
        color = 'black'
    else:
        color = 'white'
    hints = get_hints(b, color)
    hints = convert_positions(hints)
    return (hints)
예제 #15
0
 def test_two_double_jumps(self):
     b = Board()
     b.set_board(",...o.o,,...o,..x")
     self.assertEqual(
         "[[Move<x,f(2, 4),t(4, 2)>, Move<x,f(4, 2),t(2, 0)>], "
         "[Move<x,f(2, 4),t(4, 2)>, Move<x,f(4, 2),t(6, 0)>]]",
         str(b.legal_moves()))
     self.assertIsNotNone(b.checker_at(3, 3))
     self.assertIsNotNone(b.checker_at(3, 1))
     self.assertIsNotNone(b.checker_at(5, 1))
예제 #16
0
 def test_move_black(self):
     b = Board()
     b.set_board(",,....o")
     b.color = checkers.BLACK
     self.assertEqual(
         "[[Move<o,f(4, 2),t(3, 3)>], [Move<o,f(4, 2),t(5, 3)>]]",
         str(b.legal_moves()))
예제 #17
0
def _board_value(board: Board, color: bool) -> int:
    """
    Returns value of the board. Value is calculated as +1 for each checker of given color and -1 for each checker of
    other color.
    :param board:
    :param color:
    :return:
    """
    total = 1
    for (x, y, checker) in board.get_checkers():
        total += (+1 if checker.color == color else -1) * (5 if checker.crowned
                                                           else 1)
    return total
예제 #18
0
 def test2(self):
     b = Board()
     b.set_board(",.o........,,.o........,,,,,........x.,")
     b.color = False
     moves = str(b.legal_moves())
     self.assertEqual(
         moves, "[[Move<o,f(1, 1),t(0, 2)>], [Move<o,f(1, 1),t(2, 2)>], "
         "[Move<o,f(1, 3),t(0, 4)>], [Move<o,f(1, 3),t(2, 4)>]]")
예제 #19
0
    def test_complicated_circle_chain(self):
        b = Board()
        b.set_board(",.o.o.o....,,.o.o......,..x")

        ch1 = "[Move<x,f(2, 4),t(0, 2)>, Move<x,f(0, 2),t(2, 0)>, Move<x,f(2, 0),t(4, 2)>, Move<x,f(4, 2),t(2, 4)>]"
        ch2 = "[Move<x,f(2, 4),t(0, 2)>, Move<x,f(0, 2),t(2, 0)>, Move<x,f(2, 0),t(4, 2)>, Move<x,f(4, 2),t(6, 0)>]"
        ch3 = "[Move<x,f(2, 4),t(4, 2)>, Move<x,f(4, 2),t(2, 0)>, Move<x,f(2, 0),t(0, 2)>, Move<x,f(0, 2),t(2, 4)>]"

        self.assertEqual("[" + ch1 + ", " + ch2 + ", " + ch3 + "]",
                         str(b.legal_moves()))
        self.assertIsNotNone(b.checker_at(1, 3))
        self.assertIsNotNone(b.checker_at(3, 3))
        self.assertIsNotNone(b.checker_at(1, 1))
        self.assertIsNotNone(b.checker_at(3, 1))
        self.assertIsNotNone(b.checker_at(5, 1))
예제 #20
0
def alpha_beta_search(board: Board, max_depth: int) -> Move:
    """
    Returns best Move for given Board, found by performing minimax algorithm with alpha-beta pruning.
    :param board: Board to start search from
    :param max_depth: Maximum tree depth to search
    :return: best found Move
    """

    # By international checker rules and for given board_value function, board_value has a range of [-20, 20]
    best_move, best_value = None, -INF

    # Perform MAX step explicitly, storing best move and it's value
    player_color = True
    for move in board.legal_moves():
        board.push(move)
        value = _alpha_beta(board, {}, player_color, max_depth, -INF, +INF,
                            MAX)
        board.pop()

        if value > best_value:
            best_move = move

    return best_move
예제 #21
0
 def test_move_two_kings_white(self):
     b = Board()
     b.set_board(".......X.X")
     wc = Checker(WHITE, True)  # white, crowned checker (X)
     self.assertCountEqual([
         [Move(wc, (7, 0), (6, 1))],
         [Move(wc, (7, 0), (5, 2))],
         [Move(wc, (7, 0), (4, 3))],
         [Move(wc, (7, 0), (3, 4))],
         [Move(wc, (7, 0), (2, 5))],
         [Move(wc, (7, 0), (1, 6))],
         [Move(wc, (7, 0), (0, 7))],
         [Move(wc, (7, 0), (8, 1))],
         [Move(wc, (7, 0), (9, 2))],
         [Move(wc, (9, 0), (8, 1))],
         [Move(wc, (9, 0), (7, 2))],
         [Move(wc, (9, 0), (6, 3))],
         [Move(wc, (9, 0), (5, 4))],
         [Move(wc, (9, 0), (4, 5))],
         [Move(wc, (9, 0), (3, 6))],
         [Move(wc, (9, 0), (2, 7))],
         [Move(wc, (9, 0), (1, 8))],
         [Move(wc, (9, 0), (0, 9))],
     ], b.legal_moves())
예제 #22
0
 def test_move_king_black_blocked(self):
     b = Board()
     b.set_board(",,.....O....,,...o......,........o.")
     b.color = checkers.BLACK
     self.assertEqual(
         "[[Move<O,f(5, 2),t(4, 1)>], [Move<O,f(5, 2),t(3, 0)>], [Move<O,f(5, 2),t(6, 1)>], "
         "[Move<O,f(5, 2),t(7, 0)>], [Move<O,f(5, 2),t(4, 3)>], [Move<O,f(5, 2),t(6, 3)>], "
         "[Move<O,f(5, 2),t(7, 4)>], [Move<o,f(3, 4),t(2, 5)>], [Move<o,f(3, 4),t(4, 5)>], "
         "[Move<o,f(8, 5),t(7, 6)>], [Move<o,f(8, 5),t(9, 6)>]]",
         str(b.legal_moves()))
예제 #23
0
def get_state(move: Move, board: Board):
    board.push(move)
    n_our_un_crwn_pices = board.get_board().count(our_pics)
    n_their_un_crwn_pices = board.get_board().count(their_pics)
    n_our_king = board.get_board().count(our_kings)
    n_their_king = board.get_board().count(their_kings)
    n_pcs_on_edge = get_pics_on_edge(our_pics, our_kings, board)
    own_center_of_mass = 0
    their_center_of_mass = 0

    board.pop()

    return State(n_our_un_crwn_pices,
                 n_their_un_crwn_pices,
                 n_our_king,
                 n_their_king,
                 n_pcs_on_edge,
                 own_center_of_mass,
                 their_center_of_mass)
예제 #24
0
 def test_move_king_black_corner(self):
     b = Board()
     b.set_board(",,,,,,,,,.........O")
     b.color = BLACK
     bc = Checker(BLACK, True)
     self.assertCountEqual([
         [Move(bc, (9, 9), (8, 8))],
         [Move(bc, (9, 9), (7, 7))],
         [Move(bc, (9, 9), (6, 6))],
         [Move(bc, (9, 9), (5, 5))],
         [Move(bc, (9, 9), (4, 4))],
         [Move(bc, (9, 9), (3, 3))],
         [Move(bc, (9, 9), (2, 2))],
         [Move(bc, (9, 9), (1, 1))],
         [Move(bc, (9, 9), (0, 0))],
     ], b.legal_moves())
예제 #25
0
def play(board, color):
    """
        Play must return the next move to play.
        You can define here any strategy you would find suitable.
    """
    moves = allowed_moves(board, color)

    # There will always be an allowed move
    # because otherwise the game is over and
    # 'play' would not be called by main.py

    b = Board(8)
    initialize(b, board)
    if color == 'b':
        turn = 'black'
    else:
        turn = 'white'
    choice = get_next_move(b, turn)
    choice = list(choice)
    for i in range(0, len(choice)):
        choice[i] = indexify(choice[i])
    return choice
예제 #26
0
def board_initial():
    """
    An example initial board.
    """
    Piece.symbols = ['b', 'w']
    Piece.symbols_king = ['B', 'W']
    board = Board()
    cells = eval("[[None, 'b', None, 'b', None, 'b', None, 'b'], " + \
        "['b', None, 'b', None, 'b', None, 'b', None], " + \
        "[None, 'b', None, 'b', None, 'b', None, 'b'], " + \
        "[None, None, None, None, None, None, None, None], " + \
        "[None, None, None, None, None, None, None, None], " + \
        "['w', None, 'w', None, 'w', None, 'w', None], " + \
        "[None, 'w', None, 'w', None, 'w', None, 'w'], " + \
        "['w', None, 'w', None, 'w', None, 'w', None]]")
    for row, lst in enumerate(cells):
        for col, item in enumerate(lst):
            if item is not None:
                if item == 'w':
                    board.place(row, col, Piece('white'))
                else:
                    board.place(row, col, Piece())
    return board
예제 #27
0
def game_play_ai():
    """
    
    This is the main mechanism of the human vs. ai game play. You need to
    implement this function by taking helps from the game_play_human() 
    function.
    
    For a given board situation/state, you can call the ai function to get
    the next best move, like this:
        
        move = ai.get_next_move(board, turn)
        
    where the turn variable is a color 'black' or 'white', also you need to 
    import ai module as 'import gameai as ai' at the beginning of the file.
    This function will be very similar to game_play_human().
    # UNCOMMENT THESE TWO LINES TO TEST ON MIMIR SUBMISSION
    This is the main mechanism of the human vs. human game play.
    Use this function to write the game_play_ai() function.
    
    """

    # UNCOMMENT THESE TWO LINES TO TEST ON MIMIR SUBMISSION
    Piece.symbols = ['b', 'w']
    Piece.symbols_king = ['B', 'W']

    prompt = "[{:s}'s turn] :> "

    print(tools.banner)

    # Choose the color here
    (my_color, opponent_color) = tools.choose_color()

    # Take a board of size 8x8
    board = Board(8)
    initialize(board)

    # Decide on whose turn, use a variable called 'turn'.

    turn = my_color if my_color == 'black' else opponent_color
    print("Black always plays first.\n")

    # 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)

            # =============================================================================
            #                        Modififications from the game_play_human
            #                                Changes starts HERE
            # =============================================================================

            if turn == my_color:

                command = input(prompt.format(turn)).strip().lower()

            else:

                move = ai.get_next_move(board, turn)

                if type(move) == tuple:

                    command = "move {:s} {:s}".format(move[0], move[1])

                else:
                    command = "jump {:s}".format(" ".join([b for b in move]))
                command = command.strip().lower()

            # Now decide on different commands

            if command == 'pass':
                break
            elif command == 'exit':
                break
            elif command == 'hints':
                (moves, captures) = get_hints(board, turn, True)
                if moves:
                    print("You have moves:")
                    for i, move in enumerate(moves):
                        print("\t{:d}: {:s} --> {:s}"\
                                  .format(i + 1, move[0], move[1]))
                if captures:
                    print("You have captures:")
                    for i, path in enumerate(captures):
                        print("\t{:d}: {:s}".format(i + 1, str(path)))
            else:
                command = [s.strip().lower() for s in command.split()]
                (moves, captures) = get_hints(board, turn, True)

                action = None
                if command and command[0] == 'move' and len(command) == 3:
                    if not captures:
                        action = (command[1], command[2])
                        if action in moves:
                            apply_move(board, action)
                        else:
                            raise RuntimeError(move_error)
                    else:
                        raise RuntimeError(hasjump_error)
                elif command and command[0] == 'jump' and len(command) >= 3:
                    action = command[1:]
                    if action in captures:
                        apply_capture(board, action)
                    else:
                        raise RuntimeError(jump_error)
                elif command and command[0] == 'apply' and len(command) == 2:
                    id_hint = int(command[1])
                    if moves and (1 <= id_hint <= len(moves)):
                        action = moves[id_hint - 1]
                        apply_move(board, action)
                    elif captures and (1 <= id_hint <= len(captures)):
                        action = captures[id_hint - 1]
                        apply_capture(board, action)
                    else:
                        raise ValueError(hint_error)
                else:
                    raise RuntimeError(cmd_error + tools.usage)
                print("\t{:s} played {:s}.".format(turn, str(action)))
                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)
    if command != 'pass':
        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.")
    else:
        winner = opponent_color if turn == my_color else my_color
        print("{:s} gave up! {:s} is the winner!! yay!!!".format(turn, winner))
예제 #28
0
def game_play_human():
    """
    This is the main mechanism of the human vs. human game play.
    Use this function to write the game_play_ai() function.
    """
    # UNCOMMENT THESE TWO LINES TO TEST ON MIMIR SUBMISSION
    Piece.symbols = ['b', 'w']
    Piece.symbols_king = ['B', 'W']

    prompt = "[{:s}'s turn] :> "
    print(tools.banner)

    # Choose the color here
    (my_color, opponent_color) = tools.choose_color()

    # Take a board of size 8x8
    board = Board(8)
    initialize(board)

    # Decide on whose turn, use a variable called 'turn'.
    turn = my_color if my_color == 'black' else opponent_color
    print("Black always plays first.\n")

    # 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 the command from user using input
            command = input(prompt.format(turn)).strip().lower()

            # Now decide on different commands
            if command == 'pass':
                break
            elif command == 'exit':
                break
            elif command == 'hints':
                (moves, captures) = get_hints(board, turn, True)
                if moves:
                    print("You have moves:")
                    for i, move in enumerate(moves):
                        print("\t{:d}: {:s} --> {:s}"\
                                  .format(i + 1, move[0], move[1]))
                if captures:
                    print("You have captures:")
                    for i, path in enumerate(captures):
                        print("\t{:d}: {:s}".format(i + 1, str(path)))
            else:
                command = [s.strip().lower() for s in command.split()]
                (moves, captures) = get_hints(board, turn, True)
                action = None
                if command and command[0] == 'move' and len(command) == 3:
                    if not captures:
                        action = (command[1], command[2])
                        if action in moves:
                            apply_move(board, action)
                        else:
                            raise RuntimeError(move_error)
                    else:
                        raise RuntimeError(hasjump_error)
                elif command and command[0] == 'jump' and len(command) >= 3:
                    action = command[1:]
                    if action in captures:
                        apply_capture(board, action)
                    else:
                        raise RuntimeError(jump_error)
                elif command and command[0] == 'apply' and len(command) == 2:
                    id_hint = int(command[1])
                    if moves and (1 <= id_hint <= len(moves)):
                        action = moves[id_hint - 1]
                        apply_move(board, action)
                    elif captures and (1 <= id_hint <= len(captures)):
                        action = captures[id_hint - 1]
                        apply_capture(board, action)
                    else:
                        raise ValueError(hint_error)
                else:
                    raise RuntimeError(cmd_error + tools.usage)
                print("\t{:s} played {:s}.".format(turn, str(action)))
                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)
    if command != 'pass':
        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.")
    else:
        winner = opponent_color if turn == my_color else my_color
        print("{:s} gave up! {:s} is the winner!! yay!!!".format(turn, winner))
예제 #29
0
 def test_turns2(self):
     b = Board()
     b.set_board(",...o.o,,...o,..x")
     self.assertTrue(b.color)
     b.legal_moves()
     self.assertTrue(b.color)
     b.legal_moves()[0]
     self.assertTrue(b.color)
     b.push(b.legal_moves()[0])
     self.assertTrue(not b.color)
예제 #30
0
 def test_simple(self):
     bstr = ".x.x.x.x.x,x.x.x.x.x.,,,,,,,.o.o.o.o.o,o.o.o.o.o."
     b = Board()
     b.set_board(bstr)
     self.assertEqual(bstr, b.get_board())
예제 #31
0
 
 if not args.server and not args.client:
     print("You must choose to run as either a client or server!")
     sys.exit(0)
 
 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 clientsock = None
 
 # set up pygame
 pygame.init()
 screen = pygame.display.set_mode(size)
 selected = None
 team = False
 
 # initialize board
 board = Board()
 
 myteam = not args.server
 
 # set up sockety things
 if args.server:
     print("Running as server @ %s:%s" % (args.address, args.port))
     sock.bind((args.address, args.port))
     
     # get connections
     sock.listen(1)
     (clientsock, addr) = sock.accept()
     print("got a connection")
     clientsock.send(pickle.dumps(board.grid))
 
 elif args.client:
예제 #32
0
 def test_2(self):
     bstr = ".....o"
     b = Board()
     b.set_board(bstr)
     self.assertCountEqual([(5, 0, Checker(BLACK))], b.get_checkers())