AySeven
AySeven

Reputation: 63

How to get python to generate random size?

I need to make my python code draw my stars in different sizes at random. I've tried every method I know but unable to figure it out...still trying to completely understand loops.

import turtle
import random

for n in range(60):
    turtle.penup()
    turtle.goto(random.randint(-400, 400), random.randint(-400, 400))
    turtle.pendown()

    red_amount   = random.randint( 0,  100) / 100.0
    blue_amount  = random.randint(0 , 100) / 100.0
    green_amount = random.randint( 0,  100) / 100.0
    turtle.pencolor((red_amount, green_amount, blue_amount))

    turtle.pensize(random.randint(1, 10))

    for i in range(6):
        turtle.begin_fill()
        turtle.forward(50)
        turtle.right(144)
        turtle.end_fill()

All it does currently is draw stars at the same size.

Upvotes: 0

Views: 3942

Answers (1)

cdlane
cdlane

Reputation: 41872

You've added code to randomize the color, starting position and pen width but there's none to change the size of the stars. The size is controlled by this statement:

turtle.forward(50)

but you don't want to simply replace the 50 with another call to the random module as your stars will come out irregular. You need to compute a random size before the loop and then use that size in the forward() call in the loop:

import turtle
import random

for n in range(60):
    turtle.penup()
    turtle.goto(random.randint(-400, 400), random.randint(-400, 400))
    turtle.pendown()

    red_amount = random.random()
    blue_amount = random.random()
    green_amount = random.random()
    turtle.color(red_amount, green_amount, blue_amount)

    turtle.pensize(random.randint(1, 10))

    size = random.randint(25, 100)

    turtle.begin_fill()

    for i in range(5):
        turtle.forward(size)
        turtle.right(144)

    turtle.end_fill()

turtle.done()

I've also made a few style changes to your code while I was at it.

Upvotes: 3

Related Questions