用python畫隨機顏色隨機大小隨機位置的正方形


用python畫隨機顏色隨機大小的正方形

新手練習

練習題目:用python畫出隨機顏色隨機大小的正方形

基本知識:turtle庫,random庫

隨機顏色,通過顏色的十六進制完成:

 1 def random_color():
 2     color_list=['0','1','2','3','4','5','6','7','8','9',
 3                 'A','B','C','D','E','F']
 4     color = ''
 5    #一個以“#”開頭的6位十六進制數值表示一種顏色,所以要循環6次
 6     for i in range(6):
 7         #random.randint表示產生0~15的一個整數型隨機數
 8         color_number = color_list[random.randint(0,15)]
 9         color += color_number
10     color = '#' +color
11     return color

 隨機大小:

def draw_square(size):
#size表示正方形的邊長
    for i in range(4):
        turtle.forward(size)
        turtle.right(90)
        size = random.randrange(-200,200)

隨機位置

   #改變畫筆起始點的位置
    for i in range(20):
       x = random.randrange(-200,200)
       y = random.randrange(-200,200)
       turtle.penup()
       # goto(x,y)移動到x,y所確定的那個點上
       turtle.goto(x,y)
       turtle.pendown()

 

具體總代碼:

 1 '''
 2    作者:唐梓文
 3    版本:1.0
 4    日期:08/05/2020
 5    功能:隨機的在畫布畫多個正方形,並塗色
 6 
 7 '''
 8 
 9 import turtle
10 import random
11 
12 def random_color():
13     color_list=['0','1','2','3','4','5','6','7','8','9',
14                 'A','B','C','D','E','F']
15     color = ''
16     for i in range(6):
17         color_number = color_list[random.randint(0,15)]
18         color += color_number
19     color = '#' +color
20     return color
21 
22 def draw_square(size):
23     for i in range(4):
24         turtle.forward(size)
25         turtle.right(90)
26 
27 def main():
28    for i in range(20):
29        x = random.randrange(-200,200)
30        y = random.randrange(-200,200)
31        turtle.penup()
32        # goto(x,y)移動到x,y所確定的那個點上
33        turtle.goto(x,y)
34        turtle.pendown()
35 
36        # turtle.pencolor(random_color())正方形邊框顏色隨機
37        turtle.color(random_color())
38        turtle.begin_fill()
39        size = random.randrange(-200,200)
40        draw_square(size)
41        turtle.end_fill()
42 
43    turtle.exitonclick()
44 
45 if __name__ =='__main__':
46     main()

 

實現效果圖:

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM