Kodewick
開始學 →

Python 畫雪人

三個越往上越小的雪球,戴上帽子、插上胡蘿蔔鼻子,天上還在下雪。

Python 畫雪人
完整程式碼(61 行)
import turtle
import random

screen = turtle.Screen()
screen.bgcolor("#16325c")
t = turtle.Turtle()
t.hideturtle()
t.speed(0)
t.penup()

# 地上的雪
t.goto(-320, -200)
t.color("white")
t.begin_fill()
for x, y in [(320, -200), (320, -320), (-320, -320)]:
    t.goto(x, y)
t.end_fill()

# 身子:三個雪球,越往上越小
t.goto(0, -130)
t.dot(200, "white")
t.goto(0, 10)
t.dot(150, "white")
t.goto(0, 120)
t.dot(110, "white")

# 眼睛、釦子
for x, y, size in [(-18, 135, 12), (18, 135, 12), (0, 40, 12), (0, 10, 12), (0, -20, 12)]:
    t.goto(x, y)
    t.dot(size, "black")

# 胡蘿蔔鼻子
t.goto(0, 120)
t.color("orange")
t.begin_fill()
t.goto(45, 112)
t.goto(0, 108)
t.end_fill()

# 胳膊
t.pencolor("saddlebrown")
t.pensize(5)
for sx in [-1, 1]:
    t.goto(sx * 65, 30)
    t.pendown()
    t.goto(sx * 140, 80)
    t.penup()

# 帽子
t.pensize(1)
t.goto(-60, 165)
t.color("black")
t.begin_fill()
for x, y in [(60, 165), (60, 175), (35, 175), (35, 235), (-35, 235), (-35, 175), (-60, 175)]:
    t.goto(x, y)
t.end_fill()

# 雪花
for i in range(90):
    t.goto(random.randint(-300, 300), random.randint(-180, 300))
    t.dot(random.randint(3, 7), "white")

怎麼畫的

雪球用 t.dot(直徑, 顏色) 畫:先走到圓心,再點一個大圓點。三個圓心一個比一個高,直徑一個比一個小。

眼睛和釦子寫在一個列表裡 (x, y, 大小),一個迴圈畫完。

鼻子、帽子、地面是用 goto 一個點一個點圍出來的形狀,夾在 begin_fill() 和 end_fill() 之間就塗滿。

兩隻胳膊:for sx in [-1, 1],x 座標乘 -1 就是左邊、乘 1 是右邊,一段程式碼畫出對稱的兩隻。

常見問題

為什麼畫布要先 penup?

這段程式碼幾乎都是點圓點和填色,走路時不想留下線,所以一開始就 penup(),只有畫胳膊時臨時 pendown()。

怎麼讓雪人戴圍巾?

點「改一改」,在帽子前面加一段:走到 (-55, 70),用 begin_fill 圍一個紅色的長條,就是圍巾。

換個樣子