コード例 #1
0
    def place_types(self):
        """
        Places available types for each team in the teams respective half of the board
        :return: tuple of list of places with fixed position and a list of pieces with random position
        """
        known_place = []
        # place flags at last row
        for team in (0, 1):
            flag_pos_list = [(i, j) for i in range(0 + team * 4, 1 + team * 4)
                             for j in range(5)]
            index = np.random.choice(range(len(flag_pos_list)),
                                     len(flag_pos_list),
                                     replace=False)
            flag_pos = flag_pos_list[index[0]]
            known_place.append(pieces.Piece(0, team, flag_pos))

            setup_pos = [(i, j) for i in range(0 + team * 3, 2 + team * 3)
                         for j in range(5)]
            setup_pos.remove(flag_pos)
            index = np.random.choice(range(len(setup_pos)),
                                     len(setup_pos),
                                     replace=False)
            for i, piece_type in enumerate(self.types_available):

                known_place.append(
                    pieces.Piece(piece_type, team, setup_pos[index[i]]))
        random_place = []  # random_place is across whole board
        return known_place, random_place
コード例 #2
0
ファイル: main.py プロジェクト: leonardbereska/ministratego
def draw_random_setup(types_available, team, game_dim):
    """
    Draw a random setup from the set of types types_available after placing the flag
    somewhere in the last row of the board of the side of 'team', or behind the obstacle.
    :param types_available: list of types to draw from, integers
    :param team: boolean, 1 or 0 depending on the team
    :return: the setup, in numpy array form
    """

    nr_pieces = len(types_available) - 1
    types_available = [type_ for type_ in types_available if not type_ == 0]
    if game_dim == 5:
        row_offset = 2
    elif game_dim == 7:
        row_offset = 3
    else:
        row_offset = 4
    setup_agent = np.empty((row_offset, game_dim), dtype=object)
    if team == 0:
        flag_positions = [(game_dim - 1, j) for j in range(game_dim)]
        flag_choice = np.random.choice(range(len(flag_positions)), 1)[0]
        flag_pos = game_dim - 1 - flag_positions[flag_choice][
            0], game_dim - 1 - flag_positions[flag_choice][1]
        setup_agent[flag_pos] = pieces.Piece(0, 0, flag_positions[flag_choice])

        types_draw = np.random.choice(types_available,
                                      nr_pieces,
                                      replace=False)
        positions_agent_0 = [(i, j)
                             for i in range(game_dim - row_offset, game_dim)
                             for j in range(game_dim)]
        positions_agent_0.remove(flag_positions[flag_choice])

        for idx in range(nr_pieces):
            pos = positions_agent_0[idx]
            setup_agent[(game_dim - 1 - pos[0], game_dim - 1 -
                         pos[1])] = pieces.Piece(types_draw[idx], 0, pos)
    elif team == 1:
        flag_positions = [(0, j) for j in range(game_dim)]
        flag_choice = np.random.choice(range(len(flag_positions)), 1)[0]
        setup_agent[flag_positions[flag_choice]] = pieces.Piece(
            0, 1, flag_positions[flag_choice])

        types_draw = np.random.choice(types_available,
                                      nr_pieces,
                                      replace=False)
        positions_agent_1 = [(i, j) for i in range(row_offset)
                             for j in range(game_dim)]
        positions_agent_1.remove(flag_positions[flag_choice])

        for idx in range(nr_pieces):
            pos = positions_agent_1[idx]
            setup_agent[pos] = pieces.Piece(types_draw[idx], 1, pos)
    return setup_agent
コード例 #3
0
ファイル: board.py プロジェクト: Borna5356/chess
def main():
    white_pawn = pieces.Piece("pawn", "white", (0, 2), moves.move_pawn)
    white_pieces = [white_pawn]
    black_pawn = pieces.Piece("pawn", "black", (1, 2), moves.move_pawn)
    black_pieces = [black_pawn]
    chess_board = Board(white_pieces, black_pieces)
    chess_board.print_board()
    print()
    white_pawn.make_move(chess_board)
    chess_board.print_board()
    print()
    black_pawn.make_move(chess_board)
    chess_board.print_board()
コード例 #4
0
 def __init__(self):
     self.board = []
     self.w_player = player.Player("white")
     self.b_player = player.Player("black")
     self.turn = "white"
     self.empty = pieces.Piece(-1, -1, "empty")
     self.init_board()
コード例 #5
0
    def __init__(self, width, height, record):
        self.width = width
        self.height = height
        self.start_pos = [height - 2, round(width / 2) - 1]
        self.grid = [[0 for i in range(width)] for j in range(height)]
        if not config.is_simulation:
            self.BLOCK_LIST = [
                FilledSquare(config.block_width, config.block_height,
                             COLOR_ARRAY[0]),
                FilledSquare(config.block_width, config.block_height,
                             COLOR_ARRAY[1]),
                FilledSquare(config.block_width, config.block_height,
                             COLOR_ARRAY[2]),
                FilledSquare(config.block_width, config.block_height,
                             COLOR_ARRAY[3]),
                FilledSquare(config.block_width, config.block_height,
                             COLOR_ARRAY[4]),
                FilledSquare(config.block_width, config.block_height,
                             COLOR_ARRAY[5]),
                FilledSquare(config.block_width, config.block_height,
                             COLOR_ARRAY[6]),
                FilledSquare(config.block_width, config.block_height,
                             COLOR_ARRAY[7])
            ]

            self.objectGrid = [[self.BLOCK_LIST[0] for i in range(width)]
                               for j in range(height)]
        self.score = 0
        self.record = record
        self.list_form_idx = 0

        self.curr_move_list = []
        self.curr_piece = pieces.Piece(self.grid, self.start_pos,
                                       self.getNextForm())
        self.updateGrid()
コード例 #6
0
ファイル: test_pawn.py プロジェクト: laidlawm/chess
    def test_scan(self):

        # Define position of pawn
        pos = [12, 1]

        # Generate empty chess board
        test_board = board
        test_board.grid = []
        for i in range(16):
            test_board.grid.append([])
            for j in range(16):
                test_board.grid[i].append(
                    Square(False, "b", pieces.Piece("none", "none"), i, j))

        standard_moves = [[pos[0] - 1, pos[1]]]
        other_moves = [[pos[0] - 1, pos[1]], [pos[0] - 2, pos[1]]]

        test_board.grid[pos[0]][pos[1]].piece = pieces.Pawn("W", "Pawn")
        test_board.grid[pos[0]][pos[1]].piece.row = pos[0]
        test_board.grid[pos[0]][pos[1]].piece.col = pos[1]
        #test_board.grid[pos[0]][pos[1]].piece.firstMove = True

        found_moves = test_board.grid[pos[0]][pos[1]].piece.scan()

        #print(found_moves[0].row, ", ", found_moves[0].col)
        assert (pos[0] == found_moves[0].row + 1)
        assert (pos[1] == found_moves[0].col)
コード例 #7
0
    def test_scan(self):

        # King position
        b = board
        b.grid = []
        for i in range(16):
            b.grid[i].append(
                Square(False, "b", pieces.Piece("none", "none"), i, j))
            for j in range(16):
                b.grid[i].append(
                    Square(False, "b", pieces.Piece("none", "none"), i, j))

        #king moves
        king_moves = [[0, 1], [0, -1], [1, 0], [-1, 0], [-1, 1], [1, -1],
                      [1, 1], [-1, -1]]

        # Create the king w/ all possible moves
        b.Grid(3, 3).piece = pieces.King(False, "King")
        b.Grid(3, 3).piece.row = 3
        b.Grid(3, 3).piece.col = 3

        # relative moves
        possible_moves = []
        for i in range(8):
            possible_moves.append([3, 3])
            possible_moves[i][0] += king_moves[i][0]
            possible_moves[i][1] += king_moves[i][1]

        # fetch movies
        availMoves = b.Grid(3, 3).piece.scan()

        given_moves = []
        for move in availMoves:
            given_moves.append([move.row, move.col])

        A = set(map(tuple, possible_moves))
        B = set(map(tuple, given_moves))

        self.assertTrue(A.issubset(B))
        self.assertTrue(B.issubset(A))

        print("F**k")
コード例 #8
0
ファイル: board_test.py プロジェクト: Borna5356/chess
def test_init():
    #setup
    piece = pieces.Piece("pawn", "white", (0, 0), None)
    white_pieces = [piece]
    black_pieces = []

    #invoke
    chess_board = board.Board(white_pieces, black_pieces)

    #analyze
    assert chess_board
コード例 #9
0
def lvl20():  # Level 20 -> 8 moves for perfect score
    board = [
        ".",
        "=",
        "=",
        ".",
        "t",
        ".",
        ".",
        ".",
        "P",
        "=",
        "=",
        "p",
        "T",
        ".",
        ".",
        ".",
    ]
    pcs = [pieces.Piece("p", 2, 3, 2, 0), pieces.Piece("t", 1, 0, 3, 0)]
    return (board, pcs)
コード例 #10
0
def lvl7():
    board = [
        "T",
        ".",
        "=",
        "=",
        "P",
        ".",
        "t",
        "p",
        ".",
        "=",
        "=",
        "=",
        ".",
        "=",
        ".",
        "=",
    ]
    pcs = [pieces.Piece("p", 1, 3, 1, 0), pieces.Piece("t", 1, 2, 0, 0)]
    return (board, pcs)
コード例 #11
0
def lvl5():
    board = [
        "=",
        "t",
        "=",
        "P",
        "=",
        "p",
        "T",
        ".",
        "=",
        ".",
        ".",
        "=",
        ".",
        "=",
        "=",
        ".",
    ]
    pcs = [pieces.Piece("p", 1, 1, 0, 3), pieces.Piece("t", 0, 1, 1, 2)]
    return (board, pcs)
コード例 #12
0
def lvl14():
    board = [
        "T",
        "=",
        "=",
        "=",
        ".",
        "t",
        "=",
        "=",
        ".",
        ".",
        ".",
        "=",
        "p",
        "=",
        ".",
        "P",
    ]
    pcs = [pieces.Piece("p", 3, 0, 3, 3), pieces.Piece("t", 1, 1, 0, 0)]
    return (board, pcs)
コード例 #13
0
def lvl11():
    board = [
        "=",
        "P",
        "=",
        "T",
        ".",
        "t",
        ".",
        ".",
        ".",
        ".",
        "=",
        "p",
        "=",
        ".",
        "=",
        "=",
    ]
    pcs = [pieces.Piece("p", 2, 3, 0, 1), pieces.Piece("t", 1, 1, 0, 3)]
    return (board, pcs)
コード例 #14
0
def lvl25():
    board = [
        ".",
        "t",
        "p",
        ".",
        ".",
        ".",
        "=",
        "=",
        ".",
        ".",
        ".",
        ".",
        "P",
        "T",
        ".",
        "=",
    ]
    pcs = [pieces.Piece("p", 0, 2, 3, 0), pieces.Piece("t", 0, 1, 3, 1)]
    return (board, pcs)
コード例 #15
0
def lvl3():
    board = [
        ".",
        ".",
        ".",
        "P",
        ".",
        ".",
        "T",
        "=",
        "p",
        ".",
        ".",
        "=",
        ".",
        ".",
        ".",
        "t",
    ]
    pcs = [pieces.Piece("p", 2, 0, 0, 3), pieces.Piece("t", 3, 3, 1, 2)]
    return (board, pcs)
コード例 #16
0
def lvl22():  # Level 22 -> 9 moves for perfect score
    board = [
        ".",
        "p",
        ".",
        "=",
        "=",
        "t",
        ".",
        "T",
        "=",
        ".",
        "=",
        "P",
        "=",
        ".",
        "=",
        "=",
    ]
    pcs = [pieces.Piece("p", 0, 1, 2, 3), pieces.Piece("t", 1, 1, 1, 3)]
    return (board, pcs)
コード例 #17
0
def lvl21():  # Level 21 -> 9 moves for perfect score
    board = [
        "T",
        ".",
        "p",
        "t",
        "=",
        ".",
        "=",
        "P",
        "=",
        "=",
        ".",
        ".",
        ".",
        ".",
        "=",
        "=",
    ]
    pcs = [pieces.Piece("p", 0, 2, 1, 3), pieces.Piece("t", 0, 3, 0, 0)]
    return (board, pcs)
コード例 #18
0
def lvl15():
    board = [
        "t",
        ".",
        ".",
        ".",
        ".",
        ".",
        ".",
        "p",
        "P",
        ".",
        ".",
        ".",
        ".",
        "=",
        "=",
        "T",
    ]
    pcs = [pieces.Piece("p", 1, 3, 2, 0), pieces.Piece("t", 0, 0, 3, 3)]
    return (board, pcs)
コード例 #19
0
def lvl19():  # Level 19 -> 8 moves for perfect score
    board = [
        ".",
        "T",
        "=",
        ".",
        "p",
        ".",
        "P",
        ".",
        ".",
        ".",
        ".",
        ".",
        "=",
        ".",
        "t",
        ".",
    ]
    pcs = [pieces.Piece("p", 1, 0, 1, 2), pieces.Piece("t", 3, 2, 0, 1)]
    return (board, pcs)
コード例 #20
0
def lvl18():
    board = [
        ".",
        ".",
        ".",
        ".",
        ".",
        ".",
        "t",
        "T",
        ".",
        ".",
        ".",
        "=",
        "=",
        ".",
        "P",
        "p",
    ]
    pcs = [pieces.Piece("p", 3, 3, 3, 2), pieces.Piece("t", 1, 2, 1, 3)]
    return (board, pcs)
コード例 #21
0
def lvl4():
    board = [
        "P",
        ".",
        "p",
        "=",
        "=",
        "=",
        ".",
        "=",
        "=",
        ".",
        ".",
        ".",
        "t",
        ".",
        "T",
        "=",
    ]
    pcs = [pieces.Piece("p", 0, 2, 0, 0), pieces.Piece("t", 3, 0, 3, 2)]
    return (board, pcs)
コード例 #22
0
def test_move_white_pawn(monkeypatch):
    #setup
    pawn = pieces.Piece("pawn", "white", (1, 0), moves.move_pawn)
    monkeypatch.setattr("sys.stdin", io.StringIO("0 0"))
    white_pieces = [pawn]
    chess_board = board.Board(white_pieces, [])
    expected = (0, 0)

    #invoke
    actual = moves.move_pawn(pawn, chess_board)

    #analyze
    assert expected == actual
コード例 #23
0
def test_move_knight(monkeypatch):
    #setup
    monkeypatch.setattr("sys.stdin", io.StringIO("1 3"))
    knight = pieces.Piece("knight", "black", (1, 0), moves.move_piece)
    white_pieces = [knight]
    chess_board = board.Board(white_pieces, [])
    expected = (3, 1)

    #invoke
    actual = moves.move_piece(knight, chess_board)

    #analyze
    assert expected == actual
コード例 #24
0
def test_queen_vertical(monkeypatch):
    #setup
    queen = pieces.Piece("queen", "white", (1, 0), moves.move_queen)
    monkeypatch.setattr("sys.stdin", io.StringIO("0 4"))
    white_pieces = [queen]
    chess_board = board.Board(white_pieces, [])
    expected = (4, 0)

    #invoke
    actual = moves.move_queen(queen, chess_board)

    #analyze
    assert expected == actual
コード例 #25
0
ファイル: player_test.py プロジェクト: Borna5356/chess
def test_choose_piece(monkeypatch):
    #setup
    monkeypatch.setattr("sys.stdin", io.StringIO("0 0"))
    piece = pieces.Piece("pawn", "white", (0, 0), moves.move_pawn)
    white_pieces = [piece]
    black_pieces = []
    chess_board = board.Board(white_pieces, black_pieces)

    #invoke
    result = player.choose_piece(chess_board)

    #analyze
    assert piece == result
コード例 #26
0
ファイル: game.py プロジェクト: rlgriffin2/chess-ai
 def __init__(self, surface, size):
     self.surface = surface
     self.size = size
     self.game_over = False
     self.board = board.Board(size)
     self.pieces = []
     # the code below is for creating pieces, was most pythonic way of doing it I could think of, still somewhat repetitive
     piece_sprite_dir = Path('piece_sprites/orig')
     for p in piece_sprite_dir.iterdir():
         p = str(p)
         coords = []
         img_file = ''
         if 'white_rook' in p:
             coords = ['a1', 'h1']
             img_file = p
         if 'white_knight' in p:
             coords = ['b1', 'g1']
             img_file = p
         if 'white_bishop' in p:
             coords = ['c1', 'f1']
             img_file = p
         if 'white_queen' in p:
             coords = ['d1']
             img_file = p
         if 'white_king' in p:
             coords = ['e1']
             img_file = p
         if 'white_pawn' in p:
             coords = ['a2', 'b2', 'c2', 'd2', 'e2', 'f2', 'g2', 'h2']
             img_file = p
         if 'black_rook' in p:
             coords = ['a8', 'h8']
             img_file = p
         if 'black_knight' in p:
             coords = ['b8', 'g8']
             img_file = p
         if 'black_bishop' in p:
             coords = ['c8', 'f8']
             img_file = p
         if 'black_queen' in p:
             coords = ['d8']
             img_file = p
         if 'black_king' in p:
             coords = ['e8']
             img_file = p
         if 'black_pawn' in p:
             coords = ['a7', 'b7', 'c7', 'd7', 'e7', 'f7', 'g7', 'h7']
             img_file = p
         for c in coords:
             self.pieces.append(pieces.Piece(c, img_file, self.board.locations, board.Square.size))
             '''
コード例 #27
0
ファイル: peers.py プロジェクト: MechyX/bittorrent-downloader
    def generate_pieces_objects(self):
        logging.info("Initializing... peer lists")
        hashes = self.torrent_dict['info']['pieces']
        piece_length = self.torrent_dict['info']['piece length']
        if 'files' in self.torrent_dict['info']:
            files = self.torrent_dict['info']['files']
            totalLength = sum([file['length'] for file in files])
            self.num_of_pieces = int(math.ceil(float(totalLength) / piece_length))
        else:
            totalLength = self.torrent_dict['info']['length']
            self.num_of_pieces = int(math.ceil(float(totalLength) / piece_length))

        counter = totalLength
        self.total_torrent_length = totalLength
        for i in range(self.num_of_pieces):
            if i == self.num_of_pieces - 1:
                self.pieces.append(pieces.Piece(i, counter, hashes[0:20]))
            else:
                self.pieces.append(pieces.Piece(i, piece_length, hashes[0:20]))
                counter -= piece_length
                hashes = hashes[20:]

        self.current_piece = self.pieces.popleft()
コード例 #28
0
ファイル: peers.py プロジェクト: zzlettle/bittorrent
    def generatePieces(self):
        logging.info("Initalizing... ")
        pieceHashes = self.tracker['info']['pieces']
        pieceLength = self.tracker['info']['piece length']
        if 'files' in self.tracker['info']:
            files = self.tracker['info']['files']
            totalLength = sum([file['length'] for file in files])
            self.numPieces = int(math.ceil(float(totalLength) / pieceLength))
        else:
            totalLength = self.tracker['info']['length']
            self.numPieces = int(math.ceil(float(totalLength) / pieceLength))

        counter = totalLength
        self.totalLength = totalLength
        for i in range(self.numPieces):
            if i == self.numPieces - 1:
                self.pieces.append(pieces.Piece(i, counter, pieceHashes[0:20]))
            else:
                self.pieces.append(
                    pieces.Piece(i, pieceLength, pieceHashes[0:20]))
                counter -= pieceLength
                pieceHashes = pieceHashes[20:]

        self.curPiece = self.pieces.popleft()
コード例 #29
0
    def testScan(self):
        # Generate empty chess board
        b = board
        b.grid = []
        for i in range(16):
            b.grid.append([])
            for j in range(16):
                b.grid[i].append(
                    Square(False, "b", pieces.Piece("none", "none"), i, j))

        # Create a rook at location 3,3
        # This should allow the rook all of its possible moves
        b.Grid(0, 0).piece = pieces.Rook(False, "Rook")
        b.Grid(0, 0).piece.row = 0
        b.Grid(0, 0).piece.col = 0
        availMoves = b.Grid(0, 0).piece.scan()

        self.assertTrue(availMoves == [] or availMoves != [])
コード例 #30
0
ファイル: game.py プロジェクト: leonardbereska/ministratego
    def __init__(self, agent0, agent1, game_size="big"):
        self.game_size = game_size
        self.agents = (agent0, agent1)
        if game_size == "small":
            self.types_available = np.array([0, 1] + [2]*3 + [3]*2 + [10] + [11]*2)
            obstacle_positions = [(2, 2)]
            self.game_dim = 5
        elif game_size == "medium":
            obstacle_positions = [(3, 1), (3, 5)]
            self.types_available = np.array([0, 1] + [2]*5 + [3]*3 + [4]*3 + [5]*2 + [6] + [10] + [11]*4)
            self.game_dim = 7
        else:
            obstacle_positions = [(4, 2), (5, 2), (4, 3), (5, 3), (4, 6), (5, 6), (4, 7), (5, 7)]
            self.types_available = np.array([0, 1] + [2]*8 + [3]*5 + [4]*4 + [5]*4 + [6]*4 +
                                            [7]*3 + [8]*2 + [9]*1 + [10] + [11]*6)
            self.game_dim = 10
        self.board = np.empty((self.game_dim, self.game_dim), dtype=object)
        setup0, setup1 = agent0.setup, agent1.setup

        for idx, piece in np.ndenumerate(setup0):
            if piece is not None:
                piece.hidden = False
                self.board[piece.position] = piece
        for idx, piece in np.ndenumerate(setup1):
            if piece is not None:
                piece.hidden = False
                self.board[piece.position] = piece
        for pos in obstacle_positions:
            obs = pieces.Piece(99, 99, pos)
            obs.hidden = False
            self.board[pos] = obs
        agent0.install_board(self.board, reset=True)
        agent1.install_board(self.board, reset=True)

        self.move_count = 1  # agent 1 starts

        self.deadPieces = []
        dead_piecesdict = dict()
        for type_ in set(self.types_available):
            dead_piecesdict[type_] = 0
        self.deadPieces.append(dead_piecesdict)
        self.deadPieces.append(copy.deepcopy(dead_piecesdict))

        self.battleMatrix = helpers.get_battle_matrix()