def test_players_can_get_out_of_check(): board = Board({'e1': King('black'), 'f8': Rook('white'), 'a1': King('white')}) assert board.check is None board.move('f8', 'e8') assert board.check == 'black' board.move('e1', 'f1') assert board.check is None
def __init__(self, board_size=(8, 8)): self.board = Board(board_size) self.state = PRE self.judge = False self.score = 0 self.pre_solve_figures_queue = queue.Queue()
def test_player_should_to_get_out_of_check(): board = Board({'e1': King('black'), 'f8': Rook('white'), 'a1': King('white')}) assert board.check is None board.move('f8', 'e8') assert board.check == 'black' with pytest.raises(ImpossibleMove): board.move('e1', 'e2')
def run(): board = Board() board.start_game() gui = Gui(board) gui.load_images() gui.run()
def test_check_if_player_is_not_in_check_anymore(self): board = Board({'e1': King('black'), 'f8': Rook('white'), 'a1': King('white')}) self.assertIsNone(board.check) board.move('f8', 'e8') self.assertEqual('black', board.check) board.move('e1', 'f1') self.assertIsNone(board.check)
def parse_board(message, width, height): b = Board(width, height) fig_info = re.findall(r'\([a-zA-Z]*\d* \d* \d*\)', message) for info in fig_info: info = info.replace('(', '').replace(')', '').split() b.add_figure(info[0], int(info[1]), int(info[2])) return b
def test_it_raise_an_exception_if_a_piece_already_settled(self): board = Board() board.squares = {'a': {'1': Rook()}} with pytest.raises(ImpossibleSettleException): board.settle(Rook(), x='a', y='1')
def _init(self): self.selected = None self.board = Board() self.turn = WHITE self.valid_moves = [] self.check_mate = False self.move_x, self.move_y = 805, 40 self.__draw_static_text()
def test_en_passant(self): board = Board.from_fen( 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq A1 0 1') self.assertEqual(board.en_passant_pos, P('a1')) board = Board.from_fen( 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq h8 0 1') self.assertEqual(board.en_passant_pos, P('h8'))
def test_it_should_settle_the_rook_in_a_square(self): board = Board() rook = Rook() board.settle(rook, x='a', y='1') assert board.squares['a']['1'] == rook
def test_castling_left_white(self): board = Board(initial_pieces={'e1': King('white'), 'a1': Rook('white')}) king = board.squares['e1'] rook = board.squares['a1'] board.move('e1', 'c1') self.assertIs(king, board.squares['c1']) self.assertIs(rook, board.squares['d1']) self.assertIsNone(board.squares['e1']) self.assertIsNone(board.squares['a1'])
def test_copy(): board = Board() king = King(BLACK, 0, 0) rook = Rook(WHITE, 2, 2) board._pieces = {king, rook} clone = board.copy() assert len(clone._pieces) == len(board._pieces) for piece in clone._pieces: assert piece not in board._pieces
def test_active_side(self): with self.subTest('should be white'): board = Board.from_fen('8/8/8/8/8/8/PPPPPPPP/RNBQKBNR w - - 0 1') self.assertEqual(board.player, Color.WHITE) self.assertEqual(board.enemy, Color.BLACK) with self.subTest('should be black'): board = Board.from_fen('8/8/8/8/8/8/PPPPPPPP/RNBQKBNR b - - 0 1') self.assertEqual(board.player, Color.BLACK) self.assertEqual(board.enemy, Color.WHITE)
def test_full_move_clock(self): board = Board.from_fen('8/8/8/8/8/8/PPPPPPPP/RNBQKBNR w - - 0 1') self.assertEqual(getattr(board, 'full_move'), 1) board = Board.from_fen('8/8/8/8/8/8/PPPPPPPP/RNBQKBNR w - - 0 42') self.assertEqual(getattr(board, 'full_move'), 42) self.assertTrue( False, 'Refactor this test') # the getattr with direct attribute access
def test_raise_exception_when_player_doesnt_get_out_of_check(self): board = Board({ 'e1': King('black'), 'f8': Rook('white'), 'a1': King('white') }) self.assertIsNone(board.check) board.move('f8', 'e8') self.assertEqual('black', board.check) self.assertRaises(ImpossibleMove, board.move, 'e1', 'e2')
def test_castling_left_black(self): board = Board(initial_pieces={'a2': Pawn('white'), 'e8': King('black'), 'a8': Rook('black')}) king = board.squares['e8'] rook = board.squares['a8'] board.move('a2', 'a3') # just because white have to move first board.move('e8', 'c8') self.assertIs(king, board.squares['c8']) self.assertIs(rook, board.squares['d8']) self.assertIsNone(board.squares['e8']) self.assertIsNone(board.squares['a8'])
def test_fail_castling_when_king_already_moved(self): board = Board(initial_pieces={ 'a8': King('black'), 'a7': Pawn('black'), 'e1': King('white'), 'h1': Rook('white')}) board.move('e1', 'f1') board.move('a7', 'a6') # pawn moves board.move('f1', 'e1') board.move('a6', 'a5') # pawn moves self.assertRaises(ImpossibleMove, board.move, 'e1', 'g1')
def test_king_can_moves(): king = King('white') # # I have to pass a second king because the board look for a second # king when you set the first one. Maybe a have to add an attribute # to the board class to say wether the match is tutorial or not. # board = Board(initial_pieces={'f5': king, 'h1': King('black')}) board.move('f5', 'e5') assert board.get_piece('e5') is king assert board.get_piece('f5') is None
def test_knight_capture(self): board = Board(initial_pieces={'a8': King('black'), 'e5': Pawn('black'), 'f3': Knight('white')}) pieces = [piece for piece in board.squares.values() if piece is not None] self.assertEqual(3, len(pieces)) knight = board.squares['f3'] board.move('f3', 'e5') self.assertIs(knight, board.squares['e5']) pieces = [piece for piece in board.squares.values() if piece is not None] self.assertEqual(2, len(pieces))
def test_castling_left_white(self): board = Board(initial_pieces={ 'e1': King('white'), 'a1': Rook('white') }) king = board.squares['e1'] rook = board.squares['a1'] board.move('e1', 'c1') self.assertIs(king, board.squares['c1']) self.assertIs(rook, board.squares['d1']) self.assertIsNone(board.squares['e1']) self.assertIsNone(board.squares['a1'])
def test_it_returns_a_piece_by_coordinates(self): board = Board() piece = board.tiles[0][0].piece retrieved_piece = board.get_piece_on_coordinates('a8') self.assertEqual(piece, retrieved_piece) piece = board.tiles[0][1].piece retrieved_piece = board.get_piece_on_coordinates('b8') self.assertEqual(piece, retrieved_piece) self.assertIsNone(board.get_piece_on_coordinates('c5'))
def test_moving_the_king_should_disallow_any_further_castling(self): with self.subTest('white'): board = Board.from_strings([ # bcdefgh '........', # 8 '........', # 7 '........', # 6 '........', # 5 '........', # 4 '........', # 3 '........', # 2 'R...K..R' # 1 # bcdefgh ]) white_king = board[Rank.ONE][File.E] moves = white_king.generate_moves(board, P('e1')) self.assertIn(P('c1'), moves) self.assertIn(P('g1'), moves) # move the king and then return it in it's original position board.move(from_pos=P('e1'), to_pos=P('f1')) board.move(from_pos=P('f1'), to_pos=P('e1')) moves = white_king.generate_moves(board, P('e1')) self.assertNotIn(P('c1'), moves) self.assertNotIn(P('g1'), moves) with self.subTest('black'): board = Board.from_strings([ # bcdefgh 'r...k..r', # 8 '........', # 7 '........', # 6 '........', # 5 '........', # 4 '........', # 3 '........', # 2 '........' # 1 # bcdefgh ]) black_king = board[Rank.EIGHT][File.E] moves = black_king.generate_moves(board, P('e8')) self.assertIn(P('c8'), moves) self.assertIn(P('g8'), moves) board.move(from_pos=P('e8'), to_pos=P('f8')) board.move(from_pos=P('f8'), to_pos=P('e8')) moves = black_king.generate_moves(board, P('e8')) self.assertNotIn(P('c8'), moves) self.assertNotIn(P('g8'), moves)
def main(): run = True clock = pygame.time.Clock() board = Board(WIN) while run: clock.tick(FPS) for event in pygame.event.get(): if event.type == pygame.QUIT: run = False break if event.type == pygame.MOUSEBUTTONDOWN: pass board.update() pygame.quit()
def test_castling_left_black(self): board = Board(initial_pieces={ 'a2': Pawn('white'), 'e8': King('black'), 'a8': Rook('black') }) king = board.squares['e8'] rook = board.squares['a8'] board.move('a2', 'a3') # just because white have to move first board.move('e8', 'c8') self.assertIs(king, board.squares['c8']) self.assertIs(rook, board.squares['d8']) self.assertIsNone(board.squares['e8']) self.assertIsNone(board.squares['a8'])
def __init__(self, win, skill_level): self.win = win self.board = Board() self._initialize() self.engine = Engine(skill_level) self.buttons = [ Button(SQUARE_SIZE * 9, SQUARE_SIZE, SQUARE_SIZE, SQUARE_SIZE // 2, RED, "queen"), Button(SQUARE_SIZE * 9, SQUARE_SIZE * 2, SQUARE_SIZE, SQUARE_SIZE // 2, BLUE, "bishop"), Button(SQUARE_SIZE * 9, SQUARE_SIZE * 3, SQUARE_SIZE, SQUARE_SIZE // 2, GREEN, "knight"), Button(SQUARE_SIZE * 9, SQUARE_SIZE * 4, SQUARE_SIZE, SQUARE_SIZE // 2, ORANGE, "rook") ]
def __init__( self, board=None, white_player=RandomAgent, black_player=RandomAgent, current_color='white', ): self.white_player = white_player(color='white') self.black_player = black_player(color='black') self.current_color = current_color if board is None: self.board = Board() else: self.board = Board(board) self._game_history = []
def test_en_passant_square_is_set_on_the_board_object(self): board = Board.from_strings([ # bcdefgh '........', # 8 '.p......', # 7 '........', # 6 '........', # 5 '........', # 4 '........', # 3 '.P......', # 2 '........' # 1 ]) with self.subTest('white'): en_passant_want = Position(Rank.THREE, File.B) f, t = Position(Rank.TWO, File.B), Position(Rank.FOUR, File.B) board.move(from_pos=f, to_pos=t) self.assertEqual(board.en_passant_pos, en_passant_want) with self.subTest('black'): en_passant_want = Position(Rank.SIX, File.B) f, t = Position(Rank.SEVEN, File.B), Position(Rank.FIVE, File.B) board.move(from_pos=f, to_pos=t) self.assertEqual(board.en_passant_pos, en_passant_want)
def test_promotion_callback_should_be_called(self): board = Board.from_strings([ # bcdefgh '........', # 8 '.P......', # 7 '........', # 6 '........', # 5 '........', # 4 '........', # 3 '.p......', # 2 '........' # 1 ]) board.promotion_cb = unittest.mock.Mock() mock_piece = board.promotion_cb.return_value with self.subTest('white'): f, t = Position(Rank.SEVEN, File.B), Position(Rank.EIGHT, File.B) board.move(from_pos=f, to_pos=t) board.promotion_cb.assert_called_once() mock_piece.assert_called_once_with(Color.WHITE) board.promotion_cb.reset_mock() mock_piece = board.promotion_cb.return_value with self.subTest('black'): f, t = Position(Rank.TWO, File.B), Position(Rank.ONE, File.B) board.move(from_pos=f, to_pos=t) board.promotion_cb.assert_called_once() mock_piece.assert_called_once_with(Color.BLACK)
def test_get_attackers_detects_king_attacks(self): """The placement of this test must seem off The bulk of the use cases are get_attackers are tested inderectly in the check awareness tests The only use case that cannot be tested with check awareness is when the king attacks something """ board = Board.from_strings([ # bcdefgh "p.......", # 8 "K.......", # 7 "........", # 6 "........", # 5 "........", # 4 "........", # 3 "k.......", # 2 "P......." # 1 ]) with self.subTest('white pawn attacked'): attackers = board.get_attackers(P('a1'), Color.WHITE) self.assertEqual([P('a2')], list(attackers)) with self.subTest('black pawn attacked'): attackers = board.get_attackers(P('a8'), Color.BLACK) self.assertEqual([P('a7')], list(attackers))
def test_fail_castling_when_some_piece_is_between_king_rook(self): board = Board(initial_pieces={ 'e1': King('white'), 'f1': Queen('white'), 'h1': Rook('white') }) self.assertRaises(ImpossibleMove, board.move, 'e1', 'g1')
def test_double_check_no_other_pieces_other_than_king_should_move(self): for figure, figure_name in ( ('q', 'queen'), ('n', 'knight'), ('b', 'bishop'), ('p', 'pawn'), ('r', 'rook'), ): test_case = { 'name': f'{figure_name}_is_blocking_double_check_and_should_not_be_able_to_move', 'board': Board.from_strings( os.linesep.join([ # bcdefgh '....q...', # 8 '.q......', # 7 '..X.....', # 6 '.K......', # 5 '.......Q', # 4 '....Q...', # 3 '.....x..', # 2 '....k...' # 1 ]).replace('x', figure).replace('X', figure.upper()).split( os.linesep)), 'want': { 'white': { P('c6'): {} }, 'black': { P('f2'): {} } } } self.runMoveGenerationTest(test_case)
def test_alternating_between_players(): board = Board() assert board.turn == 'white' board.move('g2', 'g3') # white pawn moves assert board.turn == 'black' board.move('b7', 'b6') # black pawn moves assert board.turn == 'white' board.move('f1', 'g2') # white bishop moves assert board.turn == 'black'
def moves_str(self, color): moves_strs = [] for piece, move in self.moves(color, with_piece=True): move_str = Board.chess_move_notation(move) moves_strs.append( f"{str(piece)} : {move_str}" ) return '\n'.join(moves_strs)
def test_instantiate_board(self): board = Board() self.assertEqual(64, len(board.squares)) pieces = [ piece for piece in board.squares.values() if piece is not None ] self.assertEqual(32, len(pieces))
def test_icon(): board = Board() rook = Rook(0, 0, Color.WHITE, board) assert rook.char() == '♖' rook = Rook(0, 0, Color.BLACK, board) assert rook.char() == '♜'
def test_it_has_tiles(self): board = Board() self.assertEqual(len(board.tiles), board.height) for row in board.tiles: self.assertEqual(len(row), board.width) tile = board.tiles[0][0] self.assertIsInstance(tile, Tile)
def main(): run = True clock = pygame.time.Clock() board = Board() active_click = 0 while run: clock.tick(FPS) for event in pygame.event.get(): #For exiting the game if event.type == pygame.QUIT: run = False #For clicking on screen if event.type == pygame.MOUSEBUTTONDOWN: if active_click == 1: pos = pygame.mouse.get_pos() row, col = return_row_col_of_mouse(pos) board.move_piece(piece, row, col) active_click = 0 else: pos = pygame.mouse.get_pos() row, col = return_row_col_of_mouse(pos) piece = board.return_piece(row, col) if piece != 0: active_click = 1 board.draw(WIN) pygame.display.update() pygame.quit()
def assignment(): """ Assignment """ board = Board(5, 5) pieces = {} pieces['king'] = 2 pieces['queen'] = 2 pieces['bishop'] = 2 pieces['rook'] = 0 pieces['knight'] = 1 start = datetime.datetime.now() print 'Start', start board.set_pieces(pieces) board.put_pieces() end = datetime.datetime.now() print 'End', end print 'Duration', end-start print 'Found '+str(len(board.solutions))+ ' solutions' exit()
def to_python(self, value): u"""Creates a new board from the board described by board_string.""" if isinstance(value, Board): return value else: if value is not None: if len(value) == 0: # Web requrests can provide an empty string value = None return Board(value)
def test_pieces_can_capture_opponent_pieces(): board = Board(initial_pieces={'a8': King('black'), 'e5': Pawn('black'), 'f3': Knight('white')}) assert board.pieces_quantity() == 3 knight = board.get_piece('f3') board.move('f3', 'e5') assert board.get_piece('e5') is knight assert board.pieces_quantity() == 2
class TestPawnInit(unittest.TestCase): def setUp(self): self.board = Board() def test_init_pawn(self): pawn = Pawn(self.board, 'c', '5', 'white') posx, posy = self.board.convert_pos_to_array('c', 5) self.assertIsNotNone(self.board.__board__[posx][posy]) self.assertTrue(pawn in self.board.white_set) self.assertFalse(pawn in self.board.black_set)
def test_check_small(): board = Board() king = King(BLACK, 0, 0) rook = Rook(WHITE, 2, 2) board._pieces = {king, rook} assert not board.checked(BLACK) board.move(rook, 2, 0) assert board.checked(BLACK)
def test_fail_castling_when_king_already_moved(): board = Board(initial_pieces={ 'a8': King('black'), 'a7': Pawn('black'), 'e1': King('white'), 'h1': Rook('white')}) board.move('e1', 'f1') # king moves board.move('a7', 'a6') # pawn moves board.move('f1', 'e1') # king moves back board.move('a6', 'a5') # pawn moves again with pytest.raises(ImpossibleMove): board.move('e1', 'g1')
def test_check_medium(): board = Board() king = King(BLACK, 0, 0) rook = Rook(WHITE, 2, 2) pawn = Pawn(WHITE, 7, 3) bishop = Bishop(WHITE, 1, 3) enemy_king = King(WHITE, 6, 6) board._pieces = {king, rook, pawn, bishop, enemy_king} assert not board.checked(BLACK) board.move(rook, 2, 0) assert board.checked(BLACK) assert not board.checked(WHITE)
def test_king_can_do_castling_to_left(): board = Board(initial_pieces={'e1': King('white'), 'a1': Rook('white')}) king = board.get_piece('e1') rook = board.get_piece('a1') board.move('e1', 'c1') assert board.get_piece('c1') == king assert board.get_piece('d1') == rook assert board.get_piece('e1') is None assert board.get_piece('a1') is None
def test_bishop_capture_rook(self): board = Board() pieces = [piece for piece in board.squares.values() if piece is not None] self.assertEqual(32, len(pieces)) bishop = board.squares['f1'] board.move('g2', 'g3') # white pawn moves board.move('b7', 'b6') # black pawn moves board.move('f1', 'g2') # white bishop moves board.move('g8', 'f6') # black knight moves board.move('g2', 'a8') # white bishop capture white rook self.assertIs(bishop, board.squares['a8']) pieces = [piece for piece in board.squares.values() if piece is not None] self.assertEqual(31, len(pieces))
def test_board_regular_move(self): board = Board() knight = board.squares['g1'] board.move('g1', 'f3') self.assertIs(knight, board.squares['f3']) self.assertIsNone(board.squares['g1']) board = Board() pawn = board.squares['e2'] board.move('e2', 'e3') self.assertIs(pawn, board.squares['e3']) self.assertIsNone(board.squares['e2'])
def main(): """ Main function """ parser = ArgumentParser() parser.add_argument("-x", "--horizontal", dest="width", default=3, type=int, help="Horizontal dimension (default=3)") parser.add_argument("-y", "--vertical", dest="height", default=3, type=int, help="Vertical dimension (default=3)") parser.add_argument("-k", "--kings", dest="king", default=0, type=int, help="Number of kings") parser.add_argument("-q", "--queens", dest="queen", default=0, type=int, help="Number of queens") parser.add_argument("-b", "--bishops", dest="bishop", default=0, type=int, help="Number of bishops") parser.add_argument("-r", "--rooks", dest="rook", default=0, type=int, help="Number of rooks") parser.add_argument("-n", "--knights", dest="knight", default=0, type=int, help="Number of knights") parser.add_argument("-p", "--print", dest="printsolutions", default=False, help="Print the solutions", action='store_true') args = parser.parse_args() if sum([args.king, args.queen, args.bishop, args.rook, args.knight]) == 0: print 'No chess pieces given. Nothing to do. Running the assignment!' assignment() else: print 'Chess pieces:' print '- Kings ' + str(args.king) print '- Queens ' + str(args.queen) print '- Bishops ' + str(args.bishop) print '- Rooks ' + str(args.rook) print '- Knights ' + str(args.knight) board = Board(args.width, args.height) pieces = {} pieces['king'] = args.king pieces['queen'] = args.queen pieces['bishop'] = args.bishop pieces['rook'] = args.rook pieces['knight'] = args.knight board.set_pieces(pieces) print 'Start', datetime.datetime.now() board.put_pieces() print 'End', datetime.datetime.now() print 'Found '+str(len(board.solutions))+ ' solutions' if args.printsolutions is True: board.print_solutions()
def test_fail_pawn_moves_two_squares(self): board = Board() board.move('a2', 'a3') self.assertRaises(ImpossibleMove, board.move, 'a3', 'a5')
def test_pawn_cant_move_diagonally(): board = Board() with pytest.raises(ImpossibleMove): board.move('e2', 'f3')
def test_pawn_can_moves(): board = Board() pawn = board.get_piece('e2') board.move('e2', 'e3') assert board.get_piece('e3') is pawn assert board.get_piece('e2') is None
def test_pawn_cant_moves_two_squares_after_moved(): board = Board() board.move('e2', 'e3') with pytest.raises(ImpossibleMove): board.move('e3', 'f5')
def test_pawn_cant_move_back(): board = Board(initial_pieces={'b4': Pawn('white')}) with pytest.raises(ImpossibleMove): assert board.move('b4', 'b3')
def test_raise_exception_when_player_doesnt_get_out_of_check(self): board = Board({'e1': King('black'), 'f8': Rook('white'), 'a1': King('white')}) self.assertIsNone(board.check) board.move('f8', 'e8') self.assertEqual('black', board.check) self.assertRaises(ImpossibleMove, board.move, 'e1', 'e2')
from py_uci import UCIEngine from chess.board import Board b = Board() b.move_algebraic("e4") b.move_algebraic("c5") b.move_algebraic("Nf3") b.move_algebraic("d6") b.move_algebraic("d4") b.move_algebraic("cxd4") b.move_algebraic("Nxd4") b.move_algebraic("Nf6") b.move_algebraic("Nc3") b.move_algebraic("a6") b.move_algebraic("g4") e = UCIEngine(multi_pv=10) e.new_game() e.set_position(moves=b.get_moves()) e.find_best_move(10000) print b
def test_rook_can_moves(): rook = Rook('white') board = Board(initial_pieces={'d5': rook}) board.move('d5', 'd8') assert board.get_piece('d8') is rook assert board.get_piece('d5') is None
def test_rook_cant_moves(): board = Board(initial_pieces={'e5': Rook('white')}) with pytest.raises(ImpossibleMove): board.move('e5', 'd8')
def test_pawn_moves_two_square(self): board = Board() pawn = board.squares['a2'] board.move('a2', 'a4') self.assertIs(pawn, board.squares['a4']) self.assertIsNone(board.squares['a2'])