def __init__(self, pos, board, player): Piece.__init__(self, pos, board, player) if self.player.colour == 0: self.img = pygame.image.load("images/wpawn.png").convert_alpha() else: self.img = pygame.image.load("images/bpawn.png").convert_alpha()
def final(self): side = 2.1*sin(pi/5.0) # The first piece first = Piece(vector(-1,-1.6*side,0),vector(0,0,1)) # We form the first pentagon self.pieces = [first, first.clone().rotate(vector(0,1,0), 2.0/5.0*pi), first.clone().rotate(vector(0,1,0), 4.0/5.0*pi), first.clone().rotate(vector(0,1,0), 6.0/5.0*pi), first.clone().rotate(vector(0,1,0), 8.0/5.0*pi)] # Rotate the pentagon an create the bown defased = self.clone().rotate(vector(0,1,0),0.2*pi) faces = [] for rot in defased.pieces: o = vector(rot.box.x * side, rot.box.y, rot.box.z* side) faces.append(self.clone().rotate(rot.box.axis, -16.7/5.0*pi, o)) for face in faces: self.merge(face) face.delete() defased.delete() # the other half roted = self.clone().rotate(vector(1,0,0),pi).rotate(vector(0,1,0),pi/5.0) self.merge(roted) roted.delete()
def new_game(): global gs,spaces,game_begun,done,gameover, \ turn_stage,selected_piece,hover_piece, \ attackable_pieces,credits_showing,rules_showing, \ paused,moveCounter,saved_piece,movedPieces gs = State(cols,rows) Piece.setState(gs) spaces = pygame.sprite.RenderPlain() #sets up board for i in xrange(cols): for j in xrange(rows/2+1): if i%2==0: s=Space(screenw,screenh,cols,rows,i*screenw/cols-i*screenw/cols/4,2*j*screenh/rows+50,i,j*2) else: if j < rows/2: s=Space(screenw,screenh,cols,rows,i*screenw/cols-i*screenw/cols/4,2*int((j+.5)*screenh/rows)+50,i,j*2+1) spaces.add(s) game_begun = False done = False gameover = False credits_showing = False rules_showing = False paused = False # stages: piece_select, move, dir_sel, attack turn_stage = 'piece_sel' selected_piece = None saved_piece = None # for cancel button hover_piece = None attackable_pieces = [] moveCounter = 0 movedPieces = []
def rule_6(self, moves, game, pieces, data): """ try to create bridges across other players gaps if at all possible. """ metric = [] test_board = copy.deepcopy(game.board) for move in moves: t_board = test_board t_piece = Piece( move['pieceID'], move['playerID'], rotation=move['rotation'], parity=move['parity']) position = move['position'] before = find_bridge_instances( t_board, game.current_playerID, position=move['position'], size=t_piece.geometry.shape) t_board = t_piece.place_on_board(t_board, position) after = find_bridge_instances( t_board, game.current_playerID, position=move['position'], size=t_piece.geometry.shape) # using before and after, encourages starting and crossing bridges metric += [before + after] return np.array(metric)
def getValidMoves(self): ret = [ # One space away (self.x, self.y+2), (self.x, self.y-2), (self.x-1, self.y-1), (self.x-1, self.y+1), (self.x+1, self.y-1), (self.x+1, self.y+1), # Two spaces away (self.x, self.y+4), (self.x, self.y-4), (self.x+1, self.y+3), (self.x+1, self.y-3), (self.x-1, self.y+3), (self.x-1, self.y-3), (self.x-2, self.y), (self.x+2, self.y), (self.x+2, self.y-2), (self.x+2, self.y+2), (self.x-2, self.y-2), (self.x-2, self.y+2) ] ret = filterValidSpots(ret, Piece.getState().getWidth(), Piece.getState().getHeight()) ret = filterBlockedSpots(ret, Piece.getState()) ret.append((self.x, self.y)) return ret
def get_piece_counts(self, colors=[WHITE, BLACK]): """Counts the pieces on the board. :param color: list of colors to check. Defualts to black and white :return: A dictionary of piece counts, keyed by lowercase piece type letters. """ #if not color in ["w", "b", "wb", "bw"]: # raise KeyError( # "Expected color filter to be one of 'w', 'b', 'wb', 'bw', " # "got: %s." % repr(color)) counts = { PAWN: 0, BISHOP: 0, KNIGHT: 0, ROOK: 0, KING: 0, QUEEN: 0, } for piece in self._pieces: if piece and Piece.color(piece) in colors: counts[Piece.klass(piece)] += 1 return counts
def __init__(self, position, move): resulting_position = position.copy().make_move(move) captured = position._pieces[move.target._x88] piece = position._pieces[move.source._x88] ocolor = Piece.opposite_color(position.fen._to_move) # Pawn moves. enpassant = False if Piece.klass(piece) == PAWN: # En-passant. if move.target.file != move.source.file and not captured: enpassant = True captured = Piece.from_klass_and_color(PAWN, ocolor) # Castling. # TODO: Support Chess960. # TODO: Validate the castling move. if Piece.klass(piece) == KING: self.is_king_side_castle = move.target.x - move.source.x == 2 self.is_queen_side_castle = move.target.x - move.source.x == -2 else: self.is_king_side_castle = self.is_queen_side_castle = False # Checks. self.is_check = resulting_position.is_check() self.is_checkmate = resulting_position.is_checkmate() self.move = move self.piece = piece self.captured = captured self.is_enpassant = enpassant self._set_text(position)
def __init__(self, pos, grid, player): Piece.__init__(self, pos, grid, player) self.directions = dict(Directions.diagonals.items() + Directions.straight.items()) if self.player.colour == 0: self.img = pygame.image.load("images/wqueen.png").convert_alpha() else: self.img = pygame.image.load("images/bqueen.png").convert_alpha()
def __init__(self, pos, grid, player): Piece.__init__(self, pos, grid, player) self.validMoves = [] self.directions = Directions.diagonals if self.player.colour == 0: self.img = pygame.image.load("images/wbishop.png").convert_alpha() else: self.img = pygame.image.load("images/bbishop.png").convert_alpha()
def __init__(self, pos, board, player): Piece.__init__(self, pos, board, player) if self.player.colour == 0: self.img = pygame.image.load("images/wpawn.png").convert_alpha() else: self.img = pygame.image.load("images/bpawn.png").convert_alpha() self.img = pygame.transform.scale(self.img, (self.board.grid.cellsize, self.board.grid.cellsize))
def __init__(self, pos, grid, player): Piece.__init__(self, pos, grid, player) self.directions = Directions.knight if self.player.colour == 0: self.img = pygame.image.load("images/wknight.png").convert_alpha() else: self.img = pygame.image.load("images/bknight.png").convert_alpha()
def test_piece_one_block(self): piece = Piece(fake_client, 1, 2**14, 'abc', test_dir) self.assertEqual(piece.num_blocks, 1) self.assertTrue(piece.not_all_blocks_requested()) block_info = piece.get_next_block() self.assertEqual(block_info[0], 1) self.assertEqual(block_info[1], 0) self.assertEqual(block_info[2], 2**14) self.assertFalse(piece.not_all_blocks_requested())
def __init__(self, piece): """Create a ghost of piece. The ghost's initial position is that of piece, but you can update the ghost's position without affecting the piece's position. """ Piece.__init__(self, piece.description) self.piece = piece self.position = None if piece.position is None else list(piece.position)
def test_piece_queue_random(self): test_bytes = '\x00' test_hash = hashlib.sha1(test_bytes).digest() piece = Piece(fake_client, 1, 1, test_hash, test_dir) piece_queue = PieceQueue([piece]) test_piece = piece_queue.get_next_random() self.assertEqual(test_piece.index, piece.index) test_piece.add_block(0, test_bytes) self.assertTrue(piece.check_if_finished()) self.assertTrue(piece.check_info_hash())
def __init__(self, description, color, player): """ Initializes a Unit. """ Piece.__init__(self, description) self.color = color self.chargeDescription = dict(description['charge']) self.imageBase = description['imageBase'] self.player = player
def __init__(self, pos, board, player): Piece.__init__(self, pos, board, player) self.validMoves = [] self.directions = Directions.straight if self.player.colour == 0: self.img = pygame.image.load("images/wrook.png").convert_alpha() else: self.img = pygame.image.load("images/brook.png").convert_alpha()
def make_move(self, move): move.check_validity(self) #Increase count for turns where no pawn moved or piece was obliterated or set it to zero if abs(self.board[tuple( move.coords[0])].type) == 1 or (self.board[tuple( move.coords[1])].type) != 0: self.n_half_turn = 0 else: self.n_half_turn += 1 #Check if castling and move the rook if True if abs(self.board[tuple( move.coords[0])].type) == 6 and abs(move.coords[1, 1] - move.coords[0, 1]) == 2: if move.colour == "white": if (move.coords[1, 1] - move.coords[0, 1]) == -2: self.board[7, 0] = Piece(0) self.board[7, 3] = Piece(2) elif (move.coords[1, 1] - move.coords[0, 1]) == 2: self.board[7, 7] = Piece(0) self.board[7, 5] = Piece(2) if move.colour == "black": if (move.coords[1, 1] - move.coords[0, 1]) == -2: self.board[0, 0] = Piece(0) self.board[0, 3] = Piece(-2) elif (move.coords[1, 1] - move.coords[0, 1]) == 2: self.board[0, 7] = Piece(0) self.board[0, 5] = Piece(-2) #Movement self.board[tuple(move.coords[1])] = self.board[tuple(move.coords[0])] self.board[tuple(move.coords[0])] = Piece(0) #Update array self.update_array() #If the piece that was moved is pawn now on the other side, promote it self.board[tuple(move.coords[1])].promote(move)
def is_valid_king_move(board, cords, row_vec, col_vec, player): """ Checks if the requested move is valid for the king """ # The King can move one step in any direction if abs(row_vec) <= 1 and abs(col_vec) <= 1: vec = [True] return vec # Check if castling if abs(col_vec) == 2: if board.map[cords[0]][cords[1]].get_has_moved() == False: if col_vec < 0: col = 0 else: col = 7 mid_col = cords[1] + (col_vec // 2) if board.map[cords[0]][mid_col].get_type() == " ": if board.map[cords[0]][col].get_has_moved() == False: if checks.is_king_in_check(board, player) == True: vec = [False, "Cannot castle while in check!"] return vec test_board = deepcopy(board) test_board.map[cords[0]][mid_col] = test_board.map[ cords[0]][cords[1]] test_board.map[cords[0]][cords[1]] = Piece( " ", " ", " ", " ") if checks.is_king_in_check(test_board, player) == True: vec = [False, "Cannot castle through a check!"] return vec test_board = deepcopy(board) test_board.map[cords[0]][cords[3]] = test_board.map[ cords[0]][cords[1]] test_board.map[cords[0]][cords[1]] = Piece( " ", " ", " ", " ") if checks.is_king_in_check(test_board, player) == True: vec = [False, "Cannot castle into a check!"] return vec # If this point is reached, the castle move is valid board.map[cords[0]][mid_col] = board.map[cords[0]][col] board.map[cords[0]][mid_col].set_has_moved() board.map[cords[0]][col] = Piece(" ", " ", " ", " ") vec = [True] return vec else: vec = [False, "Cannot castle through a piece!"] return vec vec = [False, "This is not a valid move for a King!"] return vec
def __init__(self, pos, board, player): Piece.__init__(self, pos, board, player) self.directions = dict(Directions.diagonals.items() + Directions.straight.items()) if self.player.colour == 0: self.img = pygame.image.load("images/wqueen.png").convert_alpha() else: self.img = pygame.image.load("images/bqueen.png").convert_alpha() self.img = pygame.transform.scale(self.img, (self.board.grid.cellsize, self.board.grid.cellsize))
def test_utility_is_inf_black(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) player_one = Player(Player.IDIOT, Piece.WHITE) player_two = Player(Player.IDIOT, Piece.BLACK) g_game = Game(player_one, player_two) inf = 99999999 self.assertEqual(inf, g_game.utility(board, player_two))
def test_move_a_pawn(self): board = Board(6, 6) piece_pawn_black = Piece(Piece.PAWN, Piece.BLACK) piece_pawn_white = Piece(Piece.PAWN, Piece.WHITE) board.add(piece_pawn_black, 3, 3) board.add(piece_pawn_white, 4, 3) self.assertFalse(board.move_piece(3, 3, 4, 3)) self.assertEqual(board.get_piece_in_pos(3, 3), piece_pawn_black) self.assertFalse(board.move_piece(4, 3, 3, 3)) self.assertEqual(board.get_piece_in_pos(4, 3), piece_pawn_white)
def test_add_pieces_to_board(self): piece_one = Piece(Piece.PAWN, Piece.BLACK) piece_two = Piece(Piece.PAWN, Piece.BLACK) piece_three = Piece(Piece.PAWN, Piece.WHITE) piece_four = Piece(Piece.PAWN, Piece.WHITE) board = Board(6, 4) pieces = [piece_one, piece_two, piece_three, piece_four] self.assertTrue(board.add(piece_one, 3, 2)) self.assertTrue(board.add(piece_two, 4, 1)) self.assertFalse(board.add(piece_three, 6, 4)) self.assertFalse(board.add(piece_four, 7, 0))
def __init__(self, screen, width, height, gui): self.screen = screen self.width = width self.height = height self.gui = gui self.boardimg = pygame.image.load(self.img_folder + "board.png") self.boardimg = pygame.transform.scale(self.boardimg, (width, height)) self.boardrect = self.boardimg.get_rect() self.star = pygame.image.load(self.img_folder + "star.png") self.black_pieceimg = pygame.image.load(self.img_folder + "black_piece.png") self.white_pieceimg = pygame.image.load(self.img_folder + "white_piece.png") self.pcwidth = self.width // 8 self.pcheight = self.height // 8 # initializing black pieces x = 0 y = 0 while y < 3: x = 0 while x < 8: if x % 2 != y % 2: piece = Piece(screen=self.screen, is_white=False, pos=(x, y), width=self.pcwidth, height=self.pcheight, image=self.black_pieceimg) self.locations[(x, y)] = piece self.black_pieces.append(piece) x += 1 y += 1 # initializing white pieces x = 0 y = 5 while y < 8: x = 0 while x < 8: if x % 2 != y % 2: piece = Piece(screen=self.screen, is_white=True, pos=(x, y), width=self.pcwidth, height=self.pcheight, image=self.white_pieceimg) self.locations[(x, y)] = piece self.white_pieces.append(piece) x += 1 y += 1
def main () : pygame.init() #初始化pygame screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT+100)) pygame.display.set_caption('俄罗斯方块') piece = Piece('Z', screen) while True: #游戏主循环 check_event(piece) screen.fill(BG_COLOR) draw_game_area(screen) Piece.paint(piece) pygame.display.flip()
def test_do_move_blocked_out_of_home(): p1 = Player.get(1) piece = Piece(1, 0, 0) status = [piece, Piece(0, 0, 15), Piece(0, 1, 15)] assert not is_valid_move(piece, 6, status) success = do_move(status, p1, 0, 6) assert not success assert status[0].progress() == 0
def test_get_move(): # get_move() should return the move with the maximum value test_ai = AI('B') test_board = Board([Piece('9WN'), Piece('17BN'), Piece('21BN')], 'B') assert test_ai.get_move(test_board) in [{ "position_from": "17", "position_to": "13" }, { "position_from": "21", "position_to": "18" }]
def playerHasLegalMoves(self, color) -> bool: """ returns whether or not a player has any legal moves left""" enemyPieces = self.getPositionsWhere( lambda piece: piece.color == color) if self.checkCheck(color): getLegalMoves = lambda piece: Piece.possibleMoves( *piece, self, legalMoves=self.getPositionsToProtectKing(color)) else: getLegalMoves = lambda piece: Piece.possibleMoves(*piece, self) return any(getLegalMoves(piece) != [] for piece in enemyPieces)
def test_moves_forced(): # If a piece can eat another one, it can only do that. # Also, it cannot eat a piece of its own color. test_piece = Piece('12WN') test_board = Board([test_piece, Piece('9BN')], 'W') assert test_piece.get_moves(test_board) == [{ "position": '5', "eats_piece": True }] pass
def __init__(self, pos, board, player): Piece.__init__(self, pos, board, player) self.directions = Directions.knight if self.player.colour == 0: self.img = pygame.image.load("images/wknight.png").convert_alpha() else: self.img = pygame.image.load("images/bknight.png").convert_alpha() self.img = pygame.transform.scale(self.img, (self.board.grid.cellsize, self.board.grid.cellsize))
def __init__(self, pos, board, player): Piece.__init__(self, pos, board, player) self.validMoves = [] self.directions = Directions.diagonals if self.player.colour == 0: self.img = pygame.image.load("images/wbishop.png").convert_alpha() else: self.img = pygame.image.load("images/bbishop.png").convert_alpha() self.img = pygame.transform.scale(self.img, (self.board.grid.cellsize, self.board.grid.cellsize))
def __init__(self, pos, board, player): Piece.__init__(self, pos, board, player) self.directions = Directions.knight if self.player.colour == 0: self.img = pygame.image.load("images/wknight.png").convert_alpha() else: self.img = pygame.image.load("images/bknight.png").convert_alpha() self.img = pygame.transform.scale( self.img, (self.board.grid.cellsize, self.board.grid.cellsize))
def _spawn_piece(self): ''' Produce a new piece ''' self.display.update_board() self.current_piece = Piece() try: self.display.add_piece(self.current_piece) self.display.draw() except OverlapError: print('Game Over') exit()
def __init__(self, color, board): self.color = color self.board = board self.piece_in_home = [] self.piece_in_game = [] self.remain_piece = [ Piece(color, board, self), Piece(color, board, self), Piece(color, board, self), Piece(color, board, self) ] self.can_move = []
def __init__(self, pos, board, player): Piece.__init__(self, pos, board, player) self.directions = dict(Directions.diagonals.items() + Directions.straight.items()) if self.player.colour == 0: self.img = pygame.image.load("images/wqueen.png").convert_alpha() else: self.img = pygame.image.load("images/bqueen.png").convert_alpha() self.img = pygame.transform.scale( self.img, (self.board.grid.cellsize, self.board.grid.cellsize))
def test_is_legal_movement_pawn(self): board = Board(6, 4) piece_pawn = Piece(Piece.PAWN, Piece.BLACK) piece_pawn_two = Piece(Piece.PAWN, Piece.BLACK) piece_king = Piece(Piece.KING, Piece.WHITE) piece_white_pawn = Piece(Piece.PAWN, Piece.WHITE) board.add(piece_king, 5, 2) board.add(piece_pawn, 3, 2) board.add(piece_pawn_two, 4, 3) board.add(piece_white_pawn, 4, 1) available_positions = [[4, 2], [4, 1]] self.assertEquals(board.is_legal_movement(3, 2), available_positions)
def test_piece_one_short_block(self): piece = Piece(fake_client, 1, 2, 'abcd', test_dir) self.assertEqual(piece.num_blocks, 1) self.assertTrue(piece.not_all_blocks_requested()) block = piece.get_next_block() self.assertEqual(block[2], 2) (block_info, peer) = piece.get_next_block_and_peer_to_request() self.assertEqual(peer, None) self.assertEqual(block_info[0], 1) self.assertEqual(block_info[1], 0) self.assertEqual(block_info[2], 2**14) self.assertFalse(piece.not_all_blocks_requested())
def test_move_no_pawn(self): board = Board(6, 6) piece_king_white = Piece(Piece.KING, Piece.WHITE) piece_queen_black = Piece(Piece.QUEEN, Piece.BLACK) piece_rook_black = Piece(Piece.ROOK, Piece.BLACK) board.add(piece_king_white, 0, 2) board.add(piece_queen_black, 3, 3) board.add(piece_rook_black, 4, 3) self.assertTrue(board.move_piece(3, 3, 0, 0)) self.assertEqual(board.get_piece_in_pos(0, 0), piece_queen_black) self.assertTrue(board.move_piece(4, 3, 3, 3)) self.assertEqual(board.get_piece_in_pos(3, 3), piece_rook_black)
def test_moves_eat_options(): # A piece can choose which one to each if given more options. test_piece = Piece('13WN') test_board = Board([test_piece, Piece('9BN'), Piece('10BN')], 'W') assert test_piece.get_moves(test_board) == [{ "position": '4', "eats_piece": True }, { "position": '6', "eats_piece": True }]
def make_pieces(self): pieces = [] names = [ 'rook', 'knight', 'bishop', 'king', 'queen', 'bishop', 'knight', 'rook' ] for i in range(8): self.board[i][6] = Piece('pawn', BLACK) self.board[i][1] = Piece('pawn', WHITE) self.board[i][7] = Piece(names[i], BLACK) self.board[i][0] = Piece(names[i], WHITE) return pieces
def test_rotate_piece_counter_clockwise_through_all_rotations(self): p = Piece(Piece.T_SHAPE) rotations = [((0, 2), (1, 1), (1, 2), (2, 2)), ((1, 1), (1, 2), (1, 3), (2, 2)), ((0, 2), (1, 2), (1, 3), (2, 2)), ((0, 2), (1, 1), (1, 2), (1, 3)), ((0, 2), (1, 1), (1, 2), (2, 2))] for all_points in rotations: for point in all_points: self.assertEqual(p.value_at(point[0], point[1]), 2) p.rotate_counter_clockwise()
def test_moves_free(): # A piece can move freely if there is nothing on the way test_piece = Piece('18WN') test_board = Board([test_piece], 'W') assert test_piece.get_moves(test_board) == [{ "position": '13', "eats_piece": False }, { "position": '14', "eats_piece": False }]
def test(): # imbracing the grossness of python with dynmaic imports from piece import Piece cp = CaptureBoard() cp.printBoard() print("==========INSERT==========") for x in range(0, 16): name = "k%d" % x pos = cp.insertNextPos(Piece(name, "white")) print("x:%d y:%d cBoardX:%d cBoardY:%d" % (pos.getX(), pos.getY(), pos.getXBoard(), pos.getYBoard())) cp.printBoard() print() print("==========POPPING==========") for x in range(0, 16): pos, peice = cp.popLast() print("x:%d y:%d cBoardX:%d cBoardY:%d" % (pos.getX(), pos.getY(), pos.getXBoard(), pos.getYBoard())) print("%s:%s" % (peice.getName(), peice.getColor())) cp.printBoard() #print(cp.getBoard()) print("==========INSERT==========") for x in range(0, 16): name = "k%d" % x pos = cp.insertNextPos(Piece(name, "white")) print("x:%d y:%d cBoardX:%d cBoardY:%d" % (pos.getX(), pos.getY(), pos.getXBoard(), pos.getYBoard())) cp.printBoard() #print(cp.getBoard()) print("==========RESET==========") cp.resetBoard() cp.printBoard() #print(cp.getBoard()) print("==========INSERT==========") for x in range(0, 16): name = "k%d" % x pos = cp.insertNextPos(Piece(name, "white")) print("x:%d y:%d cBoardX:%d cBoardY:%d" % (pos.getX(), pos.getY(), pos.getXBoard(), pos.getYBoard())) cp.printBoard() #print(cp.getBoard()) print("==========POPPING==========") for x in range(0, 16): pos, peice = cp.popLast() print("x:%d y:%d cBoardX:%d cBoardY:%d" % (pos.getX(), pos.getY(), pos.getXBoard(), pos.getYBoard())) cp.printBoard()
def test_do_move_on_path(): p1 = Player.get(1) piece = Piece(0, 0, 16) status = [piece, Piece(1, 0, 1)] assert is_valid_move(piece, 1, status) success = do_move(status, p1, 0, 1) assert success assert status[0].progress() == 0 assert status[1].progress() == 2
def __init__(self, pos, board, player): Piece.__init__(self, pos, board, player) self.validMoves = [] self.directions = Directions.diagonals if self.player.colour == 0: self.img = pygame.image.load("images/wbishop.png").convert_alpha() else: self.img = pygame.image.load("images/bbishop.png").convert_alpha() self.img = pygame.transform.scale( self.img, (self.board.grid.cellsize, self.board.grid.cellsize))
def create_board(self): for row in range(ROWS): self.board.append([]) for col in range(COLS): if col % 2 == ((row + 1) % 2): if row < 3: self.board[row].append(Piece(row, col, WHITE)) elif row > 4: self.board[row].append(Piece(row, col, RED)) else: self.board[row].append(0) else: self.board[row].append(0)
def test_select_values_for_different_shapes(self): p = Piece(Piece.L_SHAPE) block_values = [(0, 1), (1, 1), (2, 1), (2, 2)] for point in block_values: self.assertEqual(3, p.value_at(point[0], point[1]), "point should exist at (%s, %s)" % (point[0], point[1])) p = Piece(Piece.T_SHAPE) block_values = [(0, 2), (1, 1), (1, 2), (2, 2)] for point in block_values: self.assertEqual(2, p.value_at(point[0], point[1]), "point should exist at (%s, %s)" % (point[0], point[1]))
def unmake_move(board, ix, iy, x, y, queen, to_revive, SYM): """ :param ix, iy: piece that will return to original position :param x, y: piece that will be again occupied :param queen: know if was queen or not """ board[y][x] = Piece(x, y, SYM) board[y][x].queen = queen board[iy][ix] = Piece(ix, iy, 0) for elem in to_revive: a, b = elem board[b][a] = Piece(a, b, -SYM)
def test1(): b = Board(10,10) base=Board(data='0,0,0,1,1,1,0,0,0,0;0,0,0,0,0,0,0,0,0,0;0,0,0,0,0,0,0,0,0,0;0,0,0,0,0,0,0,0,0,0;0,0,0,0,0,0,0,0,0,0;0,0,0,0,0,0,0,0,0,0;0,0,0,0,0,0,0,0,0,0;0,0,0,0,0,0,0,0,0,0;0,0,0,0,0,0,0,0,0,0;0,0,0,0,0,0,0,0,0,0;0,0,0,0,0,0,0,0,0,0;0,0,0,0,0,0,0,0,0,0;0,0,0,0,0,0,0,0,0,0;0,0,0,2,2,0,0,0,0,0;0,0,0,0,2,2,0,0,0,0;0,0,0,2,2,0,0,0,0,0;0,0,0,0,2,2,0,0,0,0;0,0,0,0,2,2,0,0,0,0;0,0,0,2,2,2,0,0,0,0;0,0,0,2,2,2,0,0,0,0') p1 = Piece('I') p2 = Piece('I') p2.rotate_right() loc1 = (0,0) loc2 = (2,2) path = b.get_path(p1, loc1, p2, loc2) result = b.get_feature_vector() print result
def test_footman(self): x = y = 3 footman = Piece('Footman', 'white', current_side='front', x=x, y=y) expected_moves = { 'move': set([ Point(2, 3), Point(4, 3), Point(3, 2), Point(3, 4), ]), } self.assertEqual(footman.available_moves(), expected_moves)
def test_utility_is_negative_inf_white(self): board = Board(4, 4) p_king_black = Piece(Piece.KING, Piece.BLACK) p_queen_black = Piece(Piece.QUEEN, Piece.BLACK) p_king_white = Piece(Piece.KING, Piece.WHITE) board.add(p_king_black, 0, 0) board.add(p_queen_black, 2, 0) board.add(p_king_white, 0, 2) player_one = Player(Player.IDIOT, Piece.WHITE) player_two = Player(Player.IDIOT, Piece.BLACK) g_game = Game(player_one, player_two) inf = -99999999 self.assertEqual(inf, g_game.utility(board, player_one))
def test_cross_victory(self): self.assertIsNone(self.b1.check_victory((0,0)), None) self.b1.place(Piece(), 0, 0) self.b1.place(Piece(), 1, 1) self.b1.place(Piece(), 2, 2) self.b1.place(Piece(), 0, 3) for i in range(4): self.assertIsNone(self.b1.check_victory((i, i))) self.assertIsNone(self.b1.check_victory((i, 3-i))) self.b1.place(Piece(), 3,3) for i in range(4): self.assertIsNotNone(self.b1.check_victory((i, i))) self.assertIsNone(self.b1.check_victory((i, 3-i)))
def init_dict(self): """ Initialize the two dictionaries that contains the pieces of the two teams """ for piece in self.PIECE: for i in range(self.CHESS_PCS_DIST[piece]): self.black_pieces[piece + '_' + str(i)] = Piece( 'black_' + piece + '_' + str(i), 'black', piece) for piece in self.PIECE: for i in range(self.CHESS_PCS_DIST[piece]): self.red_pieces[piece + '_' + str(i)] = Piece( 'red' + piece + '_' + str(i), 'red', piece)
def test_piece_info_hash_out_of_order(self): test_bytes = '\x00\x01\x02' empty_block = '\x00' * 2**14 test_hash = hashlib.sha1(empty_block + test_bytes).digest() piece = Piece(fake_client, 1, 2**14 + 3, test_hash, test_dir) piece.write_file = StringIO() self.assertEqual(piece.num_blocks, 2) self.assertFalse(piece.check_if_finished()) piece.add_block(2**14, test_bytes) self.assertFalse(piece.check_if_finished()) piece.add_block(0, empty_block) self.assertTrue(piece.check_if_finished()) self.assertTrue(piece.check_info_hash())
def initialize_king_and_rook(self): b_king = Piece(Piece.KING, Piece.BLACK) b_rook = Piece(Piece.ROOK, Piece.BLACK) w_king = Piece(Piece.KING, Piece.WHITE) w_rook = Piece(Piece.ROOK, Piece.WHITE) self.add(b_king, 2, 2) self.add(b_rook, 2, 3) self.add(w_king, 5, 2) self.add(w_rook, 1, 1)
def get_attackers(self, color, square): """Gets the attackers of a specific square. :param color: Filter attackers by this piece color. :param square: The square to check for. :yield: Source squares of the attack. """ if not color in [BLACK, WHITE]: raise KeyError("Invalid color: %s." % repr(color)) for x88, source in Square._x88_squares.iteritems(): piece = self._pieces[x88] if not piece or Piece.color(piece) != color: continue difference = x88 - square._x88 index = difference + X88.ATTACKER_DIFF klass = Piece.klass(piece) if X88.ATTACKS[index] & (1 << X88.SHIFTS[klass]): # Handle pawns. if klass == PAWN: if difference > 0: if Piece.color(piece) == WHITE: yield source else: if Piece.color(piece) == BLACK: yield source continue # Handle knights and king. if klass in [KNIGHT, KING]: yield source # Handle the others. offset = X88.RAYS[index] j = source._x88 + offset blocked = False while j != square._x88: if self._pieces[j]: blocked = True break j += offset if not blocked: yield source
def get_theoretical_ep_right(self, x): """Checks if a player could have an ep-move in theory from looking just at the piece positions. :param file: The file to check as a letter between `"a"` and `"h"`. :return: A boolean indicating whether the player could theoretically have that en-passant move. """ if x < 0 or x > 7: raise ValueError(x) ''' 3 states of en-passant p. pP .. .. .. .p .P .. .. ''' # Check there is a pawn on the right rank for e.p. y = 3 if self.fen._to_move == WHITE else 4 x88 = X88.from_x_and_y(x, y) piece = self._pieces[x88] if not piece: return False # If the square is not an opposite colored pawn then its not possible. ocolor = Piece.opposite_color(self.fen._to_move) if not Piece.is_klass_and_color(piece, PAWN, ocolor): return False # If the square below the pawn is not empty then it not possible. y = 2 if self.fen.turn == WHITE else 5 x88 = X88.from_x_and_y(x, y) if self[x88]: return False # If there is not pawn of opposite color on a neighboring file then its not possible. xs = [_x for _x in range(8) if _x>=0 and _x<8 and abs(x-_x) == 1] for _x in xs: x88 = X88.from_x_and_y(_x, y) piece = self._pieces[x88] if Piece.is_klass_and_color(piece, PAWN, Piece.opposite_color(self.fen._to_move)): return True # Else its just not possible. return False
def to_move(cls, position, san): san = str(san) # Castling moves. if san == "O-O" or san == "O-O-O": # TODO: Support Chess960, check the castling moves are valid. rank = 1 if position.fen.turn == "w" else 8 if san == "O-O": return Move( source=Square.from_rank_and_file(rank, 'e'), target=Square.from_rank_and_file(rank, 'g')) else: return Move( source=Square.from_rank_and_file(rank, 'e'), target=Square.from_rank_and_file(rank, 'c')) # Regular moves. else: matches = cls.san_regex.match(san) if not matches: raise ValueError("Invalid SAN: %s." % repr(san)) if matches.group(1): klass = Piece.klass(matches.group(1).lower()) else: klass = PAWN piece = Piece.from_klass_and_color(klass, position.fen._to_move) target = Square(matches.group(4)) source = None for m in position.get_legal_moves(): if position._pieces[m.source._x88] != piece or m.target != target: continue if matches.group(2) and matches.group(2) != m.source.file: continue if matches.group(3) and matches.group(3) != str(m.source.rank): continue # Move matches. Assert it is not ambiguous. if source: raise MoveError( "Move is ambiguous: %s matches %s and %s." % san, source, m) source = m.source if not source: raise MoveError("No legal move matches %s." % san) return Move(source, target, matches.group(5) or None)
def getValidMoves(self): ret = [ # Static list is easy (self.x, self.y+2), (self.x, self.y-2), (self.x-1, self.y-1), (self.x-1, self.y+1), (self.x+1, self.y-1), (self.x+1, self.y+1) ] ret = filterValidSpots(ret, Piece.getState().getWidth(), Piece.getState().getHeight()) ret = filterBlockedSpots(ret, Piece.getState()) ret.append((self.x, self.y)) return ret
def getValidAttacks(self): ret = [ # Static list is easy. Keep this sorted in order by direction (self.x, self.y-2), # 0 (self.x+1, self.y-1), # 1 (self.x+1, self.y+1), # 2 (self.x, self.y+2), # 3 (self.x-1, self.y+1), # 4 (self.x-1, self.y-1) # 5 ] ret2 = [ # Two spaces away (self.x, self.y-4), # 0 (self.x+1, self.y-3), # 0.5 (self.x+2, self.y-2), # 1 (self.x+2, self.y), # 1.5 (self.x+2, self.y+2), # 2 (self.x+1, self.y+3), # 2.5 (self.x, self.y+4), # 3 (self.x-1, self.y+3), # 3.5 (self.x-2, self.y+2), # 4 (self.x-2, self.y), # 4.5 (self.x-2, self.y-2), # 5 (self.x-1, self.y-3) # 5.5 ] # Get current dir + other two adjacent ones ret = [ # One square away ret[self.direction], ret[(self.direction+1)%6], ret[(self.direction-1)%6], # Two squares away ret2[self.direction*2], ret2[(self.direction*2+1)%12], ret2[(self.direction*2+2)%12], ret2[(self.direction*2-1)%12], ret2[(self.direction*2-2)%12], ] # Filter to only spots on board and that are blocked ret = filterValidSpots(ret, Piece.getState().getWidth(), Piece.getState().getHeight()) ret = filterUnblockedSpots(ret, Piece.getState()) ret = filterMyPieces(ret, Piece.getState(), self.player) # NOTE: Currently possible to attack your own troops return ret
def generate_picture_sprites(self, image, factor, gap): piece_width = image.get_width() // factor piece_height = image.get_height() // factor w = h = 0 for x in range(1, factor+1): for y in range(1, factor+1): if (gap is False) or x is not factor or y is not factor: sprite_img = SpriteManager.load(image, w, h, piece_width, piece_height) piece = Piece(sprite_img, (w, h), (x, y), factor) piece.add(self.sprites) h += piece_height else: break w += piece_width h = 0 self.last_piece = piece