用Python递归正方形
我试图让我的头在递归,我认为这将是有趣的尝试绘制递归包括正方形与旋转。
我可以使其迭代工作,但是当我从本身内部调用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()
链接地址: http://www.djcxy.com/p/80709.html