Recursive Squares with Python

I'm trying to get my head around recursion and I thought it would be fun to try drawing recursive included squares with rotation.

I can make it work iteratively, but when I call the recursive_square function from within itself, it doesn't work.

Could someone explain why this is, and point out what I'm missing conceptually?

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()
链接地址: http://www.djcxy.com/p/80710.html

上一篇: Java中正方形的递归平分

下一篇: 用Python递归正方形