import sys

def should_apply_gravity(terrain):
    width = len(terrain)
    return any(terrain[x][y] >= 4 for x in range(width) for y in range(width))


def show_terrain(terrain):
    width = len(terrain)
    for x in range(width):
        for y in range(width):
            print(" ·●⬤"[terrain[x][y]], end="")
        print()


def apply_gravity(terrain):
    """
    $ python -m pyperf timeit --fast -s 'from examples.sandpile import main' 'main(10_000, False)'
    ...........
    Mean +- std dev: 15.4 sec +- 0.4 sec
    """
    width = len(terrain)
    while should_apply_gravity(terrain):
        for x in range(width):
            for y in range(width):
                if terrain[x][y] >= 4:
                    terrain[x][y] -= 4
                    terrain[x - 1][y] += 1
                    terrain[x + 1][y] += 1
                    terrain[x][y + 1] += 1
                    terrain[x][y - 1] += 1


def main(height, show=True):
    width = int(height ** .5) + 1
    terrain = [[0] * width for _ in range(width)]
    terrain[width // 2][width // 2] = height
    apply_gravity(terrain)
    if show:
        show_terrain(terrain)


if __name__ == "__main__":
    main(int(sys.argv[1]))
