builder.py

2.1 kB · python · 78 lines

1import numpy as np2from mrlypy.two import carpet_2d, net_2d, tree_2d, void_2d, Cell2d, magic_2d, special_2d, mosaic_2d3from .enums import Design, Group4from .models import Tile56# HELPERS78CELL_FACTORY = {9    Design.CARPET: carpet_2d,10    Design.NET: net_2d,11    Design.TREE: tree_2d,12    Design.VOID: void_2d,13}1415def tree_mask(n: int) -> np.ndarray:16    vertical_tree = tree_2d(n).types17    horizontal_tree = np.rot90(vertical_tree)18    mask = np.zeros((n, n), dtype=np.int8)19    mask[(vertical_tree == 1) | (horizontal_tree == 1)] = 120    mask[(vertical_tree == 1) & (horizontal_tree == 1)] = 221    return mask2223def build_cell(tile: Tile, i: int = 0, level: int = 1) -> Cell2d:24    anti = tile.anti[i] if tile.anti else False25    design = tile.design[i]26    number = tile.number[i]27    rotation = tile.rotation[i]28    cell = CELL_FACTORY[design](number)29    if anti:30        cell.invert()31    if level > 1:32        cell.fractal(level)33    if rotation != 0:34        cell.rotate(rotation)35    return cell3637# GROUP BUILDERS3839def general_tile(tile: Tile) -> Cell2d:40    return build_cell(tile, 0)4142def fractal_tile(tile: Tile) -> Cell2d:43    return build_cell(tile, 0, tile.level[0])4445def magic_tile(tile: Tile) -> Cell2d:46    count = len(tile.design)47    cells = [build_cell(tile, i) for i in range(count)]48    return magic_2d(cells)4950def special_tile(tile: Tile) -> Cell2d:51    cell = tree_2d(number=tile.number[0])52    mask = CELL_FACTORY[tile.design[0]](tile.mask)53    if tile.rotation[0] != 0:54        mask.rotate(tile.rotation[0])55    if tile.flip:56        mask.invert()57    return special_2d(mask.types, cell)5859def mosaic_tile(tile: Tile) -> Cell2d:60    mask = tree_mask(tile.mask)61    cells = [build_cell(tile, i) for i in range(3)]62    return mosaic_2d(mask, cells)6364BUILD_FACTORY = {65    Group.GENERAL: general_tile,66    Group.FRACTAL: fractal_tile,67    Group.MAGIC: magic_tile,68    Group.SPECIAL: special_tile,69    Group.MOSAIC: mosaic_tile,70}7172# BUILD7374def build(tile: Tile) -> Tile:75    tile.cell = BUILD_FACTORY[tile.group](tile)76    if tile.invert:77        tile.cell.invert()78    return tile