简化类似功能的Python Turtle绘图

时间:2018-02-26 02:34:58

标签: python python-3.x turtle-graphics

有没有办法简化这个功能,就if语句少而反复输入相同的代码?

此函数根据用户请求的数字创建正弦图。有很多重复的代码。我尝试使用列表来存储对象,但在尝试访问它们时会出错。我该如何解决这个问题?

 def createWaves(amp, count):
            even_num = [2, 4, 6, 8, 10, 12]
            alpha = createTurtle("turtle", "darkcyan", 2)
            alpha.ht()
            beta = createTurtle("turtle", "purple", 2)
            beta.ht()
            gamma = createTurtle("turtle", "orange", 2)
            gamma.ht()
            delta = createTurtle("turtle", "magenta", 2)
            delta.ht()
            epsilon = createTurtle("turtle", "deepskyblue", 2)
            epsilon.ht()
            zeta = createTurtle("turtle", "green", 2)
            zeta.ht()
            omega = createTurtle("turtle", "black", 3)
            omega.ht()
            if count == 0:
                alpha.st()
                for x in range(361):
                    y_alpha = (amp/even_num[0]) *(math.sin(math.radians(x*even_num[0])))
                    alpha.goto(x, y_alpha)
            elif count == 1:
                alpha.st()
                beta.st()
                omega.st()
                for x in range(361):
                    y_alpha = (amp/even_num[0]) *(math.sin(math.radians(x*even_num[0])))
                    y_beta = (amp/even_num[1]) *(math.sin(math.radians(x*even_num[1])))
                    y_omega = y_alpha + y_beta
                    alpha.goto(x, y_alpha)
                    beta.goto(x, y_beta)
                    omega.goto(x, y_omega)
            elif count == 2:
                alpha.st()
                beta.st()
                gamma.st()
                omega.st()
                for x in range(361):
                    y_alpha = (amp/even_num[0]) *(math.sin(math.radians(x*even_num[0])))
                    y_beta = (amp/even_num[1]) *(math.sin(math.radians(x*even_num[1])))
                    y_gamma = (amp/even_num[2]) *(math.sin(math.radians(x*even_num[2])))
                    y_omega = y_alpha + y_beta + y_gamma
                    alpha.goto(x, y_alpha)
                    beta.goto(x, y_beta)
                    gamma.goto(x, y_gamma)
                    omega.goto(x, y_omega)

0 个答案:

没有答案