Home > Net >  If I have a function that randomly creates shapes, how can I add those shapes to a group? (CMU CS Ac
If I have a function that randomly creates shapes, how can I add those shapes to a group? (CMU CS Ac

Time:01-26

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:

#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.

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. If you have any advice on my current code or what to do next, thank you so much!

CodePudding user response:

Firstly, you have forgotten to end your functions with return ..., that way you can keep working with this data further in the code block. It's one of "best practices" in 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
  • Related