'How to randomize shapes and colors using turtle python?
Can someone please help me with drawing random shapes in random colors using turtle python?
Solution 1:[1]
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()
Solution 2:[2]
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)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Eshaan Gupta |
| Solution 2 |
