1

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
J___389
  • 13
  • 3

1 Answers1

0

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
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Lev Slinsen
  • 369
  • 1
  • 4
  • 21