红绿灯倒计时python
时间: 2023-11-17 16:03:43 浏览: 259
以下是一个红绿灯倒计时的Python程序:
```python
import turtle
import time
# 红绿灯变亮
def hld_d(ys, bj, light):
light.color(ys, ys)
light.begin_fill()
light.circle(bj)
light.end_fill()
# 红绿灯倒计时
def countdown(t):
for i in range(t, 0, -1):
print(i)
time.sleep(1)
# 初始化窗口和画笔
win = turtle.Screen()
win.title("红绿灯倒计时")
win.bgcolor("black")
pen = turtle.Turtle()
pen.hideturtle()
pen.speed(0)
# 画红灯
pen.penup()
pen.goto(-50, 50)
pen.pendown()
hld_d("red", 50, pen)
# 画黄灯
pen.penup()
pen.goto(-50, 0)
pen.pendown()
ld_d("yellow", 50, pen)
# 画绿灯
pen.penup()
pen.goto(-50, -50)
pen.pendown()
hld_d("green", 50, pen)
# 红绿灯倒计时
while True:
pen.clear()
pen.write("3", align="center", font=("Courier", 80, "normal"))
countdown(3)
pen.clear()
hld_d("red", 50, pen)
pen.write("2", align="center", font=("Courier", 80, "normal"))
countdown(2)
pen.clear()
hld_d("yellow", 50, pen)
pen.write("1", align="center", font=("Courier", 80, "normal"))
countdown(1)
pen.clear()
hld_d("green", 50, pen)
pen.write("GO!", align="center", font=("Courier", 80, "normal"))
time.sleep(2)
turtle.done()
```
这个程序使用了turtle库来绘制红绿灯,同时使用了time库来实现倒计时功能。程序中定义了两个函数,hld_d用于绘制红绿灯,countdown用于实现倒计时。在主程序中,先绘制了红绿灯,然后进入一个无限循环,每次循环都会清除画布,显示倒计时数字,然后调用countdown函数实现倒计时,最后显示红绿灯的颜色和GO!字样。
阅读全文