Random Colors with Shapes

Hello,

I’m new to processing and my task is to display shapes with randomized colors.

size(700,700)
background('#FF4477')

translate(random(100, 500), 30)

fill('#E3AB62')
noStroke() 
ellipse(random(100, 120), random (10, 35), 70,75)
fill('#9FCDE8')
ellipse(random(200,180), random(100,180), 50,50)
fill('#7FD17E')
ellipse(random(100,150), random(500,675), 90,90)

translate(random(300, 100), 80)

fill('#DE8BD4')
ellipse(random(360,450), random(500,100), 30,30)
fill('#FAF488')
ellipse(random(400,320), random(700,600), 65,65)

Instead of filling the shapes with an assigned color, I wanted to randomize them, is there any way how?

3 Likes

Welcome @bridgette

How about using random() with Processing’s RGB color scheme:

fill(random(0, 255), random(0, 255), random(0, 255))

EDIT: As @javagar pointed out, you should use random(0, 256) instead of random(0, 255). Why settle for 16,581,375 possible colours when you could have 16,777,216 :stuck_out_tongue_winking_eye:

3 Likes

Thank you!

So I tried this piece of code and the shapes are all filled with random colors, but is there any way to make them change color every time I run the program? Do I have to use a variable?

1 Like

I’m confused by your question –
random() functions, by default, produce different values each time you run a sketch.

For example, this code draws a circle with a random fill in a random position every time you (re)run the program, unless you uncomment the randomSeed() line:

size(700, 700)
#randomSeed(999)
fill(random(0, 255), random(0, 255), random(0, 255))
circle(random(width), random(height), 75)
3 Likes

It probably doesn’t really matter much here, but technically, we should do this if we want to allow for a full range of possible colors:

fill(random(0, 256), random(0, 256), random(0, 256))

See Processing.py > Reference > random().

A quote from that source:

If two parameters are specified, the function will return a float with a value between the two values. For example, random(-5, 10.2) returns values starting at -5 and up to (but not including) 10.2.

Note that the upper limit is exclusive. Therefore, if we want to allow for the intensities of the color components to range as high as 255, we need an upper limit of 256. While our eyes might not notice the distinction, edge cases might matter if we were performing some color analysis of pixels in the resulting image.

EDITED (2x on April 1, 2021)

RGB color intensity values are actually whole numbers. So what happens when we pass float values with fractional portions to the fill() function? Are the values rounded or are the portions of the values after the decimal point removed? The documentation at Processing.py Reference > fill() does not address that issue. However, we can experiment. :smile:

def setup():
    size(100, 100)
    noLoop()
def draw():
    noStroke()
    # truncation or rounding?
    ### let's pass some floats with fractional portions
    fill(200.3, 200.5, 200.7)
    rect(0, 0, width, height)
    c = get(width / 2, height / 2)
    print(red(c), green(c), blue(c))
    # output:
    # (200.0, 200.0, 200.0)
    # truncation to the nearest equal or lower whole number, it is!
    # also, the upper limit with the random() function is exclusive,
    # so use this to enable a full range of random RGB fill colors:
    # fill(random(0, 256), random(0, 256), random(0, 256))

Output:

(200.0, 200.0, 200.0)

Each of the color intensities was truncated to the nearest equal or lower whole number value.

1 Like

Using fill(random(0,255),random(0,255), random(0,255)); generates 1 random color for the entire array. Is there a way to make each shape in the array to have its own color?
I have used this code before. It works great for creating a multicolor grid, but not to have a shower of of shapes, each with a unique color.

1 Like

Welcome @Panda

There’s no array (list?) in any of the code above? Each time you call the fill() line with the random() functions, you get a new colour:

fill(random(0, 256), random(0, 256), random(0, 256))
circle(random(width), random(height), 5)
fill(random(0, 256), random(0, 256), random(0, 256))
circle(random(width), random(height), 5)
...

Or, if you want to do something with a loop to save time:

for col in range(10):
    fill(random(0, 256), random(0, 256), random(0, 256))
    circle(random(width), random(height), 5)

Or maybe you want to store the colours in a list:

colors = [
  color(random(0, 256), random(0, 256), random(0, 256)) 
  for col in range(10)
]

for col in colors:
    fill(col)
    circle(random(width), random(height), 5)

In this last example, I’ve used a Python list comprehension to define the colors list, but there are other ways you can do this if you’re not familiar with those.

Or, for persistent fills across frames without employing OOP:

def setup():
    global balls
    balls = [
      {'x': random(width), 'y': random(height/3), 
       'color': color(random(0, 256), random(0, 256), random(0, 256))} 
      for col in range(10)
    ]

def draw():
    background(255)
    for ball in balls:
        fill(ball['color'])
        circle(ball['x'], ball['y'], 5)
        ball['y'] += .1
1 Like

Hello, @Panda, and welcome to the Processing Forum!

We need additional information in order to provide you with concrete advice. However, the information that you did provide suggests that you may already be learning Python, and that you have learned about lists. The following assumes that this is true.

For each shape to have its own fill color, call the fill() function each time you are about to draw a shape.

Since a shape is described by multiple attributes, such as vertex coordinates and perhaps colors, we need to know how the information about each shape is being stored in your array (list). Have you learned about objects (Python classes)? Defining a class for your shapes may be useful for organizing your code. Then you would be able to create a list of shape objects.

You may benefit by posting the code that you have thus far. If you do so, it is important that you format the code for posting. See Guidelines—Asking Questions for advice on how to do this.

Below is an example, formatted for posting, that defines a Tri class for triangles, creates a list of Tri objects, and redraws them during each frame with a fill color that is chosen randomly for each triangle. Please feel free to ask any questions that you may have.

class Tri(object):
    # a triangle with coordinates and fill attributes
    def __init__(self, x1, y1, x2, y2, x3, y3, f):
        # vertex coordinates
        self.x1 = x1
        self.y1 = y1
        self.x2 = x2
        self.y2 = y2
        self.x3 = x3
        self.y3 = y3
        # fill color; a color object
        self.f = f 
    def display(self):
        # draw this Tri
        pushStyle()
        fill(self.f)
        triangle(self.x1, self.y1, self.x2, self.y2, self.x3, self.y3)
        popStyle()
    def set_fill(self, f):
        # set a fill color for this Tri
        self.f = f
        
def random_color():
    # return a random color (red, green blue, alpha)
    return color(random(256), random(256), random(256), random(256))

def setup():
    size(400, 400)
    global tri_list
    tri_list = [Tri(random(width), random(height),
                    random(width), random(height),
                    random(width), random(height),
                    random_color())
                for i in range(4)]

    frameRate(1)
    
def draw():
    for tri in tri_list:
        tri.display()
        tri.set_fill(random_color())

EDITED on April 2, 2021 to use pushStyle() and popStyle() in the code.

2 Likes

Thank you, Javagar. No, I am not learning Python, just Processing this term, but C next term.
I am working through the Processing book by Reas and Fry, for my Processing class. I have never programmed before, so I am learning a foreign language!
Yes, the :
fill(random(0, 255), random(0, 255), random(0, 255))
Changes the color of every shape in the window each time I run the program. What I don’t understand is why. When I used the same code for a grid I drew, each rect in the grid was a different, random color. Why would it effect a shape stampede (cascade of falling hearts) differently?

We will need to see the code in order to answer your question. Please post it, so we can take a look at it.

From the Beginning Processing book, the Pacman stampede:

float[] x = new float[3000];//declare and create array

void setup() {
size(240, 120);
smooth();
fill(random(0,255),random(0,255), random(0,255));//pac color
for (int i = 0; i < x.length; i++) {
x[i] = random(-1500, 200); } } //spacing

void draw() {
background(0);
for (int i = 0; i < x.length; i++) {
x[i] += 0.5; //increase array element
float y = i * 0.4;

arc(x[i], y, 12, 12, 0.52, 5.76); } }

1 Like

I think we’ve gone off-topic here. This is a Java-mode question, so you should probably create a new topic (not in the Processing.py/Python section).

I’m no Java-mode expert. It looks like you’re trying to execute this using arrays (not objects), so you might create a multi-dimensional array to hold x-coords and fills for each of your pacs –

float[][] pacs = new float[3000][3]; // multi-dimensional array

void setup() {
  size(240, 120); smooth();
  for (int i = 0; i < pacs.length; i++) {
    // array for each pac
    float[] pac = {
     random(-1500, 200), // x-coord
     random(0, 256), random(0, 256), random(0, 256) // pac fill
    };
    pacs[i] = pac;
  } 
}

void draw() {
  background(0);
  for (int i = 0; i < pacs.length; i++) {
    pacs[i][0] += 0.5; // increase x-coord
    float y = i * 0.4;
    // apply pac-specific fill and draw it
    fill(pacs[i][1], pacs[i][2], pacs[i][3]);
    arc(pacs[i][0], y, 12, 12, 0.52, 5.76); 
  }
}
1 Like

In your code, this statement is contained in the setup() function, which runs only once each time the program is executed:

fill(random(0,255),random(0,255), random(0,255));//pac color

It picks a random fill color that remains in effect for the entire execution of the remainder of the program, because the fill() function is not called again anywhere else within your code. Consequently, the chosen fill color is applied to every shape that is drawn.

Yes, that is true, so @Panda, if you would like to continue this discussion, it would be best to post your questions, along with the applicable code, in the Processing category. That category is a good place for discussing Processing code written for Java Mode.

EDITED (April 3, 2021) to make minor adjustments to the wording.