python3的turtle畫模仿3d星空、運動的恆星小宇宙


#---第1步---導入模塊---
from turtle import *
from random import random,randint

#---第2步---初始化定義---
#---定義屏幕,窗口大小,標題,背景顏色
screen = Screen()
#---大一點效果好一點---
width ,height = 1600,1200
screen.setup(width,height)
screen.title('浪漫星空')
screen.bgcolor("black")
#設置或返回以毫秒為單位的繪制延遲,延遲越大,繪圖越慢
screen.delay(0)


#---第3步---定義3種不同顏色的星球,大小、速度、位置、形狀不同---
#shape():設置烏龜的圖形形狀,取值:“arrow”, “turtle”, “circle”, “square”, “triangle”, “classic”
#---星球---白色星星---
t = Turtle(visible = False,shape='circle')
t.pencolor("white")
#海龜的顏色,也就是飛動的星球的顏色
t.fillcolor("blue")
t.penup()
#旋轉角度
t.setheading(-10)
#坐標是隨機的
t.goto(width/2,randint(-height/2,height/2))

#---星球2---綠色遠處小星星---
t2 = Turtle(visible = False,shape='turtle')
#海龜的顏色,也就是飛動的星球的顏色
t2.fillcolor("green")
t2.penup()
t2.setheading(-50)
#坐標是隨機的
t2.goto(width,randint(-height,height))

#---星球3---近的紅色恆星---
t3 = Turtle(visible = False,shape='circle')
#海龜的顏色,也就是飛動的星球的顏色
t3.fillcolor("red")
t3.penup()
t3.setheading(-90)
#坐標是隨機的
t3.goto(width*2,randint(-height*2,height*2))

#---第4步---定義星球列表---用於存放---
stars = []
stars2 = []
stars3 = []

#---第5步---定義3種星球的大小、速度、位置並存放各自列表中---
#---注意200為畫200個各自星球就退出,注意太多了要卡死的---
for i in range(200):
    star = t.clone()
    #決定星球的大小
    s= random()/3
    star.shapesize(s,s)
    star.speed(int(s*10))
    #隨機產生坐標
    star.setx(width/2 + randint(1,width))
    star.sety(randint(-height/2,height/2))
    star.showturtle()
    stars.append(star)

for i in range(200):
    star2 = t2.clone()
    #決定星球的大小
    s2= random()/2
    star2.shapesize(s2,s2)
    star2.speed(int(s*10))
    star2.setx(width/2 + randint(1,width))
    star2.sety(randint(-height/2,height/2))
    star2.showturtle()
    stars2.append(star2)

for i in range(200):
    star3 = t3.clone()
    #決定星球的大小
    s3= random()*5
    star3.shapesize(10*s3,10*s3)
    star3.speed(int(s3*10))
    star3.setx(width*2 + randint(1,width))
    star3.sety(randint(-height*2,height*2))
    star3.showturtle()
    stars3.append(star3)

#---第6步---游戲循環---各自星球的啟動
while True:
    for star in stars:
        star.setx(star.xcor() - 3 * star.speed())
        if star.xcor()<-width/2:
            star.hideturtle()
            star.setx(width/2 + randint(1,width))
            star.sety( randint(-height/2,height/2))
            star.showturtle()

    for star2 in stars2:
        star2.setx(star2.xcor() - 3 * star2.speed())
        if star2.xcor()<-width/2:
            star2.hideturtle()
            star2.setx(width/2 + randint(1,width))
            star2.sety( randint(-height/2,height*2))
            star2.showturtle()

    for star3 in stars3:
        star3.setx(star3.xcor() - 3 * star3.speed())
        if star3.xcor()<-width*2:
            star3.hideturtle()
            star3.setx(width*2 + randint(1,width))
            star3.sety( randint(-height*2,height*2))
            star3.showturtle()

 


免責聲明!

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



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