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:

# 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

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. What should I do to my current code? What should I do next?

Asked By: J___389



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
    return my_shapes
Answered By: Lev Slinsen
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.