# GESP等级：二级 | GESP Python 二级考点
"""
流程图小画家演示程序
面向7-10岁少儿编程教学
用 turtle 画出 "判断奇偶数" 的完整流程图
"""

import turtle

# ============================================================
# 初始化画布和画笔
# ============================================================
t = turtle.Turtle()
t.speed(3)
t.pensize(2)
turtle.title("流程图小画家 - 判断奇偶数")
turtle.bgcolor("white")

# 颜色定义
COLOR_START = "green"       # 开始/结束
COLOR_PROCESS = "blue"      # 处理框
COLOR_DECISION = "orange"   # 判断框
COLOR_ARROW = "black"       # 箭头
COLOR_TEXT = "black"        # 文字

# ============================================================
# 工具函数
# ============================================================

def go_to(x, y):
    """移动到指定坐标（不画线）"""
    t.penup()
    t.goto(x, y)
    t.pendown()


def draw_arrow(x1, y1, x2, y2, label=""):
    """从 (x1,y1) 画箭头到 (x2,y2)，可加标签"""
    t.penup()
    t.goto(x1, y1)
    t.pendown()
    t.pensize(2)
    t.pencolor(COLOR_ARROW)

    # 计算角度
    import math
    dx = x2 - x1
    dy = y2 - y1
    angle = math.degrees(math.atan2(dy, dx))

    # 画线
    t.setheading(t.towards(x2, y2))
    t.forward(math.sqrt(dx*dx + dy*dy))

    # 画箭头头部
    t.penup()
    t.goto(x2, y2)
    t.pendown()
    t.setheading(angle)
    t.left(150)
    t.forward(10)
    t.penup()
    t.goto(x2, y2)
    t.pendown()
    t.setheading(angle)
    t.right(150)
    t.forward(10)

    # 画标签
    if label:
        t.penup()
        label_x = (x1 + x2) / 2
        label_y = (y1 + y2) / 2
        t.goto(label_x, label_y + 12)
        t.pendown()
        t.pencolor("red")
        t.write(label, align="center", font=("SimHei", 10, "normal"))
        t.pencolor(COLOR_ARROW)


def draw_ellipse(x, y, w, h, text, color=COLOR_START):
    """画椭圆（起止框）"""
    go_to(x, y)
    t.pensize(2)
    t.pencolor(color)
    t.fillcolor("light" + color if color == "green" else "lightcoral")
    t.fillcolor("#E8F5E9" if color == COLOR_START else "#FFF3E0")

    # 画椭圆（使用圆弧组合）
    t.penup()
    t.goto(x - w//2, y)
    t.pendown()
    t.fillcolor("#E8F5E9")
    t.begin_fill()
    for i in range(2):
        t.circle(h//2, 90)
        t.circle(w//2 - h//2, 90)
    t.end_fill()

    # 写文字
    t.penup()
    t.goto(x, y - 8)
    t.pendown()
    t.pencolor(COLOR_TEXT)
    t.write(text, align="center", font=("SimHei", 12, "bold"))


def draw_rect(x, y, w, h, text, color=COLOR_PROCESS):
    """画矩形（处理框）"""
    go_to(x - w//2, y - h//2)
    t.pensize(2)
    t.pencolor(color)
    t.fillcolor("#E3F2FD")
    t.begin_fill()
    for _ in range(2):
        t.forward(w)
        t.left(90)
        t.forward(h)
        t.left(90)
    t.end_fill()

    # 写文字
    t.penup()
    t.goto(x, y - 8)
    t.pendown()
    t.pencolor(COLOR_TEXT)
    t.write(text, align="center", font=("SimHei", 12, "bold"))


def draw_diamond(x, y, size, text, color=COLOR_DECISION):
    """画菱形（判断框）"""
    go_to(x, y + size)
    t.pensize(2)
    t.pencolor(color)
    t.fillcolor("#FFF3E0")
    t.begin_fill()
    t.goto(x + size, y)
    t.goto(x, y - size)
    t.goto(x - size, y)
    t.goto(x, y + size)
    t.end_fill()

    # 写文字（分两行）
    t.penup()
    t.goto(x, y - 14)
    t.pendown()
    t.pencolor(COLOR_TEXT)
    t.write(text, align="center", font=("SimHei", 11, "bold"))


def draw_title():
    """画标题"""
    go_to(0, 250)
    t.pencolor("purple")
    t.write("流程图小画家 —— 判断奇偶数", align="center",
            font=("SimHei", 18, "bold"))


# ============================================================
# 主程序：画判断奇偶数的完整流程图
# ============================================================

def main():
    t.speed(5)
    turtle.tracer(False)  # 先关动画，画完再显示

    draw_title()

    # ============ 第1层：开始 ============
    y_start = 190
    draw_ellipse(0, y_start, 120, 50, "开始", COLOR_START)

    # 箭头：开始 → 输入数字
    draw_arrow(0, y_start - 25, 0, y_start - 75)

    # ============ 第2层：输入数字 ============
    y_input = y_start - 100
    draw_rect(0, y_input, 180, 50, "输入数字 n", COLOR_PROCESS)

    # 箭头：输入 → 判断
    draw_arrow(0, y_input - 25, 0, y_input - 75)

    # ============ 第3层：判断条件 ============
    y_decision = y_input - 100
    draw_diamond(0, y_decision, 60, "n % 2 == 0 ?", COLOR_DECISION)

    # 箭头：判断 → 是（左分支）
    draw_arrow(-60, y_decision - 15, -120, y_decision - 75, "是")

    # 箭头：判断 → 否（右分支）
    draw_arrow(60, y_decision - 15, 120, y_decision - 75, "否")

    # ============ 第4层左：输出偶数 ============
    y_left = y_decision - 100
    draw_rect(-120, y_left, 180, 50, "输出 '是偶数'", COLOR_PROCESS)

    # 箭头：左输出 → 结束
    draw_arrow(-120, y_left - 25, -60, y_left - 75)

    # ============ 第4层右：输出奇数 ============
    draw_rect(120, y_left, 180, 50, "输出 '是奇数'", COLOR_PROCESS)

    # 箭头：右输出 → 结束
    draw_arrow(120, y_left - 25, 60, y_left - 75)

    # ============ 第5层：结束 ============
    y_end = y_left - 100
    draw_ellipse(0, y_end, 120, 50, "结束", COLOR_START)

    # 汇聚线：左边和右边汇聚到结束
    # 左边已经画了到 (-60, y_left-75)，需要到 (0, y_end)
    draw_arrow(-60, y_left - 25, 0, y_end + 25)
    draw_arrow(60, y_left - 25, 0, y_end + 25)

    # ============ 图例 ============
    y_legend = y_end - 80
    go_to(-200, y_legend)
    t.pencolor("green")
    t.write("椭圆 = 开始/结束（起止框）", font=("SimHei", 10, "normal"))

    go_to(-200, y_legend - 22)
    t.pencolor("blue")
    t.write("矩形 = 做事（处理框）", font=("SimHei", 10, "normal"))

    go_to(-200, y_legend - 44)
    t.pencolor("orange")
    t.write("菱形 = 选择（判断框）", font=("SimHei", 10, "normal"))

    go_to(-200, y_legend - 66)
    t.pencolor("black")
    t.write("箭头 = 方向（流程线）", font=("SimHei", 10, "normal"))

    # ============ 对应的Python代码 ============
    y_code = y_legend - 100
    go_to(-200, y_code)
    t.pencolor("purple")
    t.write("对应的Python代码：", font=("SimHei", 12, "bold"))

    code_lines = [
        "n = int(input('输入数字：'))",
        "if n % 2 == 0:",
        "    print('是偶数')",
        "else:",
        "    print('是奇数')",
    ]
    for i, line in enumerate(code_lines):
        go_to(-200, y_code - 25 * (i + 1))
        t.pencolor("darkblue")
        t.write(line, font=("Courier New", 10, "normal"))

    # ============ 三种结构标注 ============
    go_to(150, y_start + 20)
    t.pencolor("red")
    t.write("→顺序结构", font=("SimHei", 11, "bold"))

    go_to(150, y_decision + 20)
    t.pencolor("red")
    t.write("→选择结构", font=("SimHei", 11, "bold"))

    # 刷新显示
    t.hideturtle()
    turtle.tracer(True)
    turtle.done()


# ============================================================
# 启动程序
# ============================================================
if __name__ == "__main__":
    print("=" * 40)
    print("  流程图小画家 —— turtle画流程图")
    print("  主题：判断一个数是奇数还是偶数")
    print("=" * 40)
    print()
    print("📐 图例说明：")
    print("  椭圆 🟢 = 开始 / 结束（起止框）")
    print("  矩形 🔵 = 处理（处理框）")
    print("  菱形 🟠 = 判断（判断框）")
    print("  箭头 ⬆⬇ = 流程方向（流程线）")
    print()
    print("📝 对应的 Python 代码：")
    print("  n = int(input('输入数字：'))")
    print("  if n % 2 == 0:")
    print("      print('是偶数')")
    print("  else:")
    print("      print('是奇数')")
    print()
    print("🖥️ 流程图将显示在窗口中……")
    main()
