我试图建立一个蒙德里安艺术创造者,允许你创造任意数量的矩形,每个都有一个随机大小。我可以创建随机大小,但我遇到的麻烦是让它创建两个以上的随机矩形。在
import turtle
import random
turtle.screensize(1000,1000)
turtle.setworldcoordinates(-500,-500,500,500)
piet = turtle.Turtle()
piet.speed(3)
#primary colors, red, blue, yellow
#piet.color(red,blue,yellow)
rectangles = int(input('How many rectangles should be drawn?'))
rectangle_w = int(input('What should be the max width of the rectangles?'))
rectangle_h = int(input('What should be the max height of the rectangles?'))
def mondrian(t,random_w,random_h):
for number_r in range(1):
for box in range(2):
t.left(90)
t.forward(random_w)
t.left(90)
t.forward(random_h)
mondrian(piet,random.randint(10,rectangle_w),random.randint(10,rectangle_h))
def repeat_mondrian():
while mondrian(piet,random.randint(10,rectangle_w),random.randint(10,rectangle_h)) < rectangles:
return False
repeat_mondrian()
所以你说的对,但我发现它多了一个矩形。所以我从for循环中的矩形中减去1。谢谢您!在
不要在这里使用
while
。要调用函数rectangle
次,请使用for-loop
:注意,在Python中,如果函数结束时没有到达
return
语句,那么默认情况下函数返回None
。因此mondrian
函数总是返回None
。在所以情况
^{pr2}$相当于
因为
None
比任何一个数都小,所以在Python2中它总是正确的。在Python3中,比较None < rectangles
会引发一个类型错误!在代码从不绘制多个矩形的原因是
return-statement
:使Python在
while-loop
中的第一次迭代之后退出repeat_mondian
。在相关问题 更多 >
编程相关推荐