Python Zelle Graphics - 绘图中的递归函数?

时间:2014-11-23 00:08:55

标签: python recursion zelle-graphics

the goal

enter image description here

import graphics
def main():
    window = graphics.GraphWin("x", 600, 400)
    cntr = graphics.Point(300,200)
    size = 200
    wrapdiamond(size, window,cntr)
    window.getMouse()
def wrapdiamond(size, window,cntr):
    count = 0
    if count == 4:
        return
    if count < 4:
        diamond(size,window,"black", cntr)
        x= cntr.getX()+-0.5*size
        y = cntr.getY()+-0.5*size
        cntr= graphics.Point(x,y)
        size = size*0.33
        count +=1
        diamond(size,window,"black", cntr)

def diamond(size,window,color,cntr):
    p1 = cntr.clone()
    p1.move(0,-0.5*size)
    x1 = p1.getY()
    newcntr = graphics.Point(300,x1)
    p2 = cntr.clone()
    p2.move(-0.5*size,0)
    p3 = cntr.clone()
    p3.move(0,0.5*size)
    p4 = cntr.clone()
    p4.move(0.5*size,0)
    diamond= graphics.Polygon(p1, p2, p3, p4)
    diamond.setFill("black")
    diamond.draw(window)

所以最重要的是我的目标。我需要递归地执行此操作(调用相同的函数),移动中心点,大小和颜色。我觉得我现在的方法很可能会让我硬编码。我如何递归地实现这个?

2 个答案:

答案 0 :(得分:2)

已经过了几年,所以我认为这是关于解决问题的时间:

import graphics

def wrapdiamond(size, window, outline_color, fill_color, center, depth=1):

    if depth <= 0:
        return

    diamond(size, window, outline_color, fill_color, center)

    if depth <= 1:  # avoid going through the motions...
        return

    new_size = size * 0.33

    for x in (-1.0, 1.0):
        for y in (-1.0, 1.0):
            new_center = center.clone()
            new_center.move(x * size/2, y * size/2)
            # swap fill and outline colors on recursion
            wrapdiamond(new_size, window, fill_color, outline_color, new_center, depth - 1)

def diamond(size, window, outline_color, fill_color, center):
    p1 = center.clone()
    p1.move(0, -0.5 * size)
    p2 = center.clone()
    p2.move(-0.5 * size, 0)
    p3 = center.clone()
    p3.move(0, 0.5 * size)
    p4 = center.clone()
    p4.move(0.5 * size, 0)

    diamond = graphics.Polygon(p1, p2, p3, p4)
    diamond.setOutline(outline_color)
    diamond.setFill(fill_color)
    diamond.draw(window)

my_window = graphics.GraphWin("Recursive Diamonds", 900, 600)
my_center = graphics.Point(450, 300)

wrapdiamond(250, my_window, "gold", "black", my_center, 4)

my_window.getMouse()
my_window.close()

wrapdiamond()是递归函数,它在一个具有较小大小和重新调整中心的循环中调用自身。它还交换轮廓并填充颜色以形成交替模式:

enter image description here

答案 1 :(得分:0)

如果您遇到递归问题,可能会让您重新开始

def rdraw(x,y,level=1,max_level=5):
    draw_diamond(level)
    d = distance(level)
    if (level+1)<=max_level:
        rdraw(x+d,y+d,level+1)
        rdraw(x+y,y-d,level+1)
        rdraw(x-y,y+d,level+1)
        rdraw(x-y,y-d,level+1)

rdraw(0,0)