简单学pythonturtle库画图形7龟龟赛跑

今天我们学习点儿动态的,定义两个乌龟图标,利用随机移动距离来进行赛跑。

新知识:

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()

作品:

简单学pythonturtle库画图形7龟龟赛跑

龟龟赛跑

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

(0)
股市刺客的头像股市刺客
上一篇 2024 年 7 月 11 日
下一篇 2024 年 7 月 11 日

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注