Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a Bright Random Colour Python

Tags:

python

enter image description here

Hi all, in my snake game program, I need to generate a random colour multiple times when the user selects a "Rainbow" theme. After looking online, I found this:

Generating a Random Hex Color in Python

The answer with the most votes gave a solution of

import random
r = lambda: random.randint(0,255)
print('#%02X%02X%02X' % (r(),r(),r()))

However, this program generates very dim colours as well; for example dark brown and sometimes even black. As you can see, some of those colours do not match a rainbow-y theme.

How would you change the above code so that you get vibrant colours like bright orange, pink, red, blue, etc, you get the idea. A hypothetical solution was to increase minimum value of randint r, but that just made all the colours very white. :'(

Plz, plz, plz, help will be very much appreciated.

Thanks guys!

like image 362
Lunkle Avatar asked Apr 16 '17 12:04

Lunkle


People also ask

How do you generate a random color in python?

Using random() function to generate random colors To begin, import the random function in Python to obtain a random color. The variable r stands for red, g stands for green, and b stands for blue. We already know that the RGB format contains an integer value ranging from 0 to 255.


2 Answers

Create a random HLS color (using numbers around .5 as the "level" parameter and numbers above .5 as the "saturation" parameter) and convert them to RGB:

import random
import colorsys
h,s,l = random.random(), 0.5 + random.random()/2.0, 0.4 + random.random()/5.0
r,g,b = [int(256*i) for i in colorsys.hls_to_rgb(h,l,s)]

That will ensure you'll always have highly saturated, bright colors.

like image 98
Tim Pietzcker Avatar answered Nov 15 '22 08:11

Tim Pietzcker


If you start the random with a higher number the color will be lighter, for example:

import random

def random_color():
        rand = lambda: random.randint(100, 255)
        return '#%02X%02X%02X' % (rand(), rand(), rand())
like image 31
Yakir Tsuberi Avatar answered Nov 15 '22 08:11

Yakir Tsuberi