简体   繁体   English

如果我有一个随机创建形状的 function,我如何将这些形状添加到一个组中? (CMU CS 学院)

[英]If I have a function that randomly creates shapes, how can I add those shapes to a group? (CMU CS Academy)

I'm working in CMU CS Academy's Sandbox and I currently have a function that will draw a rectangle of random size, color, and position:我在 CMU CS Academy 的 Sandbox 工作,我目前有一个 function,它将绘制一个随机大小、颜色和 position 的矩形:

#list of colors
app.colors = ['crimson', 'gold', 'dodgerBlue', 'mediumPurple']

#creating random shapes
import random

#draws a random rectangle with random points for size and center along with a random color
def drawRect(x, y):
    color = random.choice(app.colors)
    x = random.randint(5,390)
    y = random.randint(15,300)
    w = random.randint(10,40)
    h = random.randint(10,40)
    r = Rect(x,y,w,h,fill=color,border='dimGray')
    x = r.centerX
    y = r.centerY

#draws multiple random rectangles
def drawRects():
    for i in range(5):
        x = 50 * i
        y = 60 * i
        drawRect(x,y)
drawRects()

However, I want to add all the random rectangles that the function draws to a group so that I'm able to use the.hitsShape() method.但是,我想将 function 绘制的所有随机矩形添加到一个组中,以便我能够使用 .hitsShape() 方法。

I also thought about creating a list with the random x and y values, but I'm not sure how to create a list with coordinates in CS Academy.我还考虑过创建一个包含随机 x 和 y 值的列表,但我不确定如何在 CS Academy 中创建一个包含坐标的列表。 If you have any advice on my current code or what to do next, thank you so much!如果您对我当前的代码或下一步做什么有任何建议,非常感谢!

Firstly, you have forgotten to end your functions with return... , that way you can keep working with this data further in the code block.首先,您忘记了以return...结束函数,这样您就可以在代码块中进一步处理这些数据。 It's one of "best practices" in python.这是 python 中的“最佳实践”之一。
Also, I'm assuming you mean a collection by "group"?另外,我假设你的意思是“组”的集合?

You could save them in a tuple in this manner:您可以通过这种方式将它们保存在一个元组中:

def drawRect(x, y):
    ...
    r = Rect(x,y,w,h,fill=color,border='dimGray')
    ...
    return r

def drawRects():
    my_shapes = []
    for i in range(5):
        x = 50 * i
        y = 60 * i
        my_shapes.append( drawRect(x,y) )
    return my_shapes

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM