Chapter 5 繪圖-使用turtle

5-1 turtle的基本方法/指令 method

#基本指令 forward(), right(), left(), up(), circle(), down()
import turtle as t      #呼叫 turtle 模組
t.clear() #清除畫布螢幕
t.reset() #重置, 畫筆停在原點座標(預設是畫布的中心點)
t.Pen() #提筆
t.forward(200) #預設箭頭向右,向右畫長度200像素的線
t.done() #畫圖結束
# 範例5-1-1 畫正方形
import turtle as t
t.pen()
t.forward(200)
t.left(90)
t.forward(200)
t.left(90)
t.forward(200)
t.left(90)
t.forward(200)
t.done()
將範例5-1-1改用迴圈方式重寫
# 範例5-1-2 畫正方形
import turtle as t
t.pen()
for i in range(4):
t.forward(200)
t.left(90)
t.done()
# 範例5-1-3 畫五角星
import turtle as t
t.clear()
t.reset()
t.pen()
for i in range(5):
t.forward(200)
t.left(180/5+180)
t.done()
# 範例5-1-4 畫六角星
import turtle as t
t.clear()
t.reset()
t.pen()
for i in range(6):
t.forward(100)
t.right(120)
t.forward(100)
t.left(60)
t.done()
5-1-2 移動位置與填色
#基本指令 forward(), right(), left(), up(), circle(), down()
import turtle as t
t.color('red') #填色選擇
t.begin_fill() #填色起點
t.end_fill() #填色終點
t.up() #提起筆, 代表不會描繪出邊框
t.goto(100,50) #游標移動到座標(100,50)
t.down() #放下筆, 代表會描繪出邊框
t.circle(50) #從筆的位置畫出半徑為50的圓(注意:不是從圓心用圓規畫圓的概念)
# 範例5-1-5 畫紅色正方形
import turtle as t
t.pen()
t.color('red')
t.begin_fill() #填色起點
for i in range(4):
t.forward(200)
t.left(90)
t.end_fill() #填色終點
t.done()
# 範例5-1-5-1 畫正三角角   
import turtle as t
t.fillcolor("red")
t.begin_fill()
t.lt(240)
t.fd(100)
t.lt(120)
t.fd(100)
t.lt(120)
t.fd(100)
t.end_fill()
t.done()
# 範例5-1-6 移動位置畫紅色正方形
import turtle as t
t.up()
t.goto(100,100)
t.Pen()
# t.down()
t.color('red')
t.begin_fill() #填色起點
for i in range(4):
t.forward(200)
t.left(90)
t.end_fill() #填色終點
t.done()
# 範例5-1-7  移動位置畫兩個圓
import turtle as t
t.goto(100,100)
t.Pen()
t.color('red')
t.circle(100)
t.circle(50)
t.done()
# 範例5-1-8  試試預測會出現什麼圖案
import turtle as t
t.up()
t.goto(100,100)
t.Pen()
t.down()
t.color('green')
t.begin_fill()
t.circle(50)
t.color('red')
t.circle(100)
t.end_fill()
t.done()

5-1-3-1 Case Study 個案研究 : 螺旋狀

# 範例5-1-3-1 以下程式會畫出螺旋狀多彩的顏色
from turtle import *
for steps in range(50):
for c in ('blue', 'red', 'green'):
color(c)
forward(steps)
right(30)
done()

5-1-3-2 Case Study 個案研究 : 畫出車子

# 範例5-1-3-2 車子
import turtle as t
#車身
t.pencolor("red")
t.speed(4)
t.up()
t.fd(100)
t.down()
t.fillcolor("red")
t.begin_fill()
t.fd(100)
t.rt(90)
t.fd(50)
t.rt(90)
t.fd(300)
t.rt(90)
t.fd(50)
t.rt(90)
t.fd(50)
t.lt(30)
t.fd(100)
t.rt(30)
t.fd(50)
t.goto(150,0)
t.end_fill()

#後車輪
t.up()
t.goto(100,-90)
t.down()
t.fillcolor("black")
t.begin_fill()
t.circle(20)
t.end_fill()

#前車輪
t.up()
t.goto(0,-90)
t.down()
t.fillcolor("black")
t.begin_fill()
t.circle(20)
t.end_fill()
t.done()

5-1-3-3 Case Study 個案研究 : 另類螺旋狀

# 範例5-1-3-3 另類螺旋狀
import turtle as t
t.speed(0)
for i in range(0,100,3):
t.forward(i)
t.left(91)
t.done()

5-1-3-4 Case Study 個案研究 : 螺旋狀(list列表將於下個章節探討)

# 範例5-1-3-4
import turtle as t
t.bgcolor("black")
color = ["red","yellow","blue","white","green","purple"]
t.speed(0)
for i in range(0,200,2):
t.pencolor(color[i%4])
t.fd(i)
t.lt(35)
t.done()