今天我们学习点儿动态的,定义两个乌龟图标,利用随机移动距离来进行赛跑。
新知识:
Turtle(),定义一个画笔对象。
clone(),复制一个画笔对象。
position(),画笔的坐标。
import turtle as t
import random
t.speed(0)
t.setup(500,500)#画布的长和高
#画终点线
t.up()
t.goto(200,-220)
t.down()
t.goto(200,220)
t.up()
t.home()
#定义绿龟及指定位置
x=t.Turtle()
x.shape('turtle')
x.color('green')
x.speed(0)
x.up()
x.goto(-200,100)
#定义红龟及指定位置
y=x.clone()
y.shape('turtle')
y.color('red')
y.speed(0)
y.up()
y.goto(-200,-100)
while True:
#两只龟随机向前移动0-5步
x.forward(random.randint(0,5))
y.forward(random.randint(0,5))
#到达终点线则比赛结束,宣布胜者
if x.position()[0]>=200 and y.position()[0]<200:
t.write('绿龟胜!',font=('楷体', 18, 'bold'))
break
elif y.position()[0]>=200 and x.position()[0]<200:
t.write('红龟胜!',font=('楷体', 18, 'bold'))
break
elif x.position()[0]>=200 and y.position()[0]>=200:
t.write('平局!',font=('楷体', 18, 'bold'))
t.done()
作品:

龟龟赛跑
发布者:股市刺客,转载请注明出处:https://www.95sca.cn/archives/74930
站内所有文章皆来自网络转载或读者投稿,请勿用于商业用途。如有侵权、不妥之处,请联系站长并出示版权证明以便删除。敬请谅解!