Wednesday, January 27, 2021

Python - Turtle Graphics (Day 18)

This is a 100 Days challenge to learn a new language (Python). 100 Days of Code - The Complete Python Pro Bootcamp 

I will post some notes to motivate myself to finish this challenge.


Goal



This section is to guide you how to use a new package/module.
It uses turtle package as an example.

Researching skill is important. You need to lean how to google, how to read documentation, and how to ask question from stackoverflow. In real life, as a developer, you need to solve problems by yourself or improve your skill by googling without guiding by teachers step by step.


How to import package/module


Basic import

Ex:
# import is a keyword
# turtle is a module name
import turtle

# Using the Turtle class in turtle module to create an object
my_turtle = turtle.Turtle()


from ... import ...

Ex:

# from is a keyword
# import is a keyword
# turtle is a module name
# Turtle is a thing in turtle module
from turtle import Turtle

# Using Turtle class to create an object
my_turtle = Turtle()


We even can import all things in module (but it is not recommended)
Ex:
# Import all things in turtle module
from turtle import *

# Using Turtle class to create an object
my_turtle = Turtle()


It can help you to reduce typing. But the drawback is that you cannot clearly know where the class comes from. Please try to avoid this coding style.

Aliasing Modules


Sometimes module names are quite long, and you may want to give them alias name to reduce the typing.

# import is a keyword
# as is a keyword
# turtle is a module name
# t is the alias name of turtle module name
import turtle as t

# Using Turtle class to create an object
my_turtle = t.Turtle()


Installing Modules


'turtle' is packed in the python standard library, so you don't need to install it before importing.

For example, if we want to use this hero package which is not in python standard library, then first of all, we need to run 'pip install heroes' to install it. Otherwise, you will get error such as "No module named 'heros'"

# import heroes package
import heroes

print(heroes.gen())


Error:
ModuleNotFoundError: No module named 'heroes'


Once you have installed it, the error above will be gone.


Tuple V.S. List



 * Immutable *

A tuple in Python is similar to a list.
The difference between these two is that we cannot change the elements of a tuple once it is assigned whereas we can change the elements of a list. Reference

my_tuple = (1, 3, 5)

# Try to update tuple
my_tuple[2] = 6


Error: 
typeError: 'tuple' object does not support item assignment



Exercise for turtle graphic


Exercise 1 - Draw a square

# import Turtlr Class from turtle module
from turtle import Turtle

# Initiate a turtle object
my_turtle = Turtle()
# Setup turtle shape
my_turtle.shape("turtle")

# loop for it four times for each edge of a square
for _ in range(4):
    my_turtle.forward(50)
    my_turtle.left(90)


Exercise 2 - Draw a dashed line

# import Turtlr Class from turtle module
from turtle import Turtle

# Initiate a turtle object
my_turtle = Turtle()
# Setup turtle shape
my_turtle.shape("turtle")

# How many dashed line
for i in range(5):
    # pendown: drawing when moving.
    my_turtle.pendown()
    my_turtle.forward(5)
    # penup: no drawing when moving.
    my_turtle.penup()
    my_turtle.forward(5)


Exercise 3 - Draw a triangle, square, pentagon, hexagon, heptagon, octagon, nonagon, and decagon

# import Turtlr Class from turtle module
from turtle import Turtle

# Initiate a turtle object
my_turtle = Turtle()
# Setup turtle shape
my_turtle.shape("turtle")

# Define a draw function
def draw(num_sides):
    """draw"""
    for _ in range(num_sides):
        my_turtle.forward(50)
        my_turtle.left(360 / num_sides)


# Ask user input
user_selection = int(
    input(
        "Draw a triangle, square, pentagon, hexagon, heptagon,
octagon, nonagon, and decagon? "
    )
)

draw(user_selection)


Exercise 4 - Generate a random walk

# import random module
import random

# import Turtlr Class from turtle module
from turtle import Turtle

# Initiate a turtle object
my_turtle = Turtle()
# Setup turtle shape
my_turtle.shape("turtle")

# Define direction list
# Reference:
# https://docs.python.org/3/library/turtle.html#turtle.setheading
diections = [0, 90, 180, 270]

# run 500 times
for _ in range(500):
    my_turtle.forward(random.randint(1, 40))
    my_turtle.setheading(random.choice(diections))


Exercise 5 - Draw a Spirograph

# import Turtle Class from turtle module
from turtle import Turtle

# Initiate a turtle object
my_turtle = Turtle()
# Setup turtle shape
my_turtle.shape("turtle")
# Setup turtle speed
my_turtle.speed("fastest")

# Draw
def draw(size_of_gap):
    """draw"""

    # how many circle
    for _ in range(int(360 / size_of_gap)):
        my_turtle.circle(100)
        my_turtle.setheading(my_turtle.heading() + size_of_gap)


draw(10)



Challenge - Hirst Painting


1. Using https://pypi.org/project/colorgram.py/ to extract colors from an image
2. Using turtle graphic to draw a spot painting like Hirst's with those extracted colors

Ex: Extract colors from an image via colorgram package 
# Import colorgram package
import colorgram

# Define a list to store tuple elements
color_list = []
# Extract 15 colors from an image.
colors = colorgram.extract("image.jpg", 15)

# Loop through all colors
for c in colors:
    color_list.append((c.rgb[0], c.rgb[1], c.rgb[2]))

# Print list
print(color_list)


Result:
[(221, 223, 226), (234, 229, 219), (236, 227, 232), (223, 231, 227),
(196, 164, 125), (156, 164, 179), (210, 205, 141), (148, 83, 61),
(83, 92, 116), (158, 176, 169), (188, 153, 162), (22, 25, 53),
(61, 21, 13), (183, 167, 42), (40, 23, 30)]


Ex: Use turtle graphic to draw a spot painting based on the colors from the first challenge
# import Turtle and Screen Class from turtle module
import random
from turtle import Turtle, Screen

# Define colors from the previous challenge
colors = [
    (221, 223, 226),
    (234, 229, 219),
    (236, 227, 232),
    (223, 231, 227),
    (196, 164, 125),
    (156, 164, 179),
    (210, 205, 141),
    (148, 83, 61),
    (83, 92, 116),
    (158, 176, 169),
    (188, 153, 162),
    (22, 25, 53),
    (61, 21, 13),
    (183, 167, 42),
    (40, 23, 30),
]

# Get Screen instance
screen = Screen()
# Setup color mode (rgb)
screen.colormode(255)

# Initiate a turtle object
my_turtle = Turtle()
# Hide turtle
my_turtle.hideturtle()
# Setup turtle speed
my_turtle.speed("fastest")
# No drawing when moving
my_turtle.penup()
# Setup starting position of turtle
my_turtle.setpos(-250, -250)

# Define how many dots we want to draw
remaining_dots = 100

# if 100 dots have not been drawn yet
while remaining_dots > 0:
    # Change Y position for every 10 dots
    if remaining_dots != 100 and remaining_dots % 10 == 0:
        my_turtle.setpos(-250, my_turtle.ycor() + 50)

    # Draw a circular dot with diameter size and using color
    my_turtle.dot(20, random.choice(colors))
    # Move
    my_turtle.forward(50)

    remaining_dots -= 1

# Bind bye() method to mouse clicks on the Screen.
screen.exitonclick()


No comments:

Post a Comment