首页 > 解决方案 > 如何生成正方形、五边形等网格形状?

问题描述

我发现这个生成六边形网格的代码,我想不通。如果有人可以提供帮助,我需要生成其他类型的网格(正方形、五边形......等)。我应该寻找或研究什么来理解这种代码?

class Hexagon(Xshape):
    """A gridded hexagon."""
    @classmethod
    def _make_specification(cls):
        """Return a dict that describes this Xshape."""
        side = 1.0
        h = side * math.sin(math.pi / 3.0)
        # vertex calculations
        # shared horizontal and vertical rails
        top_rail = 0.0
        vmid_rail = h
        bottom_rail = 2.0 * h
        left_rail = -1.5 * side
        midleft_rail = -1.0 * side
        midright_rail = 0.0
        right_rail = 0.5 * side
        # point coordinates
        left_pt = (vmid_rail, left_rail)
        topleft_pt = (top_rail, midleft_rail)
        topright_pt = (top_rail, midright_rail)
        right_pt = (vmid_rail, right_rail)
        bottomright_pt = (bottom_rail, midright_rail)
        bottomleft_pt = (bottom_rail, midleft_rail)
        # build components separately to avoid long lines
        c = {(0, 0): {'name': 'hexagon',
                      'clockwise_edge_names': ('top', 'top right',
                                               'bottom right', 'bottom',
                                               'bottom left', 'top left'),
                      'edges': {(-1, 0): {'name': 'top',
                                          'counter_vertex': topleft_pt},
                                (0, 1): {'name': 'top right',
                                         'counter_vertex': topright_pt},
                                (1, 1): {'name': 'bottom right',
                                         'counter_vertex': right_pt},
                                (1, 0): {'name': 'bottom',
                                         'counter_vertex': bottomright_pt},
                                (0, -1): {'name': 'bottom left',
                                          'counter_vertex': bottomleft_pt},
                                (-1, -1): {'name': 'top left',
                                           'counter_vertex': left_pt}}}}
        d = {'name': 'Hexagon',
             'reference_length': side,
             'graph_offset_per_row': (2.0 * h, 0.0),
             'graph_offset_per_col': (-1.0 * h, 1.5 * side),
             'components': c}
        return d

    @classmethod
    def origin_index(cls, index):
        """Return the equivalent index when the supershape is at the origin."""
        origin_row, origin_col = 0, 0  # there's only one shape so always origin
        return origin_row, origin_col

标签: pythongridshapes

解决方案


推荐阅读