範例 一、用雙迴圈畫方形並排列成三角形
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | import turtle c = turtle.Turtle() for i in range(1,6): for j in range(-2,3-i+1): c.penup() c.goto(-500+i*150,j*150) c.pendown() c.color("red") c.begin_fill() c.forward(100) c.left(90) c.forward(100) c.left(90) c.forward(100) c.left(90) c.forward(100) c.left(90) c.end_fill() |
執行結果:
範例二、用雙迴圈畫方形並排列成三角形,但內部畫圓來顯示
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | import turtle c = turtle.Turtle() for i in range(1,6): for j in range(-2,3-i+1): if i==1 or j==-2 or j==3-i: c.penup() c.goto(-500+i*150,j*150) c.pendown() c.color("red") c.begin_fill() c.forward(100) c.left(90) c.forward(100) c.left(90) c.forward(100) c.left(90) c.forward(100) c.left(90) c.end_fill() else: c.penup() c.goto(-500+i*150+50,j*150) c.pendown() c.color("black") c.begin_fill() c.circle(50) c.end_fill() |
執行結果:
範例三:以隨機產生圖案和顏色
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | import turtle import random c = turtle.Turtle() c.speed(0) color=["black", "red", "blue", "yellow", "green", "white"] for i in range(1,6): for j in range(-2,3-i+1): if random.randint(1,100)%2: c.penup() c.goto(-500+i*150,j*150) c.pendown() c.color(color[random.randint(0,5)]) c.begin_fill() c.forward(100) c.left(90) c.forward(100) c.left(90) c.forward(100) c.left(90) c.forward(100) c.left(90) c.end_fill() else: c.penup() c.goto(-500+i*150+50,j*150) c.pendown() c.color(random.random(),random.random(), random.random()) c.begin_fill() c.circle(50) c.end_fill() |
執行結果:
範例四、承上題,把畫方形用函式取代
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | import turtle import random def square(c): c.begin_fill() c.forward(100) c.left(90) c.forward(100) c.left(90) c.forward(100) c.left(90) c.forward(100) c.left(90) c.end_fill() c = turtle.Turtle() c.speed(0) color=["black", "red", "blue", "yellow", "green", "white"] for i in range(1,6): for j in range(-2,3-i+1): if random.randint(1,100)%2: c.penup() c.goto(-500+i*150,j*150) c.pendown() c.color(color[random.randint(0,5)]) square(c) else: c.penup() c.goto(-500+i*150+50,j*150) c.pendown() c.color(random.random(),random.random(), random.random()) c.begin_fill() c.circle(50) c.end_fill() |
執行結果:
沒有留言:
張貼留言