python红绿灯倒计时
时间: 2023-12-05 19:40:53 浏览: 180
以下是一个Python红绿灯倒计时的例子:
```python
import turtle
import time
# 定义函数,画出一个圆
def draw_circle(x, y, r, color):
turtle.penup()
turtle.goto(x, y)
turtle.pendown()
turtle.fillcolor(color)
turtle.begin_fill()
turtle.circle(r)
turtle.end_fill()
# 定义函数,画出红灯
def draw_red_light(x, y, r):
draw_circle(x, y, r, 'red')
# 定义函数,画出黄灯
def draw_yellow_light(x, y, r):
draw_circle(x, y, r, 'yellow')
# 定义函数,画出绿灯
def draw_green_light(x, y, r):
draw_circle(x, y, r, 'green')
# 定义函数,画出红绿灯
def draw_traffic_light(x, y):
turtle.hideturtle()
turtle.speed(0)
turtle.penup()
turtle.goto(x, y)
turtle.pendown()
turtle.pensize(3)
turtle.fillcolor('gray')
turtle.begin_fill()
turtle.goto(x + 80, y)
turtle.goto(x + 80, y + 180)
turtle.goto(x, y + 180)
turtle.goto(x, y)
turtle.end_fill()
draw_red_light(x + 40, y + 120, 30)
draw_yellow_light(x + 40, y + 60, 30)
draw_green_light(x + 40, y, 30)
# 定义函数,倒计时
def countdown(n):
while n > 0:
print(n)
time.sleep(1)
n -= 1
# 主函数
def main():
draw_traffic_light(-200, 0)
while True:
draw_red_light(-160, 120, 30)
countdown(5)
draw_red_light(-160, 120, 30)
draw_yellow_light(-160, 60, 30)
countdown(2)
draw_yellow_light(-160, 60, 30)
draw_green_light(-160, 0, 30)
countdown(5)
draw_green_light(-160, 0, 30)
draw_yellow_light(-160, 60, 30)
countdown(2)
draw_yellow_light(-160, 60, 30)
if __name__ == '__main__':
main()
```
阅读全文