2024年3月15日 星期五

雙迴圈5*5實心方塊

範例一、利用Tutle指令來畫出5*5實心方塊

程式碼:

 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):
        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()

執行結果:

範例二、利用Tutle指令來畫出5*5實心方塊呈三角形

程式碼:

 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+i-1,3):
        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
import turtle
c = turtle.Turtle()
for i in range(1,6):
    for j in range(-2+i-1,3):
        if i==2 and j==-1:
            continue
        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()

執行結果:


沒有留言:

張貼留言