How to make rainbow color with RBG color in Python Turtle Graphics?

Viewed 24

How to make rainbow color with RBG color in Python Turtle Graphics? I think it's can be a loop?

1 Answers

Code:

# Imports #
import turtle
import time

# Colors
tuples = [
    (148, 0, 211),
    (75, 0, 130),
    (0, 0, 255),
    (0, 255, 0),
    (255, 255, 00),
    (255, 127, 0),
    (255, 0, 0),
]

# Average between two numbers with a coefficient
def between(a, b, coef):
    return int(a * (1 - coef) + b * coef) / 255

# Draw a rainbow
## Size: The size of the line (in px)
## Period: The number of period in that rainbow
def draw_rainbow(period: int, size: int):
    period_size = round(size / period)
    coef = 0
    for _ in range(period):
        next_color = tuples[0]
        for i in range(period_size):
            previous_color = tuples[ (i * len(tuples)) // period_size]
            if next_color == previous_color:
                coef = 0
            next_color = tuples[(1 + (i * len(tuples)) // period_size) % len(tuples)]
            color_tuple = tuple(between(previous_color[j], next_color[j], coef / (period_size / len(tuples))) for j in range(3))
            coef += 1
            turtle.pencolor(color_tuple)
            turtle.fd(1)



# Example:
turtle.width(10)
draw_rainbow(3, 200)

Result:

enter image description here

( If you have any questions, don't hesitate )

Related