Exemplo n.º 1
0
def strtoboard(strdata):
	strdata = strdata.replace(" ", "").split("\n")
	mat = []
	white_plays = None
	for line in strdata:
		line_translated = []
		if "Whiteplays" in line:
			white_plays = True
			continue
		if "Blackplays" in line:
			white_plays = False
			continue

		for c in line:
			if (c == "w"):
				line_translated.append((Piece(Piece_type.white)))
			if (c == "W"):
				line_translated.append((Piece(Piece_type.white_promoted)))
			if (c == "b"):
				line_translated.append((Piece(Piece_type.black)))
			if (c == "B"):
				line_translated.append((Piece(Piece_type.black_promoted)))
			if (c == "_"):
				line_translated.append(None)
		if len(line_translated) > 0:
			mat.append(line_translated)

	if white_plays is None:
		raise ValueError("Board data didn't contain information about who plays")

	return Board(white_plays=white_plays, board_state=[list(reversed(line)) for line in matrix_rotate(mat, 90)])
Exemplo n.º 2
0
def test_constructor():
    """Test the Cell _init__ function"""
    # Test #1
    c1 = Cell(1, 1, 100)
    assert c1.location == (1, 1)
    assert c1.location[0] == 1
    assert c1.location[1] == 1
    assert c1.width == 100
    assert c1.height == 100
    assert c1.x == -2
    assert c1.y == -2
    assert c1.piece is None

    c1.piece = Piece(c1.x, c1.y, c1.width, 1)
    assert c1.piece is not None
    assert c1.piece.player == 1

    # Test #2
    c2 = Cell(3, 2, 200)
    assert c2.location == (3, 2)
    assert c2.location[0] == 3
    assert c2.location[1] == 2
    assert c2.width == 200
    assert c2.height == 200
    assert c2.x == 398
    assert c2.y == 198
    assert c2.piece is None

    c2.piece = Piece(c2.x, c2.y, c1.width, -1)
    assert c2.piece is not None
    assert c2.piece.player == -1
Exemplo n.º 3
0
    def update_board(self, old_row, old_col, new_row, new_col):
        board = self.board
        piece = board[old_row][old_col]
        delta_x = new_row - old_row
        delta_y = new_col - old_col
        all_moves = self.space_available(piece)
        if (new_row, new_col) in [move[0] for move in all_moves]:
            if (delta_x % 2 == 0):
                jumped_x = delta_x // 2
                jumped_y = delta_y // 2
                if (jumped_y == -1 and jumped_x == 1) or \
                        (jumped_y == 1 and jumped_x == -1):
                    board[old_row - jumped_y][old_col - jumped_x] = None
                else:
                    board[old_row + jumped_y][old_col + jumped_x] = None
                if piece.get_type() == 'USER' or \
                   piece.get_type() == 'USER_KING':
                    self.num_cpu_pieces -= 1
                else:
                    self.num_user_pieces -= 1
            board[old_row][old_col] = None
            piece.set_location(new_row, new_col)

            if piece.get_type() == 'USER' and new_row == 0:
                piece = Piece('USER_KING', new_row, new_col)
            elif piece.get_type() == 'CPU' and new_row == 7:
                piece = Piece('CPU_KING', new_row, new_col)
            board[new_row][new_col] = piece
        return board
Exemplo n.º 4
0
    def set_board_from_string(self, string):
        self.clear()
        row, col = 0, 0
        for char in string:

            WHITE_PIECES_ASCII = ['P', 'B', 'N', 'R', 'Q', 'K']
            BLACK_PIECES_ASCII = ['p', 'b', 'n', 'r', 'q', 'k']
            if char == '.' or char == ' ':
                piece = PieceType.EMPTY

            elif char > 'Z':
                # Black pieces
                piece_type = BLACK_PIECES_ASCII_TABLE[char]
                piece = Piece(piece_type, Color.BLACK)
            else:
                # White pieces
                piece_type = WHITE_PIECES_ASCII_TABLE[char]
                piece = Piece(piece_type, Color.WHITE)

            self._put(row, col, piece)

            if col == 7:
                row += 1
                col = 0
            else:
                col += 1
Exemplo n.º 5
0
 def __init__(self) -> None:
     # 用于存放16颗棋子
     pieces: List[Piece] = []
     # 添加红方的8颗棋子
     for name in settings.ANIMALS:
         pieces.append(Piece(name, 'red'))
     # 添加蓝方的8颗棋子
     for name in settings.ANIMALS:
         pieces.append(Piece(name, 'blue'))
     # 随机打乱棋子的顺序
     random.shuffle(pieces)
     # 用于存放棋盘上的16个格子
     # 这些格子是4行4列
     self._container: List[List[Cell]] = []
     # 把16颗棋子放到16个格子上
     i = 0
     for row in range(4):
         row_of_board = []
         for col in range(4):
             row_of_board.append(
                 Cell(pieces[i],
                      settings.LEFT_OF_BOARD + col * settings.CELL_SIZE,
                      settings.TOP_OF_BOARD + row * settings.CELL_SIZE,
                      settings.CELL_SIZE))
             i += 1
         self._container.append(row_of_board)
     self._turn = random.choice(['red', 'blue'])
     # 保存的用户第一次点击的坐标
     self.user_coordinates = None
     # 10次没有互相吃,就平局
     self.not_eat = 0
Exemplo n.º 6
0
 def __init__(self):
     # keep track of the grid as 2-D list of (R,G,B) values
     self.grid = [[(0, 0, 0) for _ in range(NUM_COLUMNS)]
                  for _ in range(NUM_ROWS)]
     # score for game as 10x for each line removed
     self.score = 0
     # dictionary of grid points that have been occupied by the various pieces
     self.locked_pos = dict()
     # to kill game if ESC is pressed or windows is closed
     self.game_running = True
     # to kill game if blocks reach out the visible region
     self.game_over = False
     # variable to track the current piece
     self.current_piece = Piece(5, 0, choice(SHAPES_LIST))
     # variable to display the next piece
     self.next_piece = Piece(5, 0, choice(SHAPES_LIST))
     # variable to indicate that current piece has reached the maximum ground and next piece needs to be loaded
     self.change_current_piece = False
     # game clock to keep track of game ticks
     self.game_clock = pygame.time.Clock()
     # variable indicate the speed of the block and to indicate the motion of falling pieces
     self.fall_time = 0
     # variable that caps the max fall time
     self.fall_speed = 0.27
     # game window surface
     self.window = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
Exemplo n.º 7
0
 def pieces(self) -> Iterable[Piece]:
     for r_ind, row in enumerate(self._board):
         for c_ind, position_state in enumerate(row):
             if position_state is PositionState.WHITE:
                 yield Piece(r_ind, c_ind, Color.WHITE)
             elif position_state is PositionState.BLACK:
                 yield Piece(r_ind, c_ind, Color.BLACK)
Exemplo n.º 8
0
    def new_board(self):

        board_matrix = [[None] * self.size] * self.size

        # set square colours
        for x in range(self.size):
            for y in range(self.size):
                if x % 2 == 0:
                    if y % 2 == 0:
                        board_matrix[x][y] = Square(Colour.WHITE)
                    else:
                        board_matrix[x][y] = Square(Colour.BLACK)
                else:
                    if y % 2 == 0:
                        board_matrix[x][y] = Square(Colour.BLACK)
                    else:
                        board_matrix[x][y] = Square(Colour.WHITE)

        # set up pieces
        for y in range(self.size):
            for x in range(3):
                if board_matrix[x][y].color == Colour.BLACK:
                    board_matrix[x][y].occupant = Piece(Colour.WHITE)
            for x in range(5, self.size):
                if board_matrix[x][y].color == Colour.BLACK:
                    board_matrix[x][y].occupant = Piece(Colour.BLACK)

        return board_matrix
Exemplo n.º 9
0
 def create_start_board(self):
     board = []
     for row in range(8):
         board_row = []
         for column in range(8):
             if row < 3:
                 if row == 0 or row == 2:
                     if column % 2 != 0:
                         board_row.append(Piece(row, column, self.BLACK))
                     else:
                         board_row.append(EmptyPiece())
                 else:
                     if column % 2 != 0:
                         board_row.append(EmptyPiece())
                     else:
                         board_row.append(Piece(row, column, self.BLACK))
             elif 2 < row < 5:
                 board_row.append(EmptyPiece())
             else:
                 if row == 5 or row == 7:
                     if column % 2 == 0:
                         board_row.append(Piece(row, column, self.RED))
                     else:
                         board_row.append(EmptyPiece())
                 else:
                     if column % 2 == 0:
                         board_row.append(EmptyPiece())
                     else:
                         board_row.append(Piece(row, column, self.RED))
         board.append(board_row)
     return board
Exemplo n.º 10
0
    def draw(self, surface):
        for i in range(8):
            for j in range(8):
                if self.get_board_val(i, j):
                    pos = (j * 100 + 5, i * 100 + 5)
                    if self.get_board_val(i, j) == Piece('CPU', i, j):
                        surface.blit(self.get_board_val(i, j).get_icon(), pos)
                    elif self.get_board_val(i, j) == Piece('USER', i, j):
                        surface.blit(self.get_board_val(i, j).get_icon(), pos)
                    elif self.get_board_val(i, j) == Piece('CPU_KING', i, j):
                        surface.blit(self.get_board_val(i, j).get_icon(), pos)
                    elif self.get_board_val(i, j) == Piece('USER_KING', i, j):
                        surface.blit(self.get_board_val(i, j).get_icon(), pos)
        for i in range(8):
            for j in range(0, 800, 200):
                if i % 2 == 0:
                    rectangle = (j, 100 * i, 100, 100)
                    surface.fill((255, 0, 0), rect=rectangle)
                else:
                    rectangle = (j + 100, 100 * i, 100, 100)
                    surface.fill((255, 0, 0), rect=rectangle)
        for i in range(100, 800, 100):
            pygame.draw.line(surface, (255, 233, 0), (0, i), (800, i), 2)
            pygame.draw.line(surface, (255, 233, 0), (i, 0), (i, 800), 2)
        pygame.draw.line(surface, (255, 233, 0), (0, 0), (0, 800), 5)
        pygame.draw.line(surface, (255, 233, 0), (0, 800), (800, 800), 5)
        pygame.draw.line(surface, (255, 233, 0), (800, 800), (800, 0), 5)
        pygame.draw.line(surface, (255, 233, 0), (800, 0), (0, 0), 5)

        surface.fill((0, 65, 0), rect=(800, 0, 400, 800))
Exemplo n.º 11
0
 def generateMap():
     map = {}
     for i in range(8):
         for j in range(8):
             if i == 1:
                 map[i, j] = Piece.P2_PAWN
             elif i == 6:
                 map[i, j] = Piece.P1_PAWN
             elif i == 0 or i == 7:
                 if j == 0 or j == 7:
                     map[i,
                         j] = Piece(Piece.P1_ROOK.value +
                                    (Piece.P2_PAWN.value if i < 4 else 0))
                 elif j == 1 or j == 6:
                     map[i,
                         j] = Piece(Piece.P1_KNIGHT.value +
                                    (Piece.P2_PAWN.value if i < 4 else 0))
                 elif j == 2 or j == 5:
                     map[i,
                         j] = Piece(Piece.P1_BISHOP.value +
                                    (Piece.P2_PAWN.value if i < 4 else 0))
                 elif j == 3:
                     map[i,
                         j] = Piece(Piece.P1_QUEEN.value +
                                    (Piece.P2_PAWN.value if i < 4 else 0))
                 elif j == 4:
                     map[i,
                         j] = Piece(Piece.P1_KING.value +
                                    (Piece.P2_PAWN.value if i < 4 else 0))
             else:
                 map[i, j] = Piece.EMPTY
     return map
Exemplo n.º 12
0
    def __init__(self):
        self.board = [[Piece() for x in range(8)] for y in range(8)]
        pieces = [
            "rook", "knight", "bishop", "queen", "king", "bishop", "knight",
            "rook"
        ]
        currId = 0
        for i in range(8):
            self.board[0][i] = Piece(pieces[i], 1, currId, 0)
            currId += 1
        for i in range(8):
            self.board[1][i] = Piece("pawn", 1, currId, 0)
            currId += 1
        for i in range(8):
            self.board[6][i] = Piece("pawn", 0, currId, 0)
            currId += 1
        for i in range(8):
            self.board[7][i] = Piece(pieces[i], 0, currId, 0)
            currId += 1
        self.kings = [None, None]
        for c in [Coord(x, y) for x in range(8) for y in range(8)]:
            if self.getSquare(c).name == "king":
                self.kings[self.getSquare(c).team] = c

        self.turnCount = 0
        self.turn = 0
        self.SCORETHRESHOLD = 15
        self.log = []
        self.winner = -1
Exemplo n.º 13
0
 def test_is_check(self):
     board = Board(6, 6)
     p_king_white = Piece(Piece.KING, Piece.WHITE)
     board.add(p_king_white, 0, 2)
     p_queen_black = Piece(Piece.QUEEN, Piece.BLACK)
     board.add(p_queen_black, 2, 4)
     self.assertTrue(board.is_check_for_enemy(Piece.WHITE))
Exemplo n.º 14
0
 def getInitialPieces():
     pieces = {}
     for coord, pieceType in STARTING_POS_WHITE:
         pieces[coordToTuple(coord)] = Piece(WHITE, pieceType)
         pieces[coordToTuple(flipCoordAcrossBoard(coord))] = Piece(
             BLACK, pieceType)
     return pieces
Exemplo n.º 15
0
 def test_array_to_xy(self):
     piece1 = Piece(c.PLAYER1, 1, 0)
     piece2 = Piece(c.PLAYER2, 6, 5)
     self.assertEqual(piece1.x, -175)
     self.assertEqual(piece1.y, -150)
     self.assertEqual(piece2.x, 75)
     self.assertEqual(piece2.y, 100)
Exemplo n.º 16
0
    def set_board(self):
        for board_file in BOARD_FILES:
            file_ = board_file[0]
            white_pawn = Piece()
            white_pawn.color = Piece.WHITE
            white_pawn.name = Piece.PAWN
            self.square(file_, 2).piece = white_pawn

        for board_file in BOARD_FILES:
            file_ = board_file[0]
            black_pawn = Piece()
            black_pawn.color = Piece.BLACK
            black_pawn.name = Piece.PAWN
            self.square(file_, 7).piece = black_pawn

        for board_file in BOARD_FILES:
            file_ = board_file[0]
            white_piece = Piece()
            white_piece.color = Piece.WHITE
            white_piece.name = board_file[1]
            self.square(file_, 1).piece = white_piece

            black_piece = Piece()
            black_piece.color = Piece.BLACK
            black_piece.name = board_file[1]
            self.square(file_, 8).piece = black_piece

        for board_file in BOARD_FILES:
            file_ = board_file[0]
            self.square(file_, 3).piece = None
            self.square(file_, 4).piece = None
            self.square(file_, 5).piece = None
            self.square(file_, 6).piece = None
Exemplo n.º 17
0
 def test_get_piece_moves(self):
     game = GameState()
     move1 = game.get_piece_moves(Piece(c.PLAYER1, 2, 1))
     move2 = game.get_piece_moves(Piece(c.PLAYER2, 4, 5))
     move3 = game.get_piece_moves(Piece(c.PLAYER1, 0, 1))
     self.assertEqual(move1.sort(), [[1, -1], [1, 1]].sort())
     self.assertEqual(move2.sort(), [[-1, -1], [-1, 1]].sort())
     self.assertEqual(move3, [])
Exemplo n.º 18
0
 def fromJSON(jsonDict: dict, offset):
     le = LogEntry(moveCost=jsonDict['moveCost'],
                   dt=jsonDict['dt'] + offset,
                   ep=tuple(jsonDict['ep']),
                   piece=Piece(jsonDict['piece']),
                   attacked=Piece(jsonDict['attacked']),
                   sp=tuple(jsonDict['sp']))
     return le
Exemplo n.º 19
0
 def test_is_legal_movement_rook_down(self):
     board = Board(20, 20)
     piece_king_white = Piece(Piece.KING, Piece.WHITE)
     piece_rook_black = Piece(Piece.ROOK, Piece.BLACK)
     board.add(piece_king_white, 18, 10)
     board.add(piece_rook_black, 15, 10)
     available_positions = [[16, 10], [17, 10], [18, 10]]
     self.assertEqual(board.is_legal_movement(15, 10), available_positions)
Exemplo n.º 20
0
 def test_is_check_only_two_kings(self):
     board = Board(4, 4)
     p_king_black = Piece(Piece.KING, Piece.BLACK)
     p_king_white = Piece(Piece.KING, Piece.WHITE)
     board.add(p_king_black, 0, 0)
     board.add(p_king_white, 0, 1)
     self.assertTrue(board.is_check_for_enemy(Piece.WHITE))
     self.assertTrue(board.is_check_for_enemy(Piece.BLACK))
Exemplo n.º 21
0
 def test_get(self):
     self.assertEqual(None, self.b1.get(0, 0))
     self.b1.place(Piece(), 0, 0)
     self.assertEqual(Piece(), self.b1.get(0, 0))
     self.b1.place(Piece(False), 0, 1)
     self.assertEqual(self.b1.get(0, 0), self.b1.get(0, 1))
     self.b1.place(Piece(True, False, False, False), 0, 2)
     self.assertNotEqual(self.b1.get(0, 1), self.b1.get(0, 2))
Exemplo n.º 22
0
def string_to_move(move):
    if len(move) == 2:
        return Move(file_to_col(move[0]), rank_to_row(move[1]))
    elif len(move) == 3:
        return Move(file_to_col(move[0]), rank_to_row(move[1]), Piece(move[0]))
    elif len(move) == 4:
        return Move(file_to_col(move[0]), rank_to_row(move[1]), Piece(move[0]),
                    True)
Exemplo n.º 23
0
def test_moves_none():
    # A piece can't eat while getting outside of the board or eat with a piece on the way.
    test_piece = Piece('12WN')
    test_board = Board(
        [test_piece, Piece('8BN'),
         Piece('9BN'), Piece('5BN')], 'W')

    assert test_piece.get_moves(test_board) == []
Exemplo n.º 24
0
 def prep_sign(self, screen, settings):
     winner = "blanco" if self.turn == "black" else "negro"
     if self.checkmate:
         return Piece(screen, settings, "Jaque mate, Gana " + (winner), 12,
                      4, "black")
     if self.promotion:
         return Piece(screen, settings, "PRM", 10, 4, "black")
     elif self.check:
         return Piece(screen, settings, "Jaque", 10, 4, "black")
Exemplo n.º 25
0
 def test_is_legal_movement_queen(self):
     board = Board(6, 6)
     piece_king_white = Piece(Piece.KING, Piece.WHITE)
     piece_queen_black = Piece(Piece.QUEEN, Piece.BLACK)
     board.add(piece_king_white, 0, 2)
     board.add(piece_queen_black, 3, 3)
     available_positions = [[3, 2], [2, 3], [1, 3], [0, 3], [2, 2], [1, 1],
                            [0, 0], [2, 4]]
     self.assertEqual(board.is_legal_movement(3, 3), available_positions)
Exemplo n.º 26
0
 def test_is_legal_movement_king(self):
     board = Board(20, 20)
     piece_king_white = Piece(Piece.KING, Piece.WHITE)
     piece_king_black = Piece(Piece.KING, Piece.BLACK)
     board.add(piece_king_white, 10, 10)
     board.add(piece_king_black, 15, 10)
     available_positions = [[11, 11], [11, 10], [11, 9]]
     self.assertEqual(
         board.is_legal_movement(10, 10).sort(), available_positions.sort())
Exemplo n.º 27
0
 def putListBoard(self, listBoard):
     for i in range(len(self.self.squares)):
         for j in range(len(self.self.squares[0])):
             if listBoard[i][j] == None:
                 self.squares[i][j].removePiece()
             elif listBoard[i][j] == "black":
                 self.squares[i][j].setPiece(Piece(0, "black"))
             elif listBoard[i][j] == "green":
                 self.squares[i][j].setPiece(Piece(1, "green"))
Exemplo n.º 28
0
 def putListBoard(self, listBord):
     for i in range(self.gameSize):
         for j in range(self.gameSize):
             if listBord[i][j] == None:
                 self.squares[i][j].removePiece()
             elif listBord[i][j] == "black":
                 self.squares[i][j].setPiece(Piece(0, "black"))
             elif listBord[i][j] == "white":
                 self.squares[i][j].setPiece(Piece(1, "white"))
Exemplo n.º 29
0
def opponent_queen(board, new_pos, piece_list, player):
    if board.board[new_pos[0]][new_pos[1]].piece.type == "pawn" and (
            new_pos[1] == 0 or new_pos[1] == 7):
        if player == 0:
            board.board[new_pos[0]][new_pos[1]].piece = Piece(
                piece_list[10], "queen", "black")
        else:
            board.board[new_pos[0]][new_pos[1]].piece = Piece(
                piece_list[4], "queen", "white")
Exemplo n.º 30
0
 def test_make_king(self):
     piece_a = Piece(c.PLAYER1, 7, 1)
     piece_a.make_king()
     piece_b = Piece(c.PLAYER2, 7, 4)
     self.assertTrue(piece_a.king)
     self.assertEqual(piece_a.direction, (
         [1, 1], [1, -1], [-1, 1], [-1, -1]))
     self.assertFalse(piece_b.king)
     self.assertEqual(piece_b.direction, ([-1, 1], [-1, -1]))