循环龟盒图形命令

时间:2014-10-05 23:55:38

标签: python

我正在尝试使用循环创建一系列

在Turtle中创建基本图形

4个黄色方框,一边是160个单位,用

4个较小的蓝色盒子,一半大小叠加在黄色上,

4个较小的绿色框​​,一半是蓝色的蓝色,

4白色和4红色以相同的方式。

我无法创建循环来执行此操作。 到目前为止,这是我的代码,谢谢!:

from turtle import Turtle
t = Turtle()

for i in range(4):
    t.begin_fill ()
    t.fillcolor("yellow")
    t.forward(160)
    t.left(90)
    t.forward(160)
    t.left(90)
    t.forward(160)
    t.left(90)        
    t.forward(160)
    t.end_fill()
    t.hideturtle( )

for i in range(4):
    t.begin_fill ()
    t.fillcolor("blue")
    t.forward(120)
    t.left(90)
    t.forward(120)
    t.left(90)
    t.forward(120)
    t.left(90)
    t.forward(120)
    t.end_fill()
    t.hideturtle( )

for i in range(4):
    t.begin_fill ()
    t.fillcolor("green")
    t.forward(80)
    t.left(90)
    t.forward(80)
    t.left(90)
    t.forward(80)
    t.left(90)
    t.forward(80)
    t.end_fill()
    t.hideturtle( )

for i in range(4):
    t.begin_fill ()
    t.fillcolor("white")
    t.forward(40)
    t.left(90)
    t.forward(40)
    t.left(90)
    t.forward(40)
    t.left(90)
    t.forward(40)
    t.end_fill()
    t.hideturtle( )

for i in range(4):
    t.begin_fill ()
    t.fillcolor("red")
    t.forward(20)
    t.left(90)
    t.forward(20)
    t.left(90)
    t.forward(20)
    t.left(90)
    t.forward(20)
    t.end_fill()
    t.hideturtle( )

2 个答案:

答案 0 :(得分:0)

因为唯一的移动是三次(向前,向左)和一次移动(向前,向右),所以你可以通过将这个基本(向前 - 向左)动作封装到一个函数中来开始压缩代码。例如。

def fw_lft():
    t.begin_fill()
    t.fillcolor()
    t.forward(160)
    t.left(90)

然后你可以在一个重复输入功能两次的函数中调用这个函数。 E.g。

def twice(f):
    f()
    f()

另一个函数可以通过重复两次2次并添加一个右移动来绘制一个完整的正方形:

def square():
    twice(fw_lft)
    twice(fw_lft)
    t.right(90)

最后一次重复方形图画两次:

def four_squares():
    twice(square)
    twice(square)

当你调用最后一个函数时,你有前四个方格。 这是压缩代码(=封装到函数中)的基本概念,然后您可以控制循环的流程等。

---我需要更多的学习才能获得以全局方式定义的颜色输入,这样你就可以拥有four_squares(c = color),但这篇文章有一些示例信息:{{3 }}

答案 1 :(得分:0)

这听起来像是一个家庭作业问题,所以我不想放弃太多。

你需要的是写一个盒子功能,可以绘制任何大小和任何颜色的盒子。它可能看起来像这样:

def myBoxFunction(size, color):
    # draw a box of the right size, and the right color.
    # hint: use a loop to draw the four sides.

然后你可以"打电话"具有不同参数的函数,根据需要多次,如下所示:

myBoxFunction(160, "yellow")
myBoxFunction(80, "blue") # for example

您可以使用循环绘制每个尺寸所需的四个框中的每个框来保存更多代码。

您可以通过循环遍历所需的大小和颜色集合来保存更多代码,如下所示:

for size, color in ((160, "yellow"), (120, "blue")):
    myBoxFunction(size, color) # only draws one box, but you get the idea.