首頁>Club>
15
回覆列表
  • 1 # 使用者4410748964788

    python聖誕樹程式碼

    1、簡單的繪製聖誕樹

    新建tree1.py或者直接輸入下面程式碼執行#宣告樹的高度

    height = 5

    #樹的雪花數,初始為1

    stars = 1

    #以數的高度作為迴圈次數

    for i in range(height):

    print((" " * (height - i)) + ("*" * stars))

    stars += 2

    #輸出樹幹

    print((" " * height) + "|")

    1581558705868932.png

    2、使用turtle繪製簡單聖誕樹

    新建tree2py,輸入以下程式碼#匯入turtle庫

    import turtle

    #設定螢幕大小

    screen = turtle.Screen()

    screen.setup(800,600)

    #獲取畫筆並設定一些屬性:圓形、紅色、快

    circle = turtle.Turtle()

    circle.shape("circle")

    circle.color("red")

    circle.speed("fastest")

    #抬起畫筆

    circle.up()

    #重新獲取畫筆

    square = turtle.Turtle()

    #重新設定畫筆屬性:四方形、綠色、快

    square.shape("square")

    square.color("green")

    square.speed("fastest")

    #重新抬起畫筆

    square.up()

    #跳到指定座標位置

    circle.goto(0,280)

    #複製當前圖形

    circle.stamp()

    k = 0

    for i in range(1, 17):

    y = 30*i

    for j in range(i-k):

    x = 30*j

    square.goto(x,-y+280)

    square.stamp()

    square.goto(-x,-y+280)

    square.stamp()

    if i % 4 == 0:

    x = 30*(j+1)

    circle.color("red")

    circle.goto(-x,-y+280)

    circle.stamp()

    circle.goto(x,-y+280)

    circle.stamp()

    k += 2

    if i % 4 == 3:

    x = 30*(j+1)

    circle.color("yellow")

    circle.goto(-x,-y+280)

    circle.stamp()

    circle.goto(x,-y+280)

    circle.stamp()

    square.color("brown")

    for i in range(17,20):

    y = 30*i

    for j in range(3):

    x = 30*j

    square.goto(x,-y+280)

    square.stamp()

    square.goto(-x,-y+280)

    square.stamp()

    turtle.exitonclick()

    執行:

    1581558728714813.png

    3、使用Turtle繪製複雜聖誕樹

    新建tree3.py,輸入以下程式碼#匯入所依賴的庫

    from turtle import *

    import random

    import time

    n = 80.0

    #設定速度快

    speed("fastest")

    #背景顏色 海貝殼色,偏粉色

    screensize(bg="seashell")

    left(90)

    forward(3*n)

    color("orange", "yellow")

    begin_fill()

    left(126)

    for i in range(5):

    forward(n/5)

    right(144)

    forward(n/5)

    left(72)

    end_fill()

    right(126)

    color("dark green")

    backward(n*4.8)

    def tree(d, s):

    if d <= 0: return

    forward(s)

    tree(d-1, s*.8)

    right(120)

    tree(d-3, s*.5)

    right(120)

    tree(d-3, s*.5)

    right(120)

    backward(s)

    tree(15, n)

    backward(n/2)

    for i in range(200):

    a = 200 - 400 * random.random()

    b = 10 - 20 * random.random()

    up()

    forward(b)

    left(90)

    forward(a)

    down()

    if random.randint(0, 1) == 0:

    color("tomato")

    else:

    color("wheat")

    circle(2)

    up()

    backward(a)

    right(90)

    backward(b)

    time.sleep(60)

    執行:

  • 中秋節和大豐收的關聯?
  • 我想和老公提離婚,然後自己過自己的小日子,可以嗎?