07-海龟绘图2_数字时钟

  • 阅读: 386
  • 更新: 2022-06-11

难度:

1. 题目描述

2. 关键点

  • 海龟绘图,绘制数字

3. 代码实现

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import datetime
import time
import turtle


# 每个数字对应的笔画,设定数字左边中间坐标为(0, 0)
number_pen = {
    0: [(0, 1), (0, 0), (0, -1), (1, -1), (1, 0), (1, 1), (0, 1)],
    1: [(1, 1), (1, 0), (1, -1)],
    2: [(0, 1), (1, 1), (1, 0), (0, 0), (0, -1), (1, -1)],
    3: [(0, 1), (1, 1), (1, 0), (0, 0), (1, 0), (1, -1), (0, -1)],
    4: [(0, 1), (0, 0), (1, 0), (1, 1), (1, 0), (1, -1)],
    5: [(1, 1), (0, 1), (0, 0), (1, 0), (1, -1), (0, -1)],
    6: [(1, 1), (0, 1), (0, 0), (0, -1), (1, -1), (1, 0), (0, 0)],
    7: [(0, 1), (1, 1), (1, 0), (1, -1)],
    8: [(1, 1), (0, 1), (0, 0), (1, 0), (1, -1), (0, -1), (0, 0), (1, 0), (1, 1)],
    9: [(1, 1), (0, 1), (0, 0), (1, 0), (1, 1), (1, 0), (1, -1), (0, -1)],
}


def draw_number(number, pos=(0, 0)):
    """绘画数字"""
    number_len = 50  # 笔画长度
    for i, (x, y) in enumerate(number_pen[number]):
        x *= number_len
        y *= number_len
        x += pos[0]
        y += pos[1]
        if i == 0:  # 每个数字初始的时候需要设置初始位置
            turtle.hideturtle()
            turtle.penup()
            turtle.setpos(x, y)
            turtle.pendown()
            turtle.showturtle()
        turtle.setpos(x, y)


def clock():
    """绘制时钟"""
    while True:
        now = datetime.datetime.now().strftime('%H%M%S')
        for i, num in enumerate(now):
            num = int(num)
            draw_number(num, ((i-3) * 100, 0))
        time.sleep(1)
        turtle.reset()


clock()

4. 运行示例

5. 进阶思考

  1. 只重新绘制变动的数字
  2. 添加背景、颜色等,做出精美的数字时钟

=== 全文完 ===


欢迎加入QQ群:778391413

京公网安备 11011302003970号 京ICP备2022012301号-1