要實(shí)現(xiàn)汽車跑動(dòng),首先我們要加載一張城市道路圖作為背景圖,然后就要把海龜?shù)膱D形變?yōu)槠嚨哪?,最后?shí)現(xiàn)兩輛汽車相向而行的效果。
首先,加載背景圖片:
turtle.bgpic(picname=None)
turtle.bgpic(picname=None)
設(shè)置背景圖片或返回當(dāng)前背景圖片的名稱。如果picname
是文件名,則將相應(yīng)的圖像設(shè)置為背景。如果 picname
是 "nopic"
,則刪除背景圖像(如果存在)。如果 picname
是 None
,則返回當(dāng)前背景圖像的文件名。
這里我們加載同文件目錄下的背景圖片如下:
import turtle
turtle.bgpic("bg1.png") # 加載背景圖片
```然后,添加汽車作為畫筆形狀:
turtle.register_shape(name)
`turtle.register_shape()`可以新增更多的畫筆`shape`,其用法之一就是添加`gif`圖片作為畫筆的新形狀。使用自己的圖片作為畫筆shape時(shí)需要注意,首先海龜僅支持`gif`圖片,另外這樣的畫筆`shape`無(wú)論怎樣設(shè)置`resizemode`均不能通過(guò)`shapesize`指令進(jìn)行筆頭大小設(shè)置。以圖片作為`shape`,筆頭的大小就是由圖片本身大小所決定的。當(dāng)然,`turtle.register_shape()`還可以添加用元組作為坐標(biāo)描述的多邊形作為畫筆的`shape`,這里我們并沒(méi)有用到,就不過(guò)多贅述了。
因?yàn)槲覀円獙?shí)現(xiàn)兩輛汽車相向而行,所以要?jiǎng)?chuàng)建兩個(gè)turtle的實(shí)例,并加載不同形狀的汽車,如下:
turtle.register_shape('car1.gif') # 把小車圖片放入海龜可用形狀倉(cāng)庫(kù)中,便于調(diào)用
car1 = turtle.Turtle() # 生成turtle,命名為car1
car1.shape('car1.gif')
turtle.register_shape('car2.gif')
car2 = turtle.Turtle()
car2.shape('car2.gif')
最后,就是和烏龜賽跑一樣,利用`for`循環(huán)實(shí)現(xiàn)汽車一起運(yùn)行的效果:
car1.penup() # 抬筆,不要留下軌跡
car2.penup()
car1.goto(-300, -110)
car2.goto(300, -200)
car2.left(180)
car1.speed(2)
car2.speed(2)
for sp in range(1, 80):
car1.forward(sp)
car2.forward(sp)
turtle.done()
所以,所有總的代碼是:
import turtle
turtle.bgpic("bg1.png") # 加載背景圖片
turtle.register_shape('car1.gif') # 把小車圖片放入海龜可用形狀倉(cāng)庫(kù)中,便于調(diào)用
car1 = turtle.Turtle() # 生成turtle,命名為car1
car1.shape('car1.gif')
turtle.register_shape('car2.gif')
car2 = turtle.Turtle()
car2.shape('car2.gif')
car1.penup() # 抬筆,不要留下軌跡
car2.penup()
car1.goto(-300, -110)
car2.goto(300, -200)
car2.left(180)
car1.speed(2)
car2.speed(2)
for sp in range(1, 80):
car1.forward(sp)
car2.forward(sp)
turtle.done()
-
循環(huán)
+關(guān)注
關(guān)注
0文章
92瀏覽量
16050 -
for
+關(guān)注
關(guān)注
0文章
44瀏覽量
15885 -
python
+關(guān)注
關(guān)注
56文章
4811瀏覽量
85078
發(fā)布評(píng)論請(qǐng)先 登錄
相關(guān)推薦
關(guān)于兩輛智能小車如何保持一致,在同一垂直水平上。。
Python for、while 等循環(huán)速度對(duì)比
兩輛ff樣車運(yùn)抵北京 車回過(guò)了賈躍亭人卻依然見(jiàn)不著
寶馬R18摩托車國(guó)內(nèi)上市 價(jià)格能買兩輛思域
詳解Python的for和while循環(huán)
Python的while循環(huán)是什么
Python中的for循環(huán)結(jié)構(gòu)
Python的循環(huán)語(yǔ)句介紹
結(jié)合for循環(huán)實(shí)現(xiàn)兩輛汽車相向而行
![結(jié)合for<b class='flag-5'>循環(huán)</b><b class='flag-5'>實(shí)現(xiàn)</b><b class='flag-5'>兩輛</b><b class='flag-5'>汽車</b><b class='flag-5'>相向</b><b class='flag-5'>而行</b>](https://file1.elecfans.com/web2/M00/8C/11/wKgaomSlKbuAD_R8AANdOUNchH8770.jpg)
如何用Python來(lái)實(shí)現(xiàn)文件系統(tǒng)的操作功能
![如<b class='flag-5'>何用</b><b class='flag-5'>Python</b>來(lái)<b class='flag-5'>實(shí)現(xiàn)</b>文件系統(tǒng)的操作功能](https://file1.elecfans.com/web2/M00/AB/4C/wKgaomU_TFyAdouzAAAGLFfce2g281.jpg)
如何用python實(shí)現(xiàn)RFM建模
![如<b class='flag-5'>何用</b><b class='flag-5'>python</b><b class='flag-5'>實(shí)現(xiàn)</b>RFM建模](https://file1.elecfans.com/web2/M00/AD/CC/wKgZomVDCvKAcEvOAAC3MMTWRwA588.jpg)
評(píng)論