Python:龟兔赛跑
时间: 2023-12-14 09:33:20 浏览: 195
以下是Python中实现龟兔赛跑的例子:
```python
# 导入turtle库
from turtle import *
import random
# 设置乌龟和兔子的起始位置
turtle_pos = -300
rabbit_pos = -300
# 创建乌龟和兔子
turtle = Turtle()
turtle.shape('turtle')
turtle.color('green')
turtle.penup()
turtle.goto(turtle_pos, 0)
turtle.pendown()
rabbit = Turtle()
rabbit.shape('turtle')
rabbit.color('red')
rabbit.penup()
rabbit.goto(rabbit_pos, -50)
rabbit.pendown()
# 设置比赛的长度
race_length = 500
# 开始比赛
while turtle_pos < race_length and rabbit_pos < race_length:
turtle_step = random.randint(1, 20)
rabbit_step = random.randint(1, 20)
turtle_pos += turtle_step
rabbit_pos += rabbit_step
turtle.goto(turtle_pos, 0)
rabbit.goto(rabbit_pos, -50)
# 判断比赛结果
if turtle_pos >= race_length and rabbit_pos >= race_length:
print("It's a tie!")
elif turtle_pos >= race_length:
print("Turtle wins!")
else:
print("Rabbit wins!")
# 隐藏乌龟和兔子
turtle.hideturtle()
rabbit.hideturtle()
```
这个例子使用了Python中的turtle库来创建乌龟和兔子,并使用random库来随机生成它们每次移动的步数。比赛的长度为500,当乌龟或兔子到达终点时,比赛结束并输出结果。
阅读全文
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)