Python有一個很好用的套件-Turtle(海龜),初學者可以參考下面文件來學習。
第一個turtle程式:http://drweb.nksh.tp.edu.tw/student/lesson/A01/
1.畫一條線
import turtle
john = turtle.Turtle()
john.forward(100)
2. 更改線的顏色
import turtle
john = turtle.Turtle()
john.color("red")
john.forward(100)
3. 往上畫線
import turtle
john = turtle.Turtle()
john.color("red")
john.forward(100)
john.left(90)
john.forward(50)
4.畫長方形
import turtle
john = turtle.Turtle()
john.color("red")
john.forward(100)
john.left(90)
john.forward(50)
john.left(90)
john.forward(100)
john.left(90)
john.forward(50)
5. 畫正方形
import turtle
john = turtle.Turtle()
for i in [0,1,2,3]:
john.forward(50)
john.left(90)
另一種寫法
import turtle
john = turtle.Turtle()
for i in range(4):
john.forward(50)
john.left(90)
用函式來表示
import turtle
def drawRect():
john = turtle.Turtle()
for i in range(4):
john.forward(50)
john.left(90)
drawRect()
6.畫星星
import turtle
star = turtle.Turtle()
for i in range(5):
star.forward(50)
star.right(144)
turtle.done()
進階練習
7. 用菱形繪製一個圓圈 (摘自http://mathalope.co.uk/2015/04/22/udacity-programming-fundamentals-with-python-turtle-module-draw-a-circle-out-of-diamonds/)
import turtle
def draw_diamond(some_turtle):
some_turtle.left(30)
some_turtle.forward(50)
some_turtle.right(60)
some_turtle.forward(50)
some_turtle.right(120)
some_turtle.forward(50)
some_turtle.right(60)
some_turtle.forward(50)
some_turtle.right(150)
def draw_art():
# Instantiate a Screen object, window. Then customize window.
window = turtle.Screen()
window.bgcolor("white") # set background color
# Instantiate a Turtle object, brad. Then customize brad.
brad = turtle.Turtle()
brad.shape("turtle") # see Turtle doc
brad.color("blue") # see Turtle doc
brad.speed(0) # 1 (slowest) to 10 (fastest). 0 means no animation.
# Draw a circle with 36 diamonds. We rotate each diamond by 10 degrees at a time.
for i in range (0, 36):
draw_diamond(brad)
brad.right(10)
# Draw a between middle of circle and the floor
brad.right(90)
brad.forward(200)
# How to exit?
window.exitonclick() # click on the window to exit
# Invoke the procedure!
draw_art()
8. Turtle star
沒有留言:
張貼留言