snowflake

import matplotlib.pyplot as plt

plt.rcParams['font.sans-serif'] = ['SimHei']

plt.rcParams['axes.unicode_minus'] = False

def replacement(str, rules, order):

    for i in range(order):

        dst = ""

        for s in str:

            if s in rules:

                dst += rules[s]

            else:

                dst += s

        str = dst

    return str

def interpretation(str, actions, rotate, angle, x, y):

    import math

    point_x = [x,]

    point_y = [y,]

    for s in str:

        if s not in actions:

            continue

        if actions[s] == "left":

            angle -= rotate

        elif actions[s] == "right":

            angle += rotate

        elif actions[s] == "forward":

            r = angle / 180.0 * math.pi

            point_x.append(point_x[-1] + math.cos(r))

            point_y.append(point_y[-1] + math.sin(r))

    return point_x, point_y

# Koch snowflake

grammer = {

  "start": "F",

  "rules": {"F": "F+F--F+F"},

}

geometry = {

  "rotate": 60,

  "actions": {"+": "left", "-": "right", "F": "forward"}

}

##########################################################

fig, ax = plt.subplots(1, 5) 

for i in range(5):

    str = replacement(grammer["start"], grammer["rules"], i + 1)

    x, y = interpretation(str, geometry["actions"], geometry["rotate"], 30, 0, 0)

    sub = ax[i]

    sub.axis("off")

    sub.set_aspect("equal")

    sub.plot(x, y)

pl.title(' snowflake',x=-2)

plt.show()


你可能感兴趣的:(snowflake)