Search code examples
graphicsdrawdrawableturtle-graphicspython-turtle

What actually happens in this code? I use the Python Turtle library to draw the fireworks, and I try to use random RGB color


import turtle
import random
t = turtle.Turtle()
w = turtle.Turtle()
t.speed(0) 
w.speed(0)
w.penup()
t.penup()
def randcolor():
    col1 = random.randint(0,255)
    col2 = random.randint(0,255)
    col3 = random.randint(0,255)
    randcol = (col1, col2, col3)
    return randcol
def drawfw1(angle):
    x = random.randint(0, 100)
    y = random.randint(0, 100)
    t.goto(x, y)
    t.pendown()
    for _ in range(random.randint(30,100)):
        t.fd(200)
        t.left(angle)
    t.penup()

def drawfw2(angle):
    x = random.randint(0, 100)
    y = random.randint(0, 100)

    w.goto(x, y)
    w.pendown()
    for _ in range(random.randint(30,100)):
        w.fd(200)
        w.left(angle)
    w.penup()

while True:
    for _ in range(2):
        t.pencolor(randcolor())
        w.pencolor(randcolor())
        angle = random.randint(99,179)
        angle2 = random.randint(99,179)
        drawfw1(angle)
        drawfw2(angle2)
    t.clear()
    w.clear()

This code is to program the random drawing firework

I actually trying to do something with this, and I know it was right. But then, the visual studio is not working and the turtle library also. How can I fix this problems.


Solution

  • This appears to be due to a common turtle color error. Turtle supports two color modes, with the RGB values as integers from 0 - 255 or as floats from 0.0 to 1.0. The float mode is the default. To switch to the other mode, you need to do:

    colormode(255)
    

    Below is a simplification of your code with this fix.

    from turtle import Screen, Turtle
    from random import randrange
    
    def randcolor():
        red = randrange(256)
        green = randrange(256)
        blue = randrange(256)
        return (red, green, blue)
    
    def drawfw(angle):
        x = randrange(100)
        y = randrange(100)
    
        turtle.goto(x, y)
        turtle.pendown()
    
        for _ in range(randrange(30, 100)):
            turtle.forward(200)
            turtle.left(angle)
    
        turtle.penup()
    
    screen = Screen()
    screen.colormode(255)
    
    turtle = Turtle()
    turtle.speed('fastest')
    turtle.penup()
    
    while True:
        for _ in range(4):
            turtle.pencolor(randcolor())
            angle = randrange(99, 180)
            drawfw(angle)
    
        turtle.clear()