Python的递归方块

时间:2016-07-02 20:37:04

标签: python canvas recursion tkinter

我试图绕过递归,我认为尝试使用旋转绘制递归包含的正方形会很有趣。

我可以让它迭代地工作,但是当我从内部调用recursive_square函数时,它不起作用。

有人可以解释为什么会这样,并指出我在概念上缺少的东西吗?

from Tkinter import *
import math

WIDTH = 600
HEIGHT = 600
CANVAS_MID_X = WIDTH/2
CANVAS_MID_Y = HEIGHT/2
CENTER = (CANVAS_MID_X, CANVAS_MID_Y)
SIDE = WIDTH - 50

root = Tk()
geometry = "%dx%d+500+100" % (WIDTH, HEIGHT)
root.geometry(geometry)
canvas = Canvas(root, bg="black", height=HEIGHT, width=WIDTH)
canvas.pack()

original_vertices = [
    [CANVAS_MID_X - SIDE/2, CANVAS_MID_Y - SIDE/2],
    [CANVAS_MID_X + SIDE/2, CANVAS_MID_Y - SIDE/2],
    [CANVAS_MID_X + SIDE/2, CANVAS_MID_Y + SIDE/2],
    [CANVAS_MID_X - SIDE/2, CANVAS_MID_Y + SIDE/2],
]

def recursive_square(angle=0, points=original_vertices, center=CENTER, side=SIDE):
    if angle < 45:
        angle = math.radians(angle)
        cos_val = math.cos(angle)
        sin_val = math.sin(angle)
        cx, cy = center
        offset = (side * math.tan(angle))/(1 + math.tan(angle))
        new_points = [[x, y] for x,y in points]
        new_points[0][0] += offset
        new_points[1][1] += offset
        new_points[2][0] -= offset
        new_points[3][1] -= offset

        canvas.create_polygon(new_points, outline="red")
        #recursive_square(angle + 5)

for angle in xrange(0,45,5): # iterative version
    recursive_square(angle)

#recursive_square()

mainloop()

0 个答案:

没有答案