How to randomize shapes and colors using turtle python?

Can someone please help me with drawing random shapes in random colors using turtle python?

Upvotes: 0

Views: 1650

Answers (2)

gerald
gerald

Reputation: 418

Here is some very straight-forward code for random moves and colors:

import turtle
import random
pat = turtle.Turtle()
turtle.Screen().bgcolor('black')
colors = ["red", "yellow", "blue"]

for i in range(500):
    pat.color(random.choice(colors))
    x = random.randint(1,4)
    if x == 1:
        pat.forward(30)
    elif x == 2:
        pat.back(30)
    elif x == 3:
        pat.right(30)
    elif x == 4:
        pat.left(30)

Upvotes: 0

Eshaan Gupta
Eshaan Gupta

Reputation: 614

Sharing your attempt first is appreciated. Here is a simple program that chooses a random colour and shape from a list and draws it. You can add more colours in the list or more functions to draw different shapes.

Feel free to ask for clarifications in the comments below...

import random

color_list = ["red" , "green" , "blue"]
shape_list = ["square" , "circle" , "triangle"]

myTurtle = turtle.Turtle()
myTurtle.hideturtle()
myTurtle.color(random.choice(color_list))

def drawSquare():
    for i in range(4):
        myTurtle.forward(100)
        myTurtle.left(90)

def drawCircle():
    myTurtle.circle(100)

def drawTriangle():
    for i in range(3):
        myTurtle.forward(100)
        myTurtle.left(120)
        
random_shape = random.choice(shape_list)

if random_shape == "square":
    drawSquare()
elif random_shape == "circle":
    drawCircle()
elif random_shape == "triangle":
    drawTriangle()

Upvotes: 1

Related Questions