From 060a17a5f898f9a9f63ad65e7be2ae33d0da14ff Mon Sep 17 00:00:00 2001 From: FH <1755742550@qq.com> Date: Mon, 21 Apr 2025 15:56:25 +0800 Subject: [PATCH] =?UTF-8?q?=E9=A6=96=E6=AC=A1=E6=8F=90=E4=BA=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .idea/.gitignore | 8 + .idea/001-Study.iml | 8 + .idea/inspectionProfiles/Project_Default.xml | 24 + .../inspectionProfiles/profiles_settings.xml | 6 + .idea/misc.xml | 4 + .idea/modules.xml | 8 + .idea/vcs.xml | 6 + 001_Python入门/01函数参数.py | 6 + 001_Python入门/02变量及标识符.py | 7 + .../03数值类型和字符串和格式化输出.py | 43 + .../04算数与赋值运算符与输入函数与转义字符.py | 62 + .../05if判断与比较运算符与逻辑运算符.py | 49 + 001_Python入门/06if-else与if-elif与if嵌套.py | 49 + 001_Python入门/07while循环与循环嵌套.py | 113 + .../08字符串编码与字符串常见操作.py | 57 + 002_练手例程/MDP/README.md | 51 + 002_练手例程/MDP/backend/MDP/MDP/__init__.py | 0 002_练手例程/MDP/backend/MDP/MDP/asgi.py | 16 + 002_练手例程/MDP/backend/MDP/MDP/settings.py | 130 + 002_练手例程/MDP/backend/MDP/MDP/urls.py | 23 + 002_练手例程/MDP/backend/MDP/MDP/wsgi.py | 16 + 002_练手例程/MDP/backend/MDP/db.sqlite3 | Bin 0 -> 147456 bytes 002_练手例程/MDP/backend/MDP/manage.py | 22 + .../MDP/backend/MDP/zjptjg/__init__.py | 0 002_练手例程/MDP/backend/MDP/zjptjg/admin.py | 3 + 002_练手例程/MDP/backend/MDP/zjptjg/apps.py | 6 + .../MDP/backend/MDP/zjptjg/migrations/__init__.py | 0 002_练手例程/MDP/backend/MDP/zjptjg/models.py | 3 + 002_练手例程/MDP/backend/MDP/zjptjg/tests.py | 3 + 002_练手例程/MDP/backend/MDP/zjptjg/urls.py | 7 + 002_练手例程/MDP/backend/MDP/zjptjg/views.py | 7 + .../MDP/frontend/MDP/zjptjg/index.html | 80 + .../MDP/frontend/MDP/zjptjg/script.js | 436 +++ .../MDP/frontend/MDP/zjptjg/style.css | 679 +++++ 002_练手例程/一般机构组件/index.html | 79 + 002_练手例程/一般机构组件/script.js | 452 +++ 002_练手例程/一般机构组件/style.css | 679 +++++ 002_练手例程/时序仿真/README.md | 15 + 002_练手例程/时序仿真/index.html | 178 ++ 002_练手例程/时序仿真/script.js | 2653 +++++++++++++++++ 002_练手例程/时序仿真/styles.css | 684 +++++ 002_练手例程/机械设计云平台.html | 699 +++++ Conda命令.txt | 5 + Django命令.txt | 6 + Git命令.txt | 2 + LICENSE | 6 +- Pycharm插件.txt | 7 + README.md | 43 +- 48 files changed, 7436 insertions(+), 4 deletions(-) create mode 100644 .idea/.gitignore create mode 100644 .idea/001-Study.iml create mode 100644 .idea/inspectionProfiles/Project_Default.xml create mode 100644 .idea/inspectionProfiles/profiles_settings.xml create mode 100644 .idea/misc.xml create mode 100644 .idea/modules.xml create mode 100644 .idea/vcs.xml create mode 100644 001_Python入门/01函数参数.py create mode 100644 001_Python入门/02变量及标识符.py create mode 100644 001_Python入门/03数值类型和字符串和格式化输出.py create mode 100644 001_Python入门/04算数与赋值运算符与输入函数与转义字符.py create mode 100644 001_Python入门/05if判断与比较运算符与逻辑运算符.py create mode 100644 001_Python入门/06if-else与if-elif与if嵌套.py create mode 100644 001_Python入门/07while循环与循环嵌套.py create mode 100644 001_Python入门/08字符串编码与字符串常见操作.py create mode 100644 002_练手例程/MDP/README.md create mode 100644 002_练手例程/MDP/backend/MDP/MDP/__init__.py create mode 100644 002_练手例程/MDP/backend/MDP/MDP/asgi.py create mode 100644 002_练手例程/MDP/backend/MDP/MDP/settings.py create mode 100644 002_练手例程/MDP/backend/MDP/MDP/urls.py create mode 100644 002_练手例程/MDP/backend/MDP/MDP/wsgi.py create mode 100644 002_练手例程/MDP/backend/MDP/db.sqlite3 create mode 100644 002_练手例程/MDP/backend/MDP/manage.py create mode 100644 002_练手例程/MDP/backend/MDP/zjptjg/__init__.py create mode 100644 002_练手例程/MDP/backend/MDP/zjptjg/admin.py create mode 100644 002_练手例程/MDP/backend/MDP/zjptjg/apps.py create mode 100644 002_练手例程/MDP/backend/MDP/zjptjg/migrations/__init__.py create mode 100644 002_练手例程/MDP/backend/MDP/zjptjg/models.py create mode 100644 002_练手例程/MDP/backend/MDP/zjptjg/tests.py create mode 100644 002_练手例程/MDP/backend/MDP/zjptjg/urls.py create mode 100644 002_练手例程/MDP/backend/MDP/zjptjg/views.py create mode 100644 002_练手例程/MDP/frontend/MDP/zjptjg/index.html create mode 100644 002_练手例程/MDP/frontend/MDP/zjptjg/script.js create mode 100644 002_练手例程/MDP/frontend/MDP/zjptjg/style.css create mode 100644 002_练手例程/一般机构组件/index.html create mode 100644 002_练手例程/一般机构组件/script.js create mode 100644 002_练手例程/一般机构组件/style.css create mode 100644 002_练手例程/时序仿真/README.md create mode 100644 002_练手例程/时序仿真/index.html create mode 100644 002_练手例程/时序仿真/script.js create mode 100644 002_练手例程/时序仿真/styles.css create mode 100644 002_练手例程/机械设计云平台.html create mode 100644 Conda命令.txt create mode 100644 Django命令.txt create mode 100644 Git命令.txt create mode 100644 Pycharm插件.txt diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..35410ca --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,8 @@ +# 默认忽略的文件 +/shelf/ +/workspace.xml +# 基于编辑器的 HTTP 客户端请求 +/httpRequests/ +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml diff --git a/.idea/001-Study.iml b/.idea/001-Study.iml new file mode 100644 index 0000000..909438d --- /dev/null +++ b/.idea/001-Study.iml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/inspectionProfiles/Project_Default.xml b/.idea/inspectionProfiles/Project_Default.xml new file mode 100644 index 0000000..e29e708 --- /dev/null +++ b/.idea/inspectionProfiles/Project_Default.xml @@ -0,0 +1,24 @@ + + + + \ No newline at end of file diff --git a/.idea/inspectionProfiles/profiles_settings.xml b/.idea/inspectionProfiles/profiles_settings.xml new file mode 100644 index 0000000..105ce2d --- /dev/null +++ b/.idea/inspectionProfiles/profiles_settings.xml @@ -0,0 +1,6 @@ + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000..a971a2c --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml new file mode 100644 index 0000000..15b04a3 --- /dev/null +++ b/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..35eb1dd --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/001_Python入门/01函数参数.py b/001_Python入门/01函数参数.py new file mode 100644 index 0000000..5ec2130 --- /dev/null +++ b/001_Python入门/01函数参数.py @@ -0,0 +1,6 @@ +print("1", "2", "3", sep="haha", end="不换行") # ,代表间隔符;sep代表间隔的符号;end代表结束符,默认是换行符/n +print("1") +""" +点击函数后会弹出函数文档,或者按Ctrl+Q,或者按右键“转到” +如果需要翻译则安装Translation插件 +""" diff --git a/001_Python入门/02变量及标识符.py b/001_Python入门/02变量及标识符.py new file mode 100644 index 0000000..4eaee87 --- /dev/null +++ b/001_Python入门/02变量及标识符.py @@ -0,0 +1,7 @@ +a = "1" +print(a) # 不加引号打印变量值 +print("a") # 加引号打印字符串 +# ============================================================ +(b) = 2 +print(b) # 标识符被包含在括号内,对标识符本身没有影响,仍然可以打印 +# 标识符:对变量名、函数名的定义符,例如上面的变量名a和(b) diff --git a/001_Python入门/03数值类型和字符串和格式化输出.py b/001_Python入门/03数值类型和字符串和格式化输出.py new file mode 100644 index 0000000..15c8914 --- /dev/null +++ b/001_Python入门/03数值类型和字符串和格式化输出.py @@ -0,0 +1,43 @@ +# Python的数值类型分为四种:整型int、浮点型float、复数complex和布尔型bool。 +a = 1 +print(type(a)) # 检测数据类型的方法是type() +# ============================================================ +bool1 = True # =1 +bool2 = False # =0 +print(type(bool1), type(bool2)) +# ============================================================ +ma = 1 + 2j # 1是实部,2是虚部,j是虚数单位 +print(type(ma)) +# ============================================================ +# 字符串(str)也就是string +a = "1" # 字符串需要加引号 +print(a) +# ============================================================ +# 占位符有三种方式%、format()和f-string +# %是格式化占位符,格式化输出 +a = "hello" +b = 30 +print("我的名字是%s" % a, "我的年龄是%d" % b) # %s:用于插入字符串, %d:用于插入整数 +print("我的名字是%s" % a, "," "我的年龄是%d" % b) # 名字和年龄之间用逗号隔开 +print("我的名字是%s,我的年龄是%d" % (a, b)) # 一次性格式化生成完整的字符串 +# ============================================================ +# %d可以设置位数,例如:%5d,不足位数前面补空白 +a = 123 +print("%5d" % a) # 右对齐,宽度为5 +print("%-5d" % a) # 左对齐,宽度为5 +print("%05d" % a) # 宽度为5,不足前面补0 +print("%+5d" % a) # 宽度为5,前缀为+ +# ============================================================ +# %f浮点数 +a = 1.2 +print("%f" % a) # 默认后六位小数,遵循四舍五入原则 +print("%.5f" % a) # 小数点后5位 +print("%+.5f" % a) # 前缀为+,小数点后5位 +# ============================================================ +# %%代表百分号 +print("我是%%" % ()) +# ============================================================ +# f-string格式化 +a = "1" +b = 30 +print(f"我的名字是{a},我的年龄是{b}") # 变量值加花括号,前面加f diff --git a/001_Python入门/04算数与赋值运算符与输入函数与转义字符.py b/001_Python入门/04算数与赋值运算符与输入函数与转义字符.py new file mode 100644 index 0000000..c0ac74b --- /dev/null +++ b/001_Python入门/04算数与赋值运算符与输入函数与转义字符.py @@ -0,0 +1,62 @@ +print("hello world") +# ============================================================ +""" +算数: +加法:+ +减法:- +乘法:* +除法:/ 除法的商一定是浮点数,除数不能为0,左边是被除数,右边是除数 +整除:// 取商的整数部分(取整除),向下取整,不遵循五入的原则,后面有小数就忽略小数,其中若有浮点数,结果也是浮点数 +取余: % 也叫取模 +取幂:** +计算优先级:幂>乘>除>取余>取整除>加减 +""" +print(5 / 1) # 除法的商一定是浮点数,例如5/1=5.0 +print(5 // 2) # 取商的整数部分,向下取整,不遵循五入的原则,后面有小数就忽略小数,=2 +print(5 % 2) # 取余数,5/2=2.5,商是2,2*2=4,余数是5-4=1 +print(2 ** 2) # 取幂,2的2次方=4 +# ============================================================ +""" +赋值运算符: +仅针对变量计算 += #非常简单 ++= #a = a+1即是a += 1,+=包含了运算和赋值,即将左边的值等于值+1,随后赋给左边的值 +-= #a = a-1即是a -= 1 +*= #a = a*1即是a *= 1 +/= #a = a/1即是a /= 1 +""" +a = 5 +a += 5 # a = a+5 +print(a) +a -= 5 # a = a-5 +print(a) +a *= 5 # a = a*5 +print(a) +a /= 5 # a = a/5 +print(a) +# ============================================================ +""" +输入函数: +input() +函数签名:def input(__prompt: object = ...) -> str 接受一个prompt参数(字符串格式),即是提示的意思,会在控制台中显示 +""" +input("请输入:") # 本质上是调用input函数 +a = input("请再次输入:") # 可以赋值给变量 +print(a) +# ============================================================ +""" +转义字符: +\t # 制表符,制表符是一种 空白字符,主要用于文本的对齐。它不像普通的空格那样占用固定宽度,制表符通常会把文本“跳”到下一个 Tab 停止位。这个跳转的距离通常是 4 到 8 个空格,但具体的表现可能取决于编辑器或程序的配置 +\n # 换行符 +\r # 将当前位置移到本行开头 +\\ # 表示一个\ +r # 原生字符串,取消转义 +""" +print("西门吹雪\t5岁\t美国") # 制表符 +print("张三李四啊\t100岁\t中国") # 制表符 +print("zhangsan\t5\tUSA") # 制表符 +print("lisi\t100\tChina") # 制表符 +print("hello\nworld") # 换行符 +print("hello\rworld") # 将当前位置移到本行开头 +print("hello\\\\world") # 两个\\表示一个\ +print(r"hello\\\\world") # 原生字符串,取消转义 diff --git a/001_Python入门/05if判断与比较运算符与逻辑运算符.py b/001_Python入门/05if判断与比较运算符与逻辑运算符.py new file mode 100644 index 0000000..4a4d733 --- /dev/null +++ b/001_Python入门/05if判断与比较运算符与逻辑运算符.py @@ -0,0 +1,49 @@ +print("hello world") +# ============================================================ +""" +1、比较运算符: +== # 比较两个值是否相等,相等返回真,不相等返回为假 +!= # 比较两个值是否不相等,不相等返回真,相等返回为假 +> +< +>= +<= +""" +a = 100 +b = 200 +print(a == b) # a是否等于b +print(a != b) # a是否不等于b +print(a > b) # a是否大于b +print(a < b) # a是否小于b +print(a >= b) # a是否大于等于b +print(a <= b) # a是否小于等于b +# ============================================================ +""" +2、逻辑运算符: +and # 与,如果两个条件都为真,则返回真,否则返回假 +or # 或,如果两个条件有一个为真,则返回真,否则返回假 +not # 非,取反,如果为真则返回假,为假则返回真 +""" +a = 100 +b = 200 +c = 300 +print(a < b and c > a) # a是否大于b,b是否大于a,如果两个条件都为真,则返回真,否则返回假 +print(a > b or b > a) # a是否大于b,b是否大于a,如果两个条件有一个为真,则返回真,否则返回假 +print(not a > b) # 取反,如果为真则返回假,为假则返回真 +# ============================================================ +""" +3、if #判断,条件后加: +:的作用:表示代码块的开始,起到代码块的结构化,与其他语言的{}类似 +定义函数时的:也意味着接下来的缩进代码也是这个函数的内容 +""" +a = "10" # 字符串类型 +if a > "5": # 字符串类型的比较,不是数字比较,而是逐个字符按照他们的ASCII码值比较 + print("a大于5") +else: + print("a小于5") # 10的第一个字符是1,ASCII码值是49,5的ASCII码值是53,所以输出a小于5 + +a = 10 # 整数类型 +if a > 5: # 整数类型比较,直接比较 + print("a大于5") +else: + print("a小于5") diff --git a/001_Python入门/06if-else与if-elif与if嵌套.py b/001_Python入门/06if-else与if-elif与if嵌套.py new file mode 100644 index 0000000..46bc39c --- /dev/null +++ b/001_Python入门/06if-else与if-elif与if嵌套.py @@ -0,0 +1,49 @@ +print("hello world") +# ============================================================ +""" +1、if-else: +if:代码块下执行满足条件要做的事情 +else:代码块下执行不满足条件要做的事情,else后面不要追加任何判断条件 +""" +a = 10 +if a > 5: # 条件为真 + print("a大于5") # 执行 +else: # 条件为假 + print("a小于5") # 不执行 +# ============================================================ +""" +2、if-elif: +if:代码块下执行满足条件1要做的事情 +elif:代码块下执行满足其他条件要做的事情,elif后面要追加判断条件 +如果满足任何一个if或者elif条件,那么后面的if或者elif都不执行 +""" +b = 10 +if b > 20: # 条件为假 + print("b大于20") # 不执行 +elif b < 20: # 条件为真 + print("b小于20") # 执行 +else: # 以上条件全部为假时执行此代码块的语句 + print("b等于20") +# ============================================================ +""" +3、if嵌套 +if里面有if +""" +c = 10 +if c > 5: # 条件为真 + print("c大于5") # 执行 + if c < 15: # 继续向下执行代码,条件为真 + print("c小于15") # 执行 + else: # 条件为假 + print("c大于15") # 不执行 +else: # 如果以上判断都为假,则执行此代码块的语句 + print("c小于5") +# ============================================================ +""" +4、三目运算(三元运算): +涉及三个操部分: +真时返回的值:条件为真的时候返回的结果。 +条件:判断条件的真假。 +假时返回的值:条件为假的时候返回的结果。 +""" +print("a大于5") if a > 5 else print("a小于5") diff --git a/001_Python入门/07while循环与循环嵌套.py b/001_Python入门/07while循环与循环嵌套.py new file mode 100644 index 0000000..72c73e7 --- /dev/null +++ b/001_Python入门/07while循环与循环嵌套.py @@ -0,0 +1,113 @@ +print("hello world") +# ============================================================ +""" +1、循环语句: +循环语句用于重复执行某段代码,直到满足某个条件为止 +应当正确改变变量,使条件满足,避免死循环 +""" +# ============================================================ +""" +2、while循环: +while循环在某个条件为 真 的情况下,不断执行循环体中的代码,直到条件变为 假 +while True: 死循环,用法:作为长期运行的任务、持续等待用户输入、不断尝试操作直到成功、游戏循环、 事件循环、需要后台运行的服务 +如何终止死循环?:通过 break 来打破循环、户通过输入特定的指令、捕获异常(如网络连接中断、用户中止等)、操作系统的信号来终止死循环(如 Ctrl+C 发送的中断信号) +while循环嵌套: 一个while循环里还有一个while循环 +""" +# 格式 +i = 0 # 初始化,表示从0开始 +while i <= 5: # 定义条件 + print(i) # 循环体,当前条件为真,执行循环体 + i += 1 # 随后变量自增(改变变量),本质上是i = i + 1;如果不改变变量,则进入死循环 + +# 死循环示例 +while False: # 条件永远为假,不进入死循环;如果是True或者除了0和False的值,则会执行循环体 + print("hello world") + +# 小案例:计算1到100的和 +i = 1 # 初始化, 表示从1开始计算 +s = 0 # 初始化,用于计算和 +while i <= 100: # 定义条件 + s += i # 循环体,s = s + i, 计算和 + i += 1 # 变量自增 +print(s) + +# while循环嵌套,每执行一次外循环,内循环在条件满足的情况下会一直循环 +i = 1 # 定义一个记录外部循环次数的变量 +while i <= 3: # 外部循环,控制循环次数 + print("第%d次外循环" % i) # %d表示格式化输出,用于插入整数 + j = 1 # 定义一个记录内部循环次数的变量 + while j <= 5: # 内部循环,控制循环次数 + print("第%d次内循环" % j) + j += 1 # 变量自增 + i += 1 +# ============================================================ +""" +3、for循环(迭代循环): +for 循环用于遍历(迭代)一个序列(如列表、元组、字符串、字典)或可迭代对象中的每一个元素,并对每个元素执行一段代码。 +可以用于依次取出对象中的元素 +相比while,for循环更简洁,更易读,更易理解,更易维护,更易扩展。 +""" +# 简单格式 +str1 = "hello world" # 定义一个字符串变量,作为可迭代对象 +for i in str1: # i是临时变量,遍历可迭代对象中的每一个字符存储在i中,可以自定义 + print(i) # 循环体,循环打印字符串中的每一个字符 + +# 其他格式1(引入了range()函数) +for i in range(1, 6): # range()函数可接受三个参数:range(start, stop, step),从start开始1,到stop结束6,步长step默认为1;返回值不包含stop,即1,2,3,4,5 + print(i) # 循环体,循环打印1到5 + +# 其他格式2(引入了range()函数,但是不写参数) +for i in range(5): # 循环次数等于从0开始直到填写的数字5,start参数默认为0,所以range(5) 等价于 range(0, 5) + print(i) # 循环体,循环打印0到4 + +# 其他格式3(不打印i值,循环执行其他代码) +for i in range(5): + print("hello world") # 循环体,循环打印5次 + +# 其他格式4(不关心循环变量的值,只关心循环次数) +for _ in range(5): # 用下划线_代替临时变量i,表示不关心循环变量的值,只关心循环次数 + print("hello world") # 循环体,循环打印5次 + +# 小案例:计算1到100的和 +s = 0 # 初始化,用于计算和 +for i in range(1, 101): # 从1到100 + s += i # 每次循环,将i加到s中 +print(s) +# ============================================================ +""" +4、break和continue: +break:在循环中遇到 break 时,立即终止整个循环。 +break只在循环中起作用,即便是在if代码块下,也会立即终止if所在的循环体 +如果有循环嵌套,且break在内循环,那么只影响内部的循环,不会终止外部循环 +continue:跳过本次循环的剩余部分,直接开始下一次循环。 +continue只在循环中起作用,即便是在if代码块下,也会立即中止if所在的循环体的剩余部分 +如果有循环嵌套,且continue在内循环,那么只影响内部的循环,不会跳到外部循环的开头 +他们只能放在循环内 +""" +# break示例1(规范写法, 主要在变量i的自增位置, 更加清晰) +i = 1 # 初始化, 表示从1开始 +while i <= 5: # 定义条件 + print("我在吃第%d个苹果" % i) + if i == 3: # 条件为真,执行循环体,并跳出循环 + print("吃饱了,不吃了") # 循环体 + break # 跳出当前while循环 + i += 1 # 变量自增 + +# break示例2(不太规范的写法,变量i的自增位置在if循环之前, 不方便阅读和逻辑不清晰) +i = 1 +while i <= 5: + print("我在吃第%d个苹果" % i) + i += 1 + if i > 3: + print("吃饱了,不吃了") + break + +# continue示例1(与break不同,变量i的自增需要在continue之前) +i = 1 # 初始化, 表示从1开始 +while i <= 5: # 定义条件 + print("我在吃第%d个苹果" % i) + if i == 3: # 条件为真,执行循环体 + print("发现坏了,第%d个不吃了" % i) + i += 1 # 变量自增 + continue # 跳过当前while循环的剩余部分,直接开始下一次循环 + i += 1 # 变量自增 diff --git a/001_Python入门/08字符串编码与字符串常见操作.py b/001_Python入门/08字符串编码与字符串常见操作.py new file mode 100644 index 0000000..ab3274d --- /dev/null +++ b/001_Python入门/08字符串编码与字符串常见操作.py @@ -0,0 +1,57 @@ +print("hello world") +# ============================================================ +""" +字符串编码: +本质上就是二进制数据与语言文字的一一对应关系 +""" +# ============================================================ +""" +1、ASCII编码 +表示英语及西欧语言,占8bit/1bytes +只能表示少量的字母和数字 +2、GB2312 +国家简体中文字符集,兼容ASCII,占2bytes +可以表示中文 +3、Unicode编码 +国际标准组织统一标准字符集,占2bytes +可以显示各种字符,字符与数字之间的转换速度更快一些 +但是占用存储空间较大 +4、GBK编码 +GB2312的扩展字符集,支持繁体字,兼容GB2312,占2bytes +5、UTF-8编码 +不定长编码,占1-3bytes +把不同的字符用不同的长度表示,节约存储空间,比较常用 +字符与数字的转换速度较慢,每次都需要计算字符需要多少个字节来表示 +""" +# ============================================================ +""" +1、字符串编码转换 +bytes以字节为单位进行处理 +对于bytes,只需要知道他跟字符串类型之间的相互转换 +应用场景: +网络传输数据时通常会将字符串编码为**bytes**,如 HTTP 请求和响应中的数据 +发送 JSON 数据时需要先将其编码为 UTF-8 字节,再通过网络传输 +读写文本文件时需要指定正确的编码格式 +在存储和查询数据库时,需要确保数据的编码一致性,避免出现乱码问题 +编码不仅限于字符处理,还涉及数据压缩与加密算法的实现。例如,某些压缩算法会将数据处理为字节流进行编码。 +""" +# 1. 编码:将字符串转换为字节,引入encode()函数,此函数接受一个字符串参数,返回一个bytes对象 +a = "你好,世界" # 包含中文的字符串 +print(type(a)) # 打印类型 + +a1 = a.encode("utf-8") # 编码为 utf-8 字节序列 +print(a1) # 输出编码: b'\xe4\xbd\xa0\xe5\xa5\xbd\xef\xbc\x8c\xe4\xb8\x96\xe7\x95\x8c' +print(type(a1)) # 打印类型 + +# 2. 解码:将字节转换回字符串,引入decode()函数,此函数接受一个bytes参数,返回一个字符串对象 +a2 = a1.decode("utf-8") # 解码为 utf-8 字符串 +print(a2) # 输出: 你好,世界 +print(type(a2)) # 打印类型 +# ============================================================ +""" +2、字符串常用操作 +字符运算符: ++:字符串链接 +*:重复输出字符串 +[]通过索引 +""" \ No newline at end of file diff --git a/002_练手例程/MDP/README.md b/002_练手例程/MDP/README.md new file mode 100644 index 0000000..2d21f83 --- /dev/null +++ b/002_练手例程/MDP/README.md @@ -0,0 +1,51 @@ +# README + + +回顾一下从头开始配置 Django 项目以展示你的 `zjptjg` 前端组件的主要步骤: + +1. **项目结构确认**: 我们确认了你的项目结构,包含独立的 `backend` (Django) 和 `frontend` (HTML/CSS/JS) 目录。 +2. **创建 Django 应用**: 你创建了名为 `zjptjg` 的 Django 应用 (`python manage.py startapp zjptjg`) 并将其添加到了 `settings.py` 的 `INSTALLED_APPS` 中。 +3. **配置主 URL 路由**: + + * 编辑了项目的主 `urls.py` 文件 (`backend/MDP/MDP/urls.py`)。 + * 导入了 `include` 函数。 + * 添加了 `path('zjptjg/', include('zjptjg.urls'))`,将所有访问 `/zjptjg/` 开头的请求转发给 `zjptjg` 应用处理。 +4. **配置应用 URL 路由**: + + * 在 `zjptjg` 应用目录下创建了 `urls.py` 文件。 + * 在 `zjptjg/urls.py` 中定义了 `path('', views.index, name='zjptjg_index')`,将 `/zjptjg/` (即空路径,相对于应用根路径) 指向名为 `index` 的视图函数。 +5. **创建视图函数**: + + * 编辑了 `zjptjg/views.py` 文件。 + * 创建了名为 `index` 的函数。 + * 这个函数最终的作用是使用 `render(request, 'MDP/zjptjg/index.html')` 来渲染你的 HTML 文件。*(我们中间尝试过让它从数据库获取数据,但后来还原了)* +6. **配置模板目录**: + + * 编辑了 `settings.py` 文件 (`backend/MDP/MDP/settings.py`)。 + * 修改了 `TEMPLATES` 设置中的 `DIRS` 列表,加入了前端目录的路径 `[os.path.join(BASE_DIR.parent.parent, 'frontend')]`。这使得 Django 能够找到位于 `frontend` 目录下的 HTML 模板。 +7. **配置静态文件目录**: + + * 同样在 `settings.py` 文件中。 + * 确认 `STATIC_URL = 'static/'`。 + * 添加了 `STATICFILES_DIRS = [os.path.join(BASE_DIR.parent.parent, 'frontend')]`。这使得 Django 的开发服务器 (`runserver`) 能够找到位于 `frontend` 目录下的 CSS 和 JS 文件。 +8. **修改 HTML 以使用静态文件标签**: + + * 编辑了你的 `index.html` 文件 (`frontend/MDP/zjptjg/index.html`)。 + * 在文件顶部添加了 `{% load static %}`。 + * 将链接 CSS 的 `` 标签的 `href` 修改为 `{% static 'MDP/zjptjg/style.css' %}`。 + * 将引用 JS 的 ` + + \ No newline at end of file diff --git a/002_练手例程/MDP/frontend/MDP/zjptjg/script.js b/002_练手例程/MDP/frontend/MDP/zjptjg/script.js new file mode 100644 index 0000000..936a35f --- /dev/null +++ b/002_练手例程/MDP/frontend/MDP/zjptjg/script.js @@ -0,0 +1,436 @@ +document.addEventListener('DOMContentLoaded', () => { + // --- DOM Elements --- + const machineComponent = document.getElementById('machine-component'); + const settingsModal = document.getElementById('settings-modal'); + const closeModalBtn = document.getElementById('close-modal-btn'); + const cancelSettingsBtn = document.getElementById('cancel-settings-btn'); + const saveSettingsBtn = document.getElementById('save-settings-btn'); + const addStepBtn = document.getElementById('add-step-btn'); + const stepsContainer = document.getElementById('steps-container'); + const machineNameInput = document.getElementById('machine-name-input'); + const batchQuantityInput = document.getElementById('batch-quantity-input'); + const hasCacheCheckbox = document.getElementById('has-cache-checkbox'); + const cacheQuantityInput = document.getElementById('cache-quantity-input'); + const totalTimeDisplay = document.getElementById('total-time-display'); + const calculatedPpmDisplay = document.getElementById('calculated-ppm-display'); + const machineNameDisplay = document.getElementById('machine-name-display'); + const theoreticalPpmDisplay = document.getElementById('theoretical-ppm'); + const modalTitle = document.getElementById('modal-title'); + const statusIndicator = machineComponent.querySelector('.status-indicator'); + const machineStatus = document.getElementById('machine-status'); + + // --- State --- + let steps = []; // Array to hold step data + let initialSettings = {}; // 恢复为空对象 + let isActive = false; // 恢复状态变量 + let isDisabled = false; + + // --- Functions --- + const updateMachineStatus = (newStatusText) => { + machineStatus.textContent = newStatusText; + statusIndicator.classList.remove('active', 'disabled'); // 清除状态 + isDisabled = false; + isActive = false; + if (newStatusText === '运行中') { + statusIndicator.classList.add('active'); + isActive = true; + } else if (newStatusText === '禁用中') { + statusIndicator.classList.add('disabled'); + isDisabled = true; + } else { + // 默认黄色脉冲,不需要特定类 + } + // 恢复存储状态逻辑 + if (initialSettings) { + initialSettings.statusText = newStatusText; + initialSettings.isActive = isActive; + initialSettings.isDisabled = isDisabled; + } + }; + + // --- Validation Helpers --- + const clearValidationErrors = () => { + const errorMessages = settingsModal.querySelectorAll('.error-message'); + errorMessages.forEach(msg => { + msg.textContent = ''; + msg.style.display = 'none'; + }); + const invalidInputs = settingsModal.querySelectorAll('.invalid'); + invalidInputs.forEach(input => input.classList.remove('invalid')); + }; + + const showValidationError = (inputElement, message) => { + inputElement.classList.add('invalid'); + const errorSpanId = inputElement.id + '-error'; // Assumes error span ID convention + const errorSpan = document.getElementById(errorSpanId); + if (errorSpan) { + errorSpan.textContent = message; + errorSpan.style.display = 'block'; + } + // Focus the first invalid element found + if (!settingsModal.querySelector('.invalid:focus')) { + inputElement.focus(); + } + }; + + // Function to remove error state when user types + const clearErrorOnInput = (event) => { + const inputElement = event.target; + inputElement.classList.remove('invalid'); + const errorSpanId = inputElement.id + '-error'; + const errorSpan = document.getElementById(errorSpanId); + if (errorSpan) { + errorSpan.textContent = ''; + errorSpan.style.display = 'none'; + } + }; + + // --- Main Validation Logic --- + const validateSettings = () => { + clearValidationErrors(); + let isValid = true; + const errors = []; + + // 1. Check Machine Name + if (!machineNameInput.value.trim()) { + showValidationError(machineNameInput, '机构名称不能为空'); + isValid = false; + errors.push('机构名称不能为空'); + } + + // 2. Check Batch Quantity + const batchQuantityValue = batchQuantityInput.value; + if (batchQuantityValue === '' || !Number.isInteger(Number(batchQuantityValue)) || Number(batchQuantityValue) < 0) { + showValidationError(batchQuantityInput, '批量处理数量必须是非负整数'); + isValid = false; + errors.push('批量处理数量必须是非负整数'); + } + + // 3. Check Steps + steps.forEach((step, index) => { + const stepIndexDisplay = index + 1; + // Check Step Name + if (!step.nameInput.value.trim()) { + showValidationError(step.nameInput, `步骤 ${stepIndexDisplay} 名称不能为空`); + isValid = false; + errors.push(`步骤 ${stepIndexDisplay} 名称不能为空`); + } + // Add listeners to step inputs dynamically if not already added + if (!step.nameInput.dataset.listenerAdded) { + step.nameInput.addEventListener('input', clearErrorOnInput); + step.nameInput.dataset.listenerAdded = 'true'; + } + // Note: We are not validating start/work time based on requirements, only name + }); + + // 4. Check Cache Quantity (if applicable) + if (hasCacheCheckbox.checked) { + const cacheQuantityValue = cacheQuantityInput.value; + if (cacheQuantityValue === '' || !Number.isInteger(Number(cacheQuantityValue)) || Number(cacheQuantityValue) <= 0) { + showValidationError(cacheQuantityInput, '缓存数量必须是大于0的整数'); + isValid = false; + errors.push('缓存数量必须是大于0的整数'); + } + } + + if (!isValid) { + // Optionally display a summary alert, though inline errors are better UX + // alert('请修正以下错误:\n- ' + errors.join('\n- ')); + } + + return isValid; + }; + + // Calculate Total Time and Theoretical PPM + const calculateMetrics = () => { + let totalDuration = 0; + let maxEndTime = 0; + + steps.forEach(step => { + const startTime = parseFloat(step.startTimeInput.value) || 0; + const workTime = parseFloat(step.workTimeInput.value) || 0; + const endTime = startTime + workTime; + if (endTime > maxEndTime) { + maxEndTime = endTime; + } + }); + + totalDuration = maxEndTime; + totalTimeDisplay.textContent = totalDuration.toFixed(2); + + const batchQuantityRaw = batchQuantityInput.value; + let batchQuantity = 1; // Default if invalid for calculation display + + // Use valid integer for calculation, default to 1 if invalid or 0 + if (batchQuantityRaw !== '' && Number.isInteger(Number(batchQuantityRaw)) && Number(batchQuantityRaw) > 0) { + batchQuantity = parseInt(batchQuantityRaw); + } + + let calculatedPpm = 0; + if (totalDuration > 0) { + calculatedPpm = (60 / totalDuration) * batchQuantity; + } + calculatedPpmDisplay.textContent = calculatedPpm.toFixed(2); + }; + + // Update Step Titles (e.g., "步骤 1", "步骤 2") + const updateStepTitles = () => { + steps.forEach((step, index) => { + step.element.querySelector('.step-title').textContent = `步骤 ${index + 1}`; + step.element.dataset.index = index; // Update data-index for reordering + }); + calculateMetrics(); // Recalculate when steps change order/number + }; + + // Create HTML for a single step + const createStepElement = (stepData = {}, index) => { + const stepId = `step-${Date.now()}-${Math.random()}`; + const stepDiv = document.createElement('div'); + stepDiv.classList.add('step-item'); + stepDiv.id = stepId; + stepDiv.dataset.index = index; + + stepDiv.innerHTML = ` +
+ 步骤 ${index + 1} +
+ + + +
+
+
+
+ + + +
+
+ + + +
+
+ + + +
+
+ `; + + // Add event listeners for controls within this step + stepDiv.querySelector('.delete-step-btn').addEventListener('click', () => deleteStep(stepId)); + stepDiv.querySelector('.move-up-btn').addEventListener('click', () => moveStep(stepId, -1)); + stepDiv.querySelector('.move-down-btn').addEventListener('click', () => moveStep(stepId, 1)); + + // Add listeners to inputs for real-time calculation and error clearing + const nameInput = stepDiv.querySelector('.step-name-input'); + const startTimeInput = stepDiv.querySelector('.step-start-input'); + const workTimeInput = stepDiv.querySelector('.step-work-input'); + + [startTimeInput, workTimeInput, batchQuantityInput].forEach(input => { + input.addEventListener('input', calculateMetrics); + }); + // Add input listener for validation clearing (only needed once per element) + if (!nameInput.dataset.listenerAdded) { + nameInput.addEventListener('input', clearErrorOnInput); + nameInput.dataset.listenerAdded = 'true'; + } + + return { element: stepDiv, id: stepId, nameInput, startTimeInput, workTimeInput }; + }; + + // Add a new step + const addStep = (stepData = {}) => { + const newIndex = steps.length; + const newStep = createStepElement(stepData, newIndex); + stepsContainer.appendChild(newStep.element); + steps.push(newStep); + updateStepTitles(); + }; + + // Delete a step + const deleteStep = (stepId) => { + const stepIndex = steps.findIndex(s => s.id === stepId); + if (stepIndex > -1) { + steps[stepIndex].element.remove(); + steps.splice(stepIndex, 1); + updateStepTitles(); + } + }; + + // Move a step up or down + const moveStep = (stepId, direction) => { + const index = steps.findIndex(s => s.id === stepId); + const newIndex = index + direction; + + if (newIndex >= 0 && newIndex < steps.length) { + // Visual feedback + const currentElement = steps[index].element; + currentElement.classList.add('moving'); + setTimeout(() => { + currentElement.classList.remove('moving'); + // Also remove from the swapped element if it had the class briefly + if (steps[newIndex] && steps[newIndex].element) { + steps[newIndex].element.classList.remove('moving'); + } + }, 300); // Match CSS transition duration + + // Swap in the steps array + [steps[index], steps[newIndex]] = [steps[newIndex], steps[index]]; + + // Re-insert elements in the DOM based on the new order + stepsContainer.innerHTML = ''; // Clear container + steps.forEach(step => stepsContainer.appendChild(step.element)); // Re-append in new order + + updateStepTitles(); + } + }; + + // Toggle Cache Quantity Input + const toggleCacheInput = () => { + const isChecked = hasCacheCheckbox.checked; + cacheQuantityInput.disabled = !isChecked; + if (isChecked) { + cacheQuantityInput.required = true; // Make required when checked + } else { + cacheQuantityInput.required = false; // Not required when unchecked + cacheQuantityInput.value = ''; // Clear value when disabled + // Clear potential validation error when disabling + cacheQuantityInput.classList.remove('invalid'); + const errorSpan = document.getElementById('cache-quantity-input-error'); + if (errorSpan) { + errorSpan.textContent = ''; + errorSpan.style.display = 'none'; + } + } + }; + + // Open Settings Modal + const openModal = () => { + clearValidationErrors(); + // 恢复为从当前状态存储设置 + initialSettings = { + name: machineNameInput.value, + batchQuantity: batchQuantityInput.value, + hasCache: hasCacheCheckbox.checked, + cacheQuantity: cacheQuantityInput.value, + stepsData: steps.map(s => ({ + name: s.nameInput.value, + startTime: s.startTimeInput.value, + workTime: s.workTimeInput.value + })), + isActive: statusIndicator.classList.contains('active'), + isDisabled: statusIndicator.classList.contains('disabled'), + statusText: machineStatus.textContent, + theoreticalPPM: theoreticalPpmDisplay.textContent, + currentStep: document.getElementById('current-step').textContent, + currentPPM: document.getElementById('current-ppm').textContent + }; + // 恢复从JS状态重建模态框步骤 + stepsContainer.innerHTML = ''; + steps = []; + initialSettings.stepsData.forEach(stepData => addStep(stepData)); + + modalTitle.textContent = `编辑-${initialSettings.name || '一般机构'}`; + toggleCacheInput(); + calculateMetrics(); + settingsModal.style.display = 'flex'; + }; + + // Close Settings Modal + const closeModal = () => { + settingsModal.style.display = 'none'; + }; + + // Revert settings to initial state (on cancel or 'X' click) + const revertSettings = () => { + clearValidationErrors(); + machineNameInput.value = initialSettings.name; + batchQuantityInput.value = initialSettings.batchQuantity; + hasCacheCheckbox.checked = initialSettings.hasCache; + cacheQuantityInput.value = initialSettings.cacheQuantity; + toggleCacheInput(); + + stepsContainer.innerHTML = ''; + steps = []; + initialSettings.stepsData.forEach(stepData => addStep(stepData)); + + // 恢复主显示状态 + machineNameDisplay.textContent = initialSettings.name; + theoreticalPpmDisplay.textContent = initialSettings.theoreticalPPM; + updateMachineStatus(initialSettings.statusText); + document.getElementById('current-step').textContent = initialSettings.currentStep; + document.getElementById('current-ppm').textContent = initialSettings.currentPPM; + + closeModal(); + }; + + // Save Settings + const saveSettings = () => { + if (!validateSettings()) { + console.log("Validation failed."); + return; + } + console.log("Validation passed."); + + const newName = machineNameInput.value.trim(); + const batchQty = parseInt(batchQuantityInput.value); + + machineNameDisplay.textContent = newName; + calculateMetrics(); + theoreticalPpmDisplay.textContent = calculatedPpmDisplay.textContent + 'PPM'; + + if (batchQty === 0) { + updateMachineStatus('禁用中'); + } else { + updateMachineStatus('运行中'); + } + + document.getElementById('current-step').textContent = steps.length > 0 ? steps[0].nameInput.value : '无步骤'; + document.getElementById('current-ppm').textContent = '0.00PPM'; + + closeModal(); + }; + + // --- Event Listeners --- + machineComponent.addEventListener('dblclick', openModal); + closeModalBtn.addEventListener('click', revertSettings); + cancelSettingsBtn.addEventListener('click', revertSettings); + saveSettingsBtn.addEventListener('click', saveSettings); + addStepBtn.addEventListener('click', () => addStep()); + hasCacheCheckbox.addEventListener('change', toggleCacheInput); + machineNameInput.addEventListener('input', clearErrorOnInput); + batchQuantityInput.addEventListener('input', clearErrorOnInput); + cacheQuantityInput.addEventListener('input', clearErrorOnInput); + + // --- Initialization --- + const initialize = () => { + // 恢复添加默认步骤 + addStep({ name: '步骤1', startTime: 0, workTime: 3 }); + addStep({ name: '步骤2', startTime: 2, workTime: 3 }); + + // 恢复设置默认值 + machineNameInput.value = '一般机构'; + batchQuantityInput.value = 1; + hasCacheCheckbox.checked = true; + cacheQuantityInput.value = 3; + toggleCacheInput(); + + machineNameDisplay.textContent = machineNameInput.value; + calculateMetrics(); + theoreticalPpmDisplay.textContent = calculatedPpmDisplay.textContent + 'PPM'; + + document.getElementById('current-step').textContent = '步骤1'; + document.getElementById('current-ppm').textContent = '0.00PPM'; + updateMachineStatus('等待中'); + + // 恢复存储初始理论PPM + if (!initialSettings.theoreticalPPM) { + initialSettings.theoreticalPPM = theoreticalPpmDisplay.textContent; + } + clearValidationErrors(); + }; + + initialize(); +}); \ No newline at end of file diff --git a/002_练手例程/MDP/frontend/MDP/zjptjg/style.css b/002_练手例程/MDP/frontend/MDP/zjptjg/style.css new file mode 100644 index 0000000..1cd5aff --- /dev/null +++ b/002_练手例程/MDP/frontend/MDP/zjptjg/style.css @@ -0,0 +1,679 @@ +/* 全局和页面基础样式 */ +body { + font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; + background-color: #f4f7f6; /* 页面背景色 */ + display: flex; + justify-content: center; /* 水平居中 */ + align-items: center; /* 垂直居中 */ + min-height: 100vh; + margin: 0; +} + +/* --- 主组件显示区域样式 --- */ +.machine-component { + background-color: #ffffff; /* 组件背景色 */ + border-radius: 12px; /* 圆角 */ + box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08); /* 阴影 */ + padding: 15px; /* Adjusted padding */ + max-width: 350px; /* Max width on larger screens */ + width: 90%; /* Relative width on smaller screens */ + margin: 10px; /* Add some margin */ + cursor: pointer; /* 鼠标样式 */ + transition: box-shadow 0.3s ease; /* 阴影过渡效果 */ + border: 1px solid #e0e0e0; /* 边框 */ +} + +.machine-component:hover { + box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12); /* 鼠标悬浮时阴影加强 */ +} + +/* 主组件头部 */ +.header { + display: flex; + justify-content: space-between; /* 两端对齐 */ + align-items: center; /* 垂直居中 */ + margin-bottom: 15px; + padding-bottom: 10px; + border-bottom: 1px solid #eee; /* 底部边框分割线 */ +} + +/* 主组件 - 机构名称 */ +#machine-name-display { + font-size: 1.2em; + font-weight: 600; + color: #333; +} + +/* 主组件 - 状态指示灯 */ +.status-indicator { + width: 12px; + height: 12px; + border-radius: 50%; /* 圆形 */ + background-color: #ffc107; /* Default Yellow for waiting */ + transition: background-color 0.3s ease; /* Keep transition for color change */ + /* Apply default yellow pulse animation */ + animation: pulse-yellow 1.5s infinite; +} + +/* Active state overrides */ +.status-indicator.active { + background-color: #4CAF50; /* Green when active */ + animation-name: pulse-green; /* Change animation name */ +} + +/* Disabled state overrides */ +.status-indicator.disabled { + background-color: #dc3545; /* Red when disabled */ + animation-name: pulse-red; /* Use red pulse */ +} + +/* Define the GREEN pulse animation */ +@keyframes pulse-green { + 0% { + box-shadow: 0 0 0 0 rgba(76, 175, 80, 0.5); /* Green shadow */ + } + 70% { + box-shadow: 0 0 0 8px rgba(76, 175, 80, 0); + } + 100% { + box-shadow: 0 0 0 0 rgba(76, 175, 80, 0); + } +} + +/* Define the YELLOW pulse animation */ +@keyframes pulse-yellow { + 0% { + box-shadow: 0 0 0 0 rgba(255, 193, 7, 0.5); /* Yellow shadow */ + } + 70% { + box-shadow: 0 0 0 8px rgba(255, 193, 7, 0); + } + 100% { + box-shadow: 0 0 0 0 rgba(255, 193, 7, 0); + } +} + +/* Define the RED pulse animation */ +@keyframes pulse-red { + 0% { + box-shadow: 0 0 0 0 rgba(220, 53, 69, 0.5); /* Red shadow */ + } + 70% { + box-shadow: 0 0 0 8px rgba(220, 53, 69, 0); + } + 100% { + box-shadow: 0 0 0 0 rgba(220, 53, 69, 0); + } +} + +/* 主组件 - 信息网格布局 */ +.info-grid { + display: grid; + grid-template-columns: auto 1fr; /* 标签自适应,值占满剩余空间 */ + gap: 8px 15px; /* 行间距 列间距 */ + margin-bottom: 15px; + font-size: 0.95em; +} + +/* 主组件 - 信息标签 */ +.info-label { + color: #555; + font-weight: 500; + text-align: right; /* 文本右对齐 */ +} + +/* 主组件 - 信息值 */ +.info-value { + color: #333; + font-weight: 600; +} + +/* 主组件 - 底部状态文本 */ +.status-text { + text-align: center; + font-weight: 500; + color: #666; + padding-top: 10px; + border-top: 1px solid #eee; /* 顶部边框分割线 */ + font-size: 0.9em; +} + +/* --- 设置弹窗 (Modal) 样式 --- */ + +/* 弹窗遮罩层 */ +.modal-overlay { + position: fixed; /* 固定定位,覆盖全屏 */ + top: 0; + left: 0; + width: 100%; + height: 100%; + background-color: rgba(0, 0, 0, 0.5); /* 半透明黑色背景 */ + display: flex; + justify-content: center; /* 水平居中弹窗内容 */ + align-items: center; /* 垂直居中弹窗内容 */ + z-index: 1000; /* 置于顶层 */ +} + +/* 弹窗内容区域 */ +.modal-content { + background-color: #fff; + border-radius: 10px; /* 圆角 */ + box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2); + max-width: 600px; /* Max width on larger screens */ + width: 90vw; /* Relative width */ + max-height: 90vh; /* 最大高度为视窗的90% */ + display: flex; /* Use flexbox for layout */ + flex-direction: column; /* Stack header, scroll, footer vertically */ + overflow: hidden; /* Re-add overflow hidden to clip children and enforce height */ +} + +/* Remove scrollbar styles from .modal-content */ +/* +.modal-content::-webkit-scrollbar { ... } +.modal-content::-webkit-scrollbar-track { ... } +.modal-content::-webkit-scrollbar-thumb { ... } +.modal-content::-webkit-scrollbar-thumb:hover { ... } +*/ + +/* Fixed Header Section */ +.modal-fixed-header { + padding: 20px 25px 0 25px; /* Padding T, R/L, B */ + border-bottom: 1px solid #eee; /* Separator */ +} + +.steps-legend { + /* Styles for the moved legend */ + font-weight: 600; + color: #333; + padding: 10px 0 5px 0; /* Adjust padding */ + margin: 0; /* Remove default legend margin */ + font-size: 1.1em; /* Match step-title size */ +} + + +/* Scrollable Steps Area */ +.modal-scrollable-steps { + flex-grow: 1; /* Allow this section to take available vertical space */ + overflow-y: auto; /* Enable vertical scrolling ONLY for this section */ + padding: 15px 25px; /* Padding inside the scrollable area */ + /* Apply custom scrollbar styles HERE */ + scrollbar-width: thin; /* Firefox */ + scrollbar-color: #ccc #f4f4f4; /* Firefox */ +} + +.modal-scrollable-steps::-webkit-scrollbar { + width: 8px; +} + +.modal-scrollable-steps::-webkit-scrollbar-track { + background: #f4f4f4; + border-radius: 10px; + margin: 5px 0; /* Add slight margin */ +} + +.modal-scrollable-steps::-webkit-scrollbar-thumb { + background-color: #ccc; + border-radius: 10px; + border: 2px solid #f4f4f4; +} + +.modal-scrollable-steps::-webkit-scrollbar-thumb:hover { + background-color: #aaa; +} + +/* Fixed Footer Section */ +.modal-fixed-footer { + padding: 10px 25px 20px 25px; /* Padding T, R/L, B */ + border-top: 1px solid #eee; /* Separator */ + background-color: #fff; /* Ensure solid background */ +} + +/* Adjustments for items moved to footer */ +.modal-fixed-footer .add-btn { + margin-top: 10px; /* Adjust top margin */ + margin-bottom: 15px; /* Add bottom margin */ +} + +.modal-fixed-footer .cache-group { + margin-bottom: 15px; /* Add consistent margin */ +} + +.modal-fixed-footer .summary-section { + margin-top: 15px; /* Adjust top margin */ + padding-top: 0; /* Remove padding as border is above */ + border-top: none; /* Remove border as it's on footer now */ +} + +.modal-fixed-footer .modal-footer { + margin-top: 15px; /* Adjust top margin */ + padding-top: 0; /* Remove padding as border is above */ + border-top: none; /* Remove border as it's on footer now */ +} + + +/* Remove original steps-config styling */ +/* +.steps-config { ... } +.steps-config legend { ... } +*/ + +/* 弹窗头部 */ +.modal-header { + display: flex; + justify-content: space-between; + align-items: center; + border-bottom: 1px solid #eee; + padding-bottom: 15px; + margin-bottom: 20px; +} + +/* 弹窗标题 */ +#modal-title { + font-size: 1.4em; + font-weight: 600; + color: #333; +} + +/* 弹窗关闭按钮 */ +.close-btn { + background: none; + border: none; + font-size: 1.8em; + cursor: pointer; + color: #888; +} + +.close-btn:hover { + color: #333; +} + +/* 弹窗主体内容区域 */ +.modal-body { + margin-bottom: 20px; +} + +/* 通用表单组样式 */ +.form-group { + margin-bottom: 15px; + display: grid; + grid-template-columns: 120px 1fr; /* 标签固定宽度,输入框占满剩余 - Default */ + align-items: center; + gap: 5px 10px; /* Reduced gap slightly */ +} + +/* 表单标签 */ +.form-group label { + font-weight: 500; + color: #555; + text-align: right; +} + +/* 表单输入框 (文本和数字) */ +.form-group input[type="text"], +.form-group input[type="number"] { + padding: 8px 12px; + border: 1px solid #ccc; + border-radius: 6px; + font-size: 0.95em; + transition: border-color 0.3s ease; +} + +/* 输入框获取焦点时样式 */ +.form-group input[type="text"]:focus, +.form-group input[type="number"]:focus { + border-color: #007bff; /* 边框变蓝 */ + outline: none; /* 移除默认轮廓 */ +} + +/* 禁用的数字输入框 */ +.form-group input[type="number"][disabled] { + background-color: #e9ecef; + cursor: not-allowed; +} + +/* --- 步骤设置区域 --- */ +.steps-config { + border: 1px solid #ddd; /* 边框 */ + border-radius: 8px; /* 圆角 */ + padding: 15px; + margin-bottom: 20px; +} + +/* 步骤设置区域标题 */ +.steps-config legend { + font-weight: 600; + color: #333; + padding: 0 10px; +} + +/* 单个步骤项 */ +.step-item { + border: 1px dashed #ccc; /* 虚线边框 */ + border-radius: 6px; + padding: 15px; + margin-bottom: 15px; + position: relative; + background-color: #f9f9f9; +} + +/* 步骤项头部 */ +.step-header { + display: flex; + justify-content: space-between; + align-items: center; + margin-bottom: 10px; +} + +/* 步骤标题 (如: 步骤 1) */ +.step-title { + font-weight: bold; + font-size: 1.1em; +} + +/* 步骤控制按钮组 (上移/下移/删除) */ +.step-controls { + display: flex; + gap: 5px; +} + +/* 步骤控制按钮通用样式 */ +.step-btn { + background: none; + border: none; + cursor: pointer; + font-size: 1.2em; + color: #888; +} +.step-btn:hover { color: #333; } +/* 删除按钮特定颜色 */ +.delete-step-btn { color: #dc3545; } +.delete-step-btn:hover { color: #a71d2a; } + +/* 步骤内部输入框布局 */ +.step-inputs { + display: grid; + grid-template-columns: auto 1fr 1fr; /* 名称自适应,时间占剩余空间 - Default */ + gap: 10px; + align-items: start; /* 顶部对齐 */ +} + +/* 步骤内表单组 */ +.step-inputs .form-group { + grid-template-columns: 1fr; /* 内部标签和输入框垂直排列 */ + margin-bottom: 0; + gap: 3px; +} +/* 步骤内标签样式 */ +.step-inputs label { + text-align: left; + font-size: 0.85em; + margin-bottom: 2px; + color: #666; + display: block; /* 确保独占一行 */ + white-space: nowrap; /* 防止标签换行 */ + overflow: hidden; /* 隐藏超出部分 */ + text-overflow: ellipsis; /* 超出部分显示省略号 */ + max-width: 100%; /* 防止标签撑开布局 */ +} + +/* 限制步骤内时间输入框的最大宽度 */ +.step-inputs .form-group:nth-child(2) input[type="number"], +.step-inputs .form-group:nth-child(3) input[type="number"] { + max-width: 85px; /* 最大宽度限制 */ + width: 100%; /* 允许在容器缩小时也缩小 */ +} + +/* 确保步骤内名称输入框填满其列 */ +.step-inputs .form-group:nth-child(1) input[type="text"] { + width: 85%; +} + +/* --- 其他设置和按钮 --- */ + +/* 添加步骤按钮 */ +.add-btn { + padding: 8px 15px; + background-color: #28a745; + color: white; + border: none; + border-radius: 8px; + cursor: pointer; + font-size: 0.95em; + transition: background-color 0.3s ease; + margin-top: 15px; + /* 居中显示 */ + display: block; + width: fit-content; /* 宽度自适应内容 */ + margin-left: auto; + margin-right: auto; +} + +.add-btn:hover { + background-color: #218838; +} + +/* 缓存设置组 */ +.cache-group { + display: grid; /* Use grid for better control with errors */ + grid-template-columns: auto auto 1fr; /* checkbox, label, input - Default */ + align-items: center; + gap: 10px; +} + +/* 缓存复选框 */ +.cache-group input[type="checkbox"] { grid-row: 1; } +.cache-group label[for="has-cache-checkbox"] { grid-row: 1; text-align: left; } +.cache-group input[type="number"] { grid-row: 1; } +.cache-group .error-message { + grid-column: 3; /* Error below the number input */ + grid-row: 2; + margin-top: 2px; +} + +/* 汇总信息区域 */ +.summary-section { + margin-top: 20px; + padding-top: 15px; + border-top: 1px solid #eee; + display: flex; + justify-content: space-around; /* 两端分散对齐 */ + font-size: 0.95em; + color: #555; +} + +/* 汇总信息中的数值 */ +.summary-section span span { + font-weight: 600; + color: #333; +} + +/* 弹窗底部按钮区域 */ +.modal-footer { + display: flex; + justify-content: flex-end; /* 按钮靠右对齐 */ + gap: 10px; + padding-top: 15px; + border-top: 1px solid #eee; + margin-top: 20px; +} + +/* 保存和取消按钮通用样式 */ +.save-btn, +.cancel-btn { + padding: 10px 20px; + border: none; + border-radius: 6px; + cursor: pointer; + font-size: 1em; + transition: background-color 0.3s ease, color 0.3s ease; +} + +/* 保存按钮 */ +.save-btn { + background-color: #007bff; + color: white; +} + +.save-btn:hover { + background-color: #0056b3; +} + +/* 取消按钮 */ +.cancel-btn { + background-color: #f8f9fa; + color: #333; + border: 1px solid #ccc; +} + +.cancel-btn:hover { + background-color: #e2e6ea; +} + +/* --- 工具类样式 --- */ + +/* 错误消息 (未使用,可备用) */ +.error-message { + color: #dc3545; + font-size: 0.85em; /* Slightly larger */ + padding-left: 0; /* Remove padding */ + display: none; /* Hidden by default */ + margin-top: 2px; /* Add small top margin */ +} + +/* Ensure error message appears below input in standard form groups */ +.form-group .error-message { + grid-column: 2; /* Align with input */ + grid-row: 2; /* Place on the row below the input */ + text-align: left; +} + +/* Error messages within steps */ +.step-inputs .error-message { + /* display: block; */ /* Already block by default */ + width: 100%; /* Take full width */ + margin-top: 2px; + text-align: left; +} + +/* Adjust cache group alignment when error shows */ +.cache-group { + display: grid; /* Use grid for better control with errors */ + grid-template-columns: auto auto 1fr; /* checkbox, label, input */ + align-items: center; + gap: 10px; +} +.cache-group input[type="checkbox"] { grid-row: 1; } +.cache-group label[for="has-cache-checkbox"] { grid-row: 1; text-align: left; } +.cache-group input[type="number"] { grid-row: 1; } +.cache-group .error-message { + grid-column: 3; /* Error below the number input */ + grid-row: 2; + margin-top: 2px; +} + +/* 步骤项移动时的视觉反馈 */ +.step-item.moving { + transition: background-color 0.3s ease-out; + background-color: #e6f7ff; /* 淡蓝色高亮 */ +} + +/* Input Validation Styles */ +input:invalid, +textarea:invalid { + border-color: #dc3545; /* Red border for invalid fields */ +} + +.form-group input.invalid, +.step-item input.invalid { + border-color: #dc3545 !important; /* Force red border */ + background-color: #fff3f3; /* Light red background */ +} + +.error-tooltip { + color: #dc3545; + font-size: 0.8em; + padding-left: 5px; + display: none; /* Hidden by default */ +} + +.form-group .error-tooltip { + grid-column: 2; /* Align with input in main form groups */ +} + +/* --- Responsive Adjustments --- */ + +@media (max-width: 600px) { + + /* Reduce padding/font size slightly globally in modal? Optional */ + .modal-content { + width: 95vw; /* Use more width on mobile */ + max-height: 95vh; /* Allow slightly more height */ + } + + .modal-fixed-header, + .modal-scrollable-steps, + .modal-fixed-footer { + padding: 15px; /* Consistent padding */ + } + + /* Stack form groups vertically */ + .form-group { + grid-template-columns: 1fr; /* Single column */ + gap: 5px; /* Reduce gap */ + } + + .form-group label { + text-align: left; /* Align labels left */ + margin-bottom: 2px; + } + + /* Ensure error messages span full width below input */ + .form-group .error-message { + grid-column: 1; /* Span full column */ + grid-row: 3; /* Ensure it's below label and input */ + } + + /* Stack step inputs vertically */ + .step-inputs { + grid-template-columns: 1fr; /* Single column */ + gap: 10px; + } + + /* Allow time inputs to take more width when stacked */ + .step-inputs .form-group:nth-child(2) input[type="number"], + .step-inputs .form-group:nth-child(3) input[type="number"] { + max-width: none; /* Remove max-width limit */ + } + + /* Stack cache group elements */ + .cache-group { + grid-template-columns: auto 1fr; /* Checkbox | Label & Input */ + gap: 5px 10px; + } + .cache-group input[type="checkbox"] { grid-row: 1; grid-column: 1; } + .cache-group label[for="has-cache-checkbox"] { grid-row: 1; grid-column: 2; } + .cache-group input[type="number"] { grid-row: 2; grid-column: 1 / span 2; width: 100%;} /* Input below */ + .cache-group .error-message { + grid-row: 3; /* Error below input */ + grid-column: 1 / span 2; + } + + /* Stack summary section */ + .summary-section { + flex-direction: column; /* Stack items */ + align-items: center; /* Center align */ + gap: 5px; + } + + /* Adjust footer buttons */ + .modal-footer { + justify-content: space-around; /* Space out buttons more */ + } + + .save-btn, + .cancel-btn { + padding: 8px 15px; /* Slightly smaller buttons */ + font-size: 0.95em; + } + +} \ No newline at end of file diff --git a/002_练手例程/一般机构组件/index.html b/002_练手例程/一般机构组件/index.html new file mode 100644 index 0000000..b930533 --- /dev/null +++ b/002_练手例程/一般机构组件/index.html @@ -0,0 +1,79 @@ + + + + + + 一般机构组件 + + + + +
+
+ 一般机构 +
+
+
+
当前步骤
+
第一步
+
理论产能
+
60.00PPM
+
当前产能
+
59.05PPM
+
+
等待下料
+
+ + + + + + + \ No newline at end of file diff --git a/002_练手例程/一般机构组件/script.js b/002_练手例程/一般机构组件/script.js new file mode 100644 index 0000000..fc8421b --- /dev/null +++ b/002_练手例程/一般机构组件/script.js @@ -0,0 +1,452 @@ +document.addEventListener('DOMContentLoaded', () => { + // --- DOM Elements --- + const machineComponent = document.getElementById('machine-component'); + const settingsModal = document.getElementById('settings-modal'); + const closeModalBtn = document.getElementById('close-modal-btn'); + const cancelSettingsBtn = document.getElementById('cancel-settings-btn'); + const saveSettingsBtn = document.getElementById('save-settings-btn'); + const addStepBtn = document.getElementById('add-step-btn'); + const stepsContainer = document.getElementById('steps-container'); + const machineNameInput = document.getElementById('machine-name-input'); + const batchQuantityInput = document.getElementById('batch-quantity-input'); + const hasCacheCheckbox = document.getElementById('has-cache-checkbox'); + const cacheQuantityInput = document.getElementById('cache-quantity-input'); + const totalTimeDisplay = document.getElementById('total-time-display'); + const calculatedPpmDisplay = document.getElementById('calculated-ppm-display'); + const machineNameDisplay = document.getElementById('machine-name-display'); + const theoreticalPpmDisplay = document.getElementById('theoretical-ppm'); + const modalTitle = document.getElementById('modal-title'); + const statusIndicator = machineComponent.querySelector('.status-indicator'); // Get status indicator + const machineStatus = document.getElementById('machine-status'); // Get status text element + + // --- State --- + let steps = []; // Array to hold step data + let initialSettings = {}; // To store settings when modal opens + let isActive = false; // Track if the machine is considered active + let isDisabled = false; // Track if machine is disabled (batch=0) + + // --- Functions --- + + // Helper function to update status text AND indicator light + const updateMachineStatus = (newStatusText) => { + machineStatus.textContent = newStatusText; + statusIndicator.classList.remove('active', 'disabled'); // Clear previous state classes + isDisabled = false; + isActive = false; + + if (newStatusText === '运行中') { + statusIndicator.classList.add('active'); + isActive = true; + } else if (newStatusText === '禁用中') { + statusIndicator.classList.add('disabled'); + isDisabled = true; + } else { + // Default: Waiting (yellow pulse) - no specific class needed + } + + // Store the current text and state in case modal is opened later + if (initialSettings) { // Prevent error during initial load + initialSettings.statusText = newStatusText; + initialSettings.isActive = isActive; + initialSettings.isDisabled = isDisabled; + } + }; + + // --- Validation Helpers --- + const clearValidationErrors = () => { + const errorMessages = settingsModal.querySelectorAll('.error-message'); + errorMessages.forEach(msg => { + msg.textContent = ''; + msg.style.display = 'none'; + }); + const invalidInputs = settingsModal.querySelectorAll('.invalid'); + invalidInputs.forEach(input => input.classList.remove('invalid')); + }; + + const showValidationError = (inputElement, message) => { + inputElement.classList.add('invalid'); + const errorSpanId = inputElement.id + '-error'; // Assumes error span ID convention + const errorSpan = document.getElementById(errorSpanId); + if (errorSpan) { + errorSpan.textContent = message; + errorSpan.style.display = 'block'; + } + // Focus the first invalid element found + if (!settingsModal.querySelector('.invalid:focus')) { + inputElement.focus(); + } + }; + + // Function to remove error state when user types + const clearErrorOnInput = (event) => { + const inputElement = event.target; + inputElement.classList.remove('invalid'); + const errorSpanId = inputElement.id + '-error'; + const errorSpan = document.getElementById(errorSpanId); + if (errorSpan) { + errorSpan.textContent = ''; + errorSpan.style.display = 'none'; + } + }; + + // --- Main Validation Logic --- + const validateSettings = () => { + clearValidationErrors(); + let isValid = true; + const errors = []; + + // 1. Check Machine Name + if (!machineNameInput.value.trim()) { + showValidationError(machineNameInput, '机构名称不能为空'); + isValid = false; + errors.push('机构名称不能为空'); + } + + // 2. Check Batch Quantity + const batchQuantityValue = batchQuantityInput.value; + if (batchQuantityValue === '' || !Number.isInteger(Number(batchQuantityValue)) || Number(batchQuantityValue) < 0) { + showValidationError(batchQuantityInput, '批量处理数量必须是非负整数'); + isValid = false; + errors.push('批量处理数量必须是非负整数'); + } + + // 3. Check Steps + steps.forEach((step, index) => { + const stepIndexDisplay = index + 1; + // Check Step Name + if (!step.nameInput.value.trim()) { + showValidationError(step.nameInput, `步骤 ${stepIndexDisplay} 名称不能为空`); + isValid = false; + errors.push(`步骤 ${stepIndexDisplay} 名称不能为空`); + } + // Add listeners to step inputs dynamically if not already added + if (!step.nameInput.dataset.listenerAdded) { + step.nameInput.addEventListener('input', clearErrorOnInput); + step.nameInput.dataset.listenerAdded = 'true'; + } + // Note: We are not validating start/work time based on requirements, only name + }); + + // 4. Check Cache Quantity (if applicable) + if (hasCacheCheckbox.checked) { + const cacheQuantityValue = cacheQuantityInput.value; + if (cacheQuantityValue === '' || !Number.isInteger(Number(cacheQuantityValue)) || Number(cacheQuantityValue) <= 0) { + showValidationError(cacheQuantityInput, '缓存数量必须是大于0的整数'); + isValid = false; + errors.push('缓存数量必须是大于0的整数'); + } + } + + if (!isValid) { + // Optionally display a summary alert, though inline errors are better UX + // alert('请修正以下错误:\n- ' + errors.join('\n- ')); + } + + return isValid; + }; + + // Calculate Total Time and Theoretical PPM + const calculateMetrics = () => { + let totalDuration = 0; + let maxEndTime = 0; + + steps.forEach(step => { + const startTime = parseFloat(step.startTimeInput.value) || 0; + const workTime = parseFloat(step.workTimeInput.value) || 0; + const endTime = startTime + workTime; + if (endTime > maxEndTime) { + maxEndTime = endTime; + } + }); + + totalDuration = maxEndTime; + totalTimeDisplay.textContent = totalDuration.toFixed(2); + + const batchQuantityRaw = batchQuantityInput.value; + let batchQuantity = 1; // Default if invalid for calculation display + + // Use valid integer for calculation, default to 1 if invalid or 0 + if (batchQuantityRaw !== '' && Number.isInteger(Number(batchQuantityRaw)) && Number(batchQuantityRaw) > 0) { + batchQuantity = parseInt(batchQuantityRaw); + } + + let calculatedPpm = 0; + if (totalDuration > 0) { + calculatedPpm = (60 / totalDuration) * batchQuantity; + } + calculatedPpmDisplay.textContent = calculatedPpm.toFixed(2); + }; + + // Update Step Titles (e.g., "步骤 1", "步骤 2") + const updateStepTitles = () => { + steps.forEach((step, index) => { + step.element.querySelector('.step-title').textContent = `步骤 ${index + 1}`; + step.element.dataset.index = index; // Update data-index for reordering + }); + calculateMetrics(); // Recalculate when steps change order/number + }; + + // Create HTML for a single step + const createStepElement = (stepData = {}, index) => { + const stepId = `step-${Date.now()}-${Math.random()}`; + const stepDiv = document.createElement('div'); + stepDiv.classList.add('step-item'); + stepDiv.id = stepId; + stepDiv.dataset.index = index; + + stepDiv.innerHTML = ` +
+ 步骤 ${index + 1} +
+ + + +
+
+
+
+ + + +
+
+ + + +
+
+ + + +
+
+ `; + + // Add event listeners for controls within this step + stepDiv.querySelector('.delete-step-btn').addEventListener('click', () => deleteStep(stepId)); + stepDiv.querySelector('.move-up-btn').addEventListener('click', () => moveStep(stepId, -1)); + stepDiv.querySelector('.move-down-btn').addEventListener('click', () => moveStep(stepId, 1)); + + // Add listeners to inputs for real-time calculation and error clearing + const nameInput = stepDiv.querySelector('.step-name-input'); + const startTimeInput = stepDiv.querySelector('.step-start-input'); + const workTimeInput = stepDiv.querySelector('.step-work-input'); + + [startTimeInput, workTimeInput, batchQuantityInput].forEach(input => { + input.addEventListener('input', calculateMetrics); + }); + // Add input listener for validation clearing (only needed once per element) + if (!nameInput.dataset.listenerAdded) { + nameInput.addEventListener('input', clearErrorOnInput); + nameInput.dataset.listenerAdded = 'true'; + } + + return { element: stepDiv, id: stepId, nameInput, startTimeInput, workTimeInput }; + }; + + // Add a new step + const addStep = (stepData = {}) => { + const newIndex = steps.length; + const newStep = createStepElement(stepData, newIndex); + stepsContainer.appendChild(newStep.element); + steps.push(newStep); + updateStepTitles(); + }; + + // Delete a step + const deleteStep = (stepId) => { + const stepIndex = steps.findIndex(s => s.id === stepId); + if (stepIndex > -1) { + steps[stepIndex].element.remove(); + steps.splice(stepIndex, 1); + updateStepTitles(); + } + }; + + // Move a step up or down + const moveStep = (stepId, direction) => { + const index = steps.findIndex(s => s.id === stepId); + const newIndex = index + direction; + + if (newIndex >= 0 && newIndex < steps.length) { + // Visual feedback + const currentElement = steps[index].element; + currentElement.classList.add('moving'); + setTimeout(() => { + currentElement.classList.remove('moving'); + // Also remove from the swapped element if it had the class briefly + if (steps[newIndex] && steps[newIndex].element) { + steps[newIndex].element.classList.remove('moving'); + } + }, 300); // Match CSS transition duration + + // Swap in the steps array + [steps[index], steps[newIndex]] = [steps[newIndex], steps[index]]; + + // Re-insert elements in the DOM based on the new order + stepsContainer.innerHTML = ''; // Clear container + steps.forEach(step => stepsContainer.appendChild(step.element)); // Re-append in new order + + updateStepTitles(); + } + }; + + // Toggle Cache Quantity Input + const toggleCacheInput = () => { + const isChecked = hasCacheCheckbox.checked; + cacheQuantityInput.disabled = !isChecked; + if (isChecked) { + cacheQuantityInput.required = true; // Make required when checked + } else { + cacheQuantityInput.required = false; // Not required when unchecked + cacheQuantityInput.value = ''; // Clear value when disabled + // Clear potential validation error when disabling + cacheQuantityInput.classList.remove('invalid'); + const errorSpan = document.getElementById('cache-quantity-input-error'); + if (errorSpan) { + errorSpan.textContent = ''; + errorSpan.style.display = 'none'; + } + } + }; + + // Open Settings Modal + const openModal = () => { + clearValidationErrors(); // Clear errors when opening + // Store current settings to revert on cancel + initialSettings = { + name: machineNameInput.value, + batchQuantity: batchQuantityInput.value, + hasCache: hasCacheCheckbox.checked, + cacheQuantity: cacheQuantityInput.value, + stepsData: steps.map(s => ({ // Only store values, not elements + name: s.nameInput.value, + startTime: s.startTimeInput.value, + workTime: s.workTimeInput.value + })), + // Store current display state + isActive: statusIndicator.classList.contains('active'), + isDisabled: statusIndicator.classList.contains('disabled'), // Store disabled state + statusText: machineStatus.textContent, + theoreticalPPM: theoreticalPpmDisplay.textContent, // Store the actual text content + currentStep: document.getElementById('current-step').textContent, + currentPPM: document.getElementById('current-ppm').textContent + }; + + // Update modal title + modalTitle.textContent = `编辑-${initialSettings.name || '一般机构'}`; + + settingsModal.style.display = 'flex'; + calculateMetrics(); // Ensure calculations are up-to-date when opening + }; + + // Close Settings Modal + const closeModal = () => { + settingsModal.style.display = 'none'; + }; + + // Revert settings to initial state (on cancel or 'X' click) + const revertSettings = () => { + clearValidationErrors(); // Clear validation errors on revert/cancel + machineNameInput.value = initialSettings.name; + batchQuantityInput.value = initialSettings.batchQuantity; + hasCacheCheckbox.checked = initialSettings.hasCache; + cacheQuantityInput.value = initialSettings.cacheQuantity; + toggleCacheInput(); // This also handles required attribute + + // Rebuild steps from initial data + stepsContainer.innerHTML = ''; + steps = []; + initialSettings.stepsData.forEach(stepData => addStep(stepData)); + + // Revert main display state using the helper function for status + machineNameDisplay.textContent = initialSettings.name; + theoreticalPpmDisplay.textContent = initialSettings.theoreticalPPM; // Use stored text + updateMachineStatus(initialSettings.statusText); // This updates text AND indicator class + document.getElementById('current-step').textContent = initialSettings.currentStep; + document.getElementById('current-ppm').textContent = initialSettings.currentPPM; + + closeModal(); + }; + + // Save Settings + const saveSettings = () => { + if (!validateSettings()) { + console.log("Validation failed."); // Debug log + // Optionally show a general error message at the top/bottom? + // alert("请检查表单中的错误并修正。"); + return; // Stop saving if validation fails + } + + console.log("Validation passed."); // Debug log + + // Validation passed, proceed with saving + const newName = machineNameInput.value.trim(); + const batchQty = parseInt(batchQuantityInput.value); // Already validated as integer + + machineNameDisplay.textContent = newName; + calculateMetrics(); // Recalculate with potentially changed batch qty + theoreticalPpmDisplay.textContent = calculatedPpmDisplay.textContent + 'PPM'; + + // Update status based on batch quantity + if (batchQty === 0) { + updateMachineStatus('禁用中'); + } else { + // Set to '运行中' or potentially another state based on future logic + // For now, assume it goes to '运行中' if not disabled + updateMachineStatus('运行中'); + } + + // Update current step/ppm (example) - might need real logic later + document.getElementById('current-step').textContent = steps.length > 0 ? steps[0].nameInput.value : '无步骤'; + document.getElementById('current-ppm').textContent = '0.00PPM'; // Reset or calculate actual current + + closeModal(); + }; + + // --- Event Listeners --- + machineComponent.addEventListener('dblclick', openModal); + closeModalBtn.addEventListener('click', revertSettings); + cancelSettingsBtn.addEventListener('click', revertSettings); + saveSettingsBtn.addEventListener('click', saveSettings); + addStepBtn.addEventListener('click', () => addStep()); + hasCacheCheckbox.addEventListener('change', toggleCacheInput); + + // Add listeners to clear errors on input for main fields + machineNameInput.addEventListener('input', clearErrorOnInput); + batchQuantityInput.addEventListener('input', clearErrorOnInput); + cacheQuantityInput.addEventListener('input', clearErrorOnInput); + + // --- Initialization --- + const initialize = () => { + // Add default steps as per the image + addStep({ name: '步骤1', startTime: 0, workTime: 3 }); + addStep({ name: '步骤2', startTime: 2, workTime: 3 }); + + // Set initial values based on the image (or defaults) + machineNameInput.value = '一般机构'; + batchQuantityInput.value = 1; + hasCacheCheckbox.checked = true; // From image + cacheQuantityInput.value = 3; // From image + toggleCacheInput(); // Enable/disable and set required + + // Initial calculation and display update + machineNameDisplay.textContent = machineNameInput.value; + calculateMetrics(); + theoreticalPpmDisplay.textContent = calculatedPpmDisplay.textContent + 'PPM'; + + // Set default component state (can be customized) + document.getElementById('current-step').textContent = '步骤1'; // Example + document.getElementById('current-ppm').textContent = '0.00PPM'; // Example + updateMachineStatus('等待中'); // Use helper to set initial status + + // Store initial theoretical PPM text correctly for revert + if (!initialSettings.theoreticalPPM) { // Ensure it's set only once initially + initialSettings.theoreticalPPM = theoreticalPpmDisplay.textContent; + } + // Clear any potential initial validation states on load + clearValidationErrors(); + }; + + initialize(); +}); \ No newline at end of file diff --git a/002_练手例程/一般机构组件/style.css b/002_练手例程/一般机构组件/style.css new file mode 100644 index 0000000..1cd5aff --- /dev/null +++ b/002_练手例程/一般机构组件/style.css @@ -0,0 +1,679 @@ +/* 全局和页面基础样式 */ +body { + font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; + background-color: #f4f7f6; /* 页面背景色 */ + display: flex; + justify-content: center; /* 水平居中 */ + align-items: center; /* 垂直居中 */ + min-height: 100vh; + margin: 0; +} + +/* --- 主组件显示区域样式 --- */ +.machine-component { + background-color: #ffffff; /* 组件背景色 */ + border-radius: 12px; /* 圆角 */ + box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08); /* 阴影 */ + padding: 15px; /* Adjusted padding */ + max-width: 350px; /* Max width on larger screens */ + width: 90%; /* Relative width on smaller screens */ + margin: 10px; /* Add some margin */ + cursor: pointer; /* 鼠标样式 */ + transition: box-shadow 0.3s ease; /* 阴影过渡效果 */ + border: 1px solid #e0e0e0; /* 边框 */ +} + +.machine-component:hover { + box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12); /* 鼠标悬浮时阴影加强 */ +} + +/* 主组件头部 */ +.header { + display: flex; + justify-content: space-between; /* 两端对齐 */ + align-items: center; /* 垂直居中 */ + margin-bottom: 15px; + padding-bottom: 10px; + border-bottom: 1px solid #eee; /* 底部边框分割线 */ +} + +/* 主组件 - 机构名称 */ +#machine-name-display { + font-size: 1.2em; + font-weight: 600; + color: #333; +} + +/* 主组件 - 状态指示灯 */ +.status-indicator { + width: 12px; + height: 12px; + border-radius: 50%; /* 圆形 */ + background-color: #ffc107; /* Default Yellow for waiting */ + transition: background-color 0.3s ease; /* Keep transition for color change */ + /* Apply default yellow pulse animation */ + animation: pulse-yellow 1.5s infinite; +} + +/* Active state overrides */ +.status-indicator.active { + background-color: #4CAF50; /* Green when active */ + animation-name: pulse-green; /* Change animation name */ +} + +/* Disabled state overrides */ +.status-indicator.disabled { + background-color: #dc3545; /* Red when disabled */ + animation-name: pulse-red; /* Use red pulse */ +} + +/* Define the GREEN pulse animation */ +@keyframes pulse-green { + 0% { + box-shadow: 0 0 0 0 rgba(76, 175, 80, 0.5); /* Green shadow */ + } + 70% { + box-shadow: 0 0 0 8px rgba(76, 175, 80, 0); + } + 100% { + box-shadow: 0 0 0 0 rgba(76, 175, 80, 0); + } +} + +/* Define the YELLOW pulse animation */ +@keyframes pulse-yellow { + 0% { + box-shadow: 0 0 0 0 rgba(255, 193, 7, 0.5); /* Yellow shadow */ + } + 70% { + box-shadow: 0 0 0 8px rgba(255, 193, 7, 0); + } + 100% { + box-shadow: 0 0 0 0 rgba(255, 193, 7, 0); + } +} + +/* Define the RED pulse animation */ +@keyframes pulse-red { + 0% { + box-shadow: 0 0 0 0 rgba(220, 53, 69, 0.5); /* Red shadow */ + } + 70% { + box-shadow: 0 0 0 8px rgba(220, 53, 69, 0); + } + 100% { + box-shadow: 0 0 0 0 rgba(220, 53, 69, 0); + } +} + +/* 主组件 - 信息网格布局 */ +.info-grid { + display: grid; + grid-template-columns: auto 1fr; /* 标签自适应,值占满剩余空间 */ + gap: 8px 15px; /* 行间距 列间距 */ + margin-bottom: 15px; + font-size: 0.95em; +} + +/* 主组件 - 信息标签 */ +.info-label { + color: #555; + font-weight: 500; + text-align: right; /* 文本右对齐 */ +} + +/* 主组件 - 信息值 */ +.info-value { + color: #333; + font-weight: 600; +} + +/* 主组件 - 底部状态文本 */ +.status-text { + text-align: center; + font-weight: 500; + color: #666; + padding-top: 10px; + border-top: 1px solid #eee; /* 顶部边框分割线 */ + font-size: 0.9em; +} + +/* --- 设置弹窗 (Modal) 样式 --- */ + +/* 弹窗遮罩层 */ +.modal-overlay { + position: fixed; /* 固定定位,覆盖全屏 */ + top: 0; + left: 0; + width: 100%; + height: 100%; + background-color: rgba(0, 0, 0, 0.5); /* 半透明黑色背景 */ + display: flex; + justify-content: center; /* 水平居中弹窗内容 */ + align-items: center; /* 垂直居中弹窗内容 */ + z-index: 1000; /* 置于顶层 */ +} + +/* 弹窗内容区域 */ +.modal-content { + background-color: #fff; + border-radius: 10px; /* 圆角 */ + box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2); + max-width: 600px; /* Max width on larger screens */ + width: 90vw; /* Relative width */ + max-height: 90vh; /* 最大高度为视窗的90% */ + display: flex; /* Use flexbox for layout */ + flex-direction: column; /* Stack header, scroll, footer vertically */ + overflow: hidden; /* Re-add overflow hidden to clip children and enforce height */ +} + +/* Remove scrollbar styles from .modal-content */ +/* +.modal-content::-webkit-scrollbar { ... } +.modal-content::-webkit-scrollbar-track { ... } +.modal-content::-webkit-scrollbar-thumb { ... } +.modal-content::-webkit-scrollbar-thumb:hover { ... } +*/ + +/* Fixed Header Section */ +.modal-fixed-header { + padding: 20px 25px 0 25px; /* Padding T, R/L, B */ + border-bottom: 1px solid #eee; /* Separator */ +} + +.steps-legend { + /* Styles for the moved legend */ + font-weight: 600; + color: #333; + padding: 10px 0 5px 0; /* Adjust padding */ + margin: 0; /* Remove default legend margin */ + font-size: 1.1em; /* Match step-title size */ +} + + +/* Scrollable Steps Area */ +.modal-scrollable-steps { + flex-grow: 1; /* Allow this section to take available vertical space */ + overflow-y: auto; /* Enable vertical scrolling ONLY for this section */ + padding: 15px 25px; /* Padding inside the scrollable area */ + /* Apply custom scrollbar styles HERE */ + scrollbar-width: thin; /* Firefox */ + scrollbar-color: #ccc #f4f4f4; /* Firefox */ +} + +.modal-scrollable-steps::-webkit-scrollbar { + width: 8px; +} + +.modal-scrollable-steps::-webkit-scrollbar-track { + background: #f4f4f4; + border-radius: 10px; + margin: 5px 0; /* Add slight margin */ +} + +.modal-scrollable-steps::-webkit-scrollbar-thumb { + background-color: #ccc; + border-radius: 10px; + border: 2px solid #f4f4f4; +} + +.modal-scrollable-steps::-webkit-scrollbar-thumb:hover { + background-color: #aaa; +} + +/* Fixed Footer Section */ +.modal-fixed-footer { + padding: 10px 25px 20px 25px; /* Padding T, R/L, B */ + border-top: 1px solid #eee; /* Separator */ + background-color: #fff; /* Ensure solid background */ +} + +/* Adjustments for items moved to footer */ +.modal-fixed-footer .add-btn { + margin-top: 10px; /* Adjust top margin */ + margin-bottom: 15px; /* Add bottom margin */ +} + +.modal-fixed-footer .cache-group { + margin-bottom: 15px; /* Add consistent margin */ +} + +.modal-fixed-footer .summary-section { + margin-top: 15px; /* Adjust top margin */ + padding-top: 0; /* Remove padding as border is above */ + border-top: none; /* Remove border as it's on footer now */ +} + +.modal-fixed-footer .modal-footer { + margin-top: 15px; /* Adjust top margin */ + padding-top: 0; /* Remove padding as border is above */ + border-top: none; /* Remove border as it's on footer now */ +} + + +/* Remove original steps-config styling */ +/* +.steps-config { ... } +.steps-config legend { ... } +*/ + +/* 弹窗头部 */ +.modal-header { + display: flex; + justify-content: space-between; + align-items: center; + border-bottom: 1px solid #eee; + padding-bottom: 15px; + margin-bottom: 20px; +} + +/* 弹窗标题 */ +#modal-title { + font-size: 1.4em; + font-weight: 600; + color: #333; +} + +/* 弹窗关闭按钮 */ +.close-btn { + background: none; + border: none; + font-size: 1.8em; + cursor: pointer; + color: #888; +} + +.close-btn:hover { + color: #333; +} + +/* 弹窗主体内容区域 */ +.modal-body { + margin-bottom: 20px; +} + +/* 通用表单组样式 */ +.form-group { + margin-bottom: 15px; + display: grid; + grid-template-columns: 120px 1fr; /* 标签固定宽度,输入框占满剩余 - Default */ + align-items: center; + gap: 5px 10px; /* Reduced gap slightly */ +} + +/* 表单标签 */ +.form-group label { + font-weight: 500; + color: #555; + text-align: right; +} + +/* 表单输入框 (文本和数字) */ +.form-group input[type="text"], +.form-group input[type="number"] { + padding: 8px 12px; + border: 1px solid #ccc; + border-radius: 6px; + font-size: 0.95em; + transition: border-color 0.3s ease; +} + +/* 输入框获取焦点时样式 */ +.form-group input[type="text"]:focus, +.form-group input[type="number"]:focus { + border-color: #007bff; /* 边框变蓝 */ + outline: none; /* 移除默认轮廓 */ +} + +/* 禁用的数字输入框 */ +.form-group input[type="number"][disabled] { + background-color: #e9ecef; + cursor: not-allowed; +} + +/* --- 步骤设置区域 --- */ +.steps-config { + border: 1px solid #ddd; /* 边框 */ + border-radius: 8px; /* 圆角 */ + padding: 15px; + margin-bottom: 20px; +} + +/* 步骤设置区域标题 */ +.steps-config legend { + font-weight: 600; + color: #333; + padding: 0 10px; +} + +/* 单个步骤项 */ +.step-item { + border: 1px dashed #ccc; /* 虚线边框 */ + border-radius: 6px; + padding: 15px; + margin-bottom: 15px; + position: relative; + background-color: #f9f9f9; +} + +/* 步骤项头部 */ +.step-header { + display: flex; + justify-content: space-between; + align-items: center; + margin-bottom: 10px; +} + +/* 步骤标题 (如: 步骤 1) */ +.step-title { + font-weight: bold; + font-size: 1.1em; +} + +/* 步骤控制按钮组 (上移/下移/删除) */ +.step-controls { + display: flex; + gap: 5px; +} + +/* 步骤控制按钮通用样式 */ +.step-btn { + background: none; + border: none; + cursor: pointer; + font-size: 1.2em; + color: #888; +} +.step-btn:hover { color: #333; } +/* 删除按钮特定颜色 */ +.delete-step-btn { color: #dc3545; } +.delete-step-btn:hover { color: #a71d2a; } + +/* 步骤内部输入框布局 */ +.step-inputs { + display: grid; + grid-template-columns: auto 1fr 1fr; /* 名称自适应,时间占剩余空间 - Default */ + gap: 10px; + align-items: start; /* 顶部对齐 */ +} + +/* 步骤内表单组 */ +.step-inputs .form-group { + grid-template-columns: 1fr; /* 内部标签和输入框垂直排列 */ + margin-bottom: 0; + gap: 3px; +} +/* 步骤内标签样式 */ +.step-inputs label { + text-align: left; + font-size: 0.85em; + margin-bottom: 2px; + color: #666; + display: block; /* 确保独占一行 */ + white-space: nowrap; /* 防止标签换行 */ + overflow: hidden; /* 隐藏超出部分 */ + text-overflow: ellipsis; /* 超出部分显示省略号 */ + max-width: 100%; /* 防止标签撑开布局 */ +} + +/* 限制步骤内时间输入框的最大宽度 */ +.step-inputs .form-group:nth-child(2) input[type="number"], +.step-inputs .form-group:nth-child(3) input[type="number"] { + max-width: 85px; /* 最大宽度限制 */ + width: 100%; /* 允许在容器缩小时也缩小 */ +} + +/* 确保步骤内名称输入框填满其列 */ +.step-inputs .form-group:nth-child(1) input[type="text"] { + width: 85%; +} + +/* --- 其他设置和按钮 --- */ + +/* 添加步骤按钮 */ +.add-btn { + padding: 8px 15px; + background-color: #28a745; + color: white; + border: none; + border-radius: 8px; + cursor: pointer; + font-size: 0.95em; + transition: background-color 0.3s ease; + margin-top: 15px; + /* 居中显示 */ + display: block; + width: fit-content; /* 宽度自适应内容 */ + margin-left: auto; + margin-right: auto; +} + +.add-btn:hover { + background-color: #218838; +} + +/* 缓存设置组 */ +.cache-group { + display: grid; /* Use grid for better control with errors */ + grid-template-columns: auto auto 1fr; /* checkbox, label, input - Default */ + align-items: center; + gap: 10px; +} + +/* 缓存复选框 */ +.cache-group input[type="checkbox"] { grid-row: 1; } +.cache-group label[for="has-cache-checkbox"] { grid-row: 1; text-align: left; } +.cache-group input[type="number"] { grid-row: 1; } +.cache-group .error-message { + grid-column: 3; /* Error below the number input */ + grid-row: 2; + margin-top: 2px; +} + +/* 汇总信息区域 */ +.summary-section { + margin-top: 20px; + padding-top: 15px; + border-top: 1px solid #eee; + display: flex; + justify-content: space-around; /* 两端分散对齐 */ + font-size: 0.95em; + color: #555; +} + +/* 汇总信息中的数值 */ +.summary-section span span { + font-weight: 600; + color: #333; +} + +/* 弹窗底部按钮区域 */ +.modal-footer { + display: flex; + justify-content: flex-end; /* 按钮靠右对齐 */ + gap: 10px; + padding-top: 15px; + border-top: 1px solid #eee; + margin-top: 20px; +} + +/* 保存和取消按钮通用样式 */ +.save-btn, +.cancel-btn { + padding: 10px 20px; + border: none; + border-radius: 6px; + cursor: pointer; + font-size: 1em; + transition: background-color 0.3s ease, color 0.3s ease; +} + +/* 保存按钮 */ +.save-btn { + background-color: #007bff; + color: white; +} + +.save-btn:hover { + background-color: #0056b3; +} + +/* 取消按钮 */ +.cancel-btn { + background-color: #f8f9fa; + color: #333; + border: 1px solid #ccc; +} + +.cancel-btn:hover { + background-color: #e2e6ea; +} + +/* --- 工具类样式 --- */ + +/* 错误消息 (未使用,可备用) */ +.error-message { + color: #dc3545; + font-size: 0.85em; /* Slightly larger */ + padding-left: 0; /* Remove padding */ + display: none; /* Hidden by default */ + margin-top: 2px; /* Add small top margin */ +} + +/* Ensure error message appears below input in standard form groups */ +.form-group .error-message { + grid-column: 2; /* Align with input */ + grid-row: 2; /* Place on the row below the input */ + text-align: left; +} + +/* Error messages within steps */ +.step-inputs .error-message { + /* display: block; */ /* Already block by default */ + width: 100%; /* Take full width */ + margin-top: 2px; + text-align: left; +} + +/* Adjust cache group alignment when error shows */ +.cache-group { + display: grid; /* Use grid for better control with errors */ + grid-template-columns: auto auto 1fr; /* checkbox, label, input */ + align-items: center; + gap: 10px; +} +.cache-group input[type="checkbox"] { grid-row: 1; } +.cache-group label[for="has-cache-checkbox"] { grid-row: 1; text-align: left; } +.cache-group input[type="number"] { grid-row: 1; } +.cache-group .error-message { + grid-column: 3; /* Error below the number input */ + grid-row: 2; + margin-top: 2px; +} + +/* 步骤项移动时的视觉反馈 */ +.step-item.moving { + transition: background-color 0.3s ease-out; + background-color: #e6f7ff; /* 淡蓝色高亮 */ +} + +/* Input Validation Styles */ +input:invalid, +textarea:invalid { + border-color: #dc3545; /* Red border for invalid fields */ +} + +.form-group input.invalid, +.step-item input.invalid { + border-color: #dc3545 !important; /* Force red border */ + background-color: #fff3f3; /* Light red background */ +} + +.error-tooltip { + color: #dc3545; + font-size: 0.8em; + padding-left: 5px; + display: none; /* Hidden by default */ +} + +.form-group .error-tooltip { + grid-column: 2; /* Align with input in main form groups */ +} + +/* --- Responsive Adjustments --- */ + +@media (max-width: 600px) { + + /* Reduce padding/font size slightly globally in modal? Optional */ + .modal-content { + width: 95vw; /* Use more width on mobile */ + max-height: 95vh; /* Allow slightly more height */ + } + + .modal-fixed-header, + .modal-scrollable-steps, + .modal-fixed-footer { + padding: 15px; /* Consistent padding */ + } + + /* Stack form groups vertically */ + .form-group { + grid-template-columns: 1fr; /* Single column */ + gap: 5px; /* Reduce gap */ + } + + .form-group label { + text-align: left; /* Align labels left */ + margin-bottom: 2px; + } + + /* Ensure error messages span full width below input */ + .form-group .error-message { + grid-column: 1; /* Span full column */ + grid-row: 3; /* Ensure it's below label and input */ + } + + /* Stack step inputs vertically */ + .step-inputs { + grid-template-columns: 1fr; /* Single column */ + gap: 10px; + } + + /* Allow time inputs to take more width when stacked */ + .step-inputs .form-group:nth-child(2) input[type="number"], + .step-inputs .form-group:nth-child(3) input[type="number"] { + max-width: none; /* Remove max-width limit */ + } + + /* Stack cache group elements */ + .cache-group { + grid-template-columns: auto 1fr; /* Checkbox | Label & Input */ + gap: 5px 10px; + } + .cache-group input[type="checkbox"] { grid-row: 1; grid-column: 1; } + .cache-group label[for="has-cache-checkbox"] { grid-row: 1; grid-column: 2; } + .cache-group input[type="number"] { grid-row: 2; grid-column: 1 / span 2; width: 100%;} /* Input below */ + .cache-group .error-message { + grid-row: 3; /* Error below input */ + grid-column: 1 / span 2; + } + + /* Stack summary section */ + .summary-section { + flex-direction: column; /* Stack items */ + align-items: center; /* Center align */ + gap: 5px; + } + + /* Adjust footer buttons */ + .modal-footer { + justify-content: space-around; /* Space out buttons more */ + } + + .save-btn, + .cancel-btn { + padding: 8px 15px; /* Slightly smaller buttons */ + font-size: 0.95em; + } + +} \ No newline at end of file diff --git a/002_练手例程/时序仿真/README.md b/002_练手例程/时序仿真/README.md new file mode 100644 index 0000000..916ac79 --- /dev/null +++ b/002_练手例程/时序仿真/README.md @@ -0,0 +1,15 @@ +# README + +1. 组件库 + +| / | 前段设备 | 常规机构 | 缓存机构 | 集装夹具 | 运输机构 | 仓储机构 | 后段设备 | +|:--------:|----------------------------------------|----------------------------------------------------|---------------------|------|------|------|------| +| 组件形状 | 椭圆形 | 圆角矩形 | 圆角矩形 | 圆角矩形 | 菱形 | 图表 | 椭圆形 | +| 组件外框颜色 | 蓝色 | 绿色 | 黄色 | 橙色 | 青色 | 黑色 | 红色 | +| 组件内文字示例 | 组件名称:前段设备1 投入总数:100 不良品数:2 当前状态:等待后续机构 | 组件名称:常规机构1 当前状态:工作中 当前步骤:步骤1 理论产能:60PPM 实时产能:50PPM | 组件名称:缓存机构1 当前状态:工作中 | | | | | +| 双击设置项 | | | | | | | | +| 功能 | | | | | | | | +| 组件时序计算逻辑 | | | | | | | | +| 流程中仿真逻辑 | | | | | | | | +| 连接点 | | | | | | | | +| 其他 | | | | | | | | diff --git a/002_练手例程/时序仿真/index.html b/002_练手例程/时序仿真/index.html new file mode 100644 index 0000000..c320a6d --- /dev/null +++ b/002_练手例程/时序仿真/index.html @@ -0,0 +1,178 @@ + + + + + + 流程图仿真工具 + + + +
+ + +
+
+ +
+ +
+
就绪
+
+ + 100% + +
+
+
+
+ + + + + + + + + + + + + diff --git a/002_练手例程/时序仿真/script.js b/002_练手例程/时序仿真/script.js new file mode 100644 index 0000000..8be1f74 --- /dev/null +++ b/002_练手例程/时序仿真/script.js @@ -0,0 +1,2653 @@ +// 流程图仿真工具脚本 +document.addEventListener('DOMContentLoaded', function() { + // 全局变量 + const canvas = document.getElementById('flow-canvas'); + const ctx = canvas.getContext('2d'); + let shapes = []; + let connections = []; + let selectedShape = null; + let draggedShape = null; + let dragOffset = { x: 0, y: 0 }; + let isDragging = false; + let isPanning = false; + let lastMousePos = { x: 0, y: 0 }; + let zoomLevel = 1; + let panOffset = { x: 0, y: 0 }; + let isConnecting = false; + let connectingFrom = null; + let connectingToPoint = { x: 0, y: 0 }; + let simulationRunning = false; + let simulationInterval = null; + let simulationTime = 0; // 仿真时间(分钟) + let simulationSpeed = 1; // 仿真速度倍率 + let particles = []; // 用于动画的粒子 + let nextShapeId = 1; + let nextConnectionId = 1; + let hoveredConnectionPoint = null; + let selectedConnection = null; + + // 常量 + const SHAPE_TYPES = { + START: 'start', + PROCESS: 'process', + TRANSPORT: 'transport', + ENDPOINT: 'endpoint' + }; + + const SHAPE_SIZES = { + [SHAPE_TYPES.START]: { width: 160, height: 80 }, + [SHAPE_TYPES.PROCESS]: { width: 160, height: 80 }, + [SHAPE_TYPES.TRANSPORT]: { width: 140, height: 80 }, + [SHAPE_TYPES.ENDPOINT]: { width: 160, height: 80 } + }; + + const SHAPE_COLORS = { + [SHAPE_TYPES.START]: '#ff0000', + [SHAPE_TYPES.PROCESS]: '#4CAF50', + [SHAPE_TYPES.TRANSPORT]: '#FF9800', + [SHAPE_TYPES.ENDPOINT]: '#9C27B0' + }; + + const SHAPE_STATUS = { + IDLE: '等待上一步', + WORKING: '工作中', + WAITING: '等待下一步' + }; + + const GRID_SIZE = 20; + const SIMULATION_TICK = 0.1; // 仿真时间步长(分钟) + + // 初始化 + initCanvas(); + setupEventListeners(); + updateCanvasSize(); + updateStatus('就绪'); + + // 初始化画布 + function initCanvas() { + updateCanvasSize(); + window.addEventListener('resize', updateCanvasSize); + } + + // 更新画布大小 + function updateCanvasSize() { + const container = canvas.parentElement; + canvas.width = container.clientWidth; + canvas.height = container.clientHeight; + drawCanvas(); + } + + // 设置事件监听器 + function setupEventListeners() { + // 画布事件 + canvas.addEventListener('mousedown', handleCanvasMouseDown); + canvas.addEventListener('mousemove', handleCanvasMouseMove); + canvas.addEventListener('mouseup', handleCanvasMouseUp); + canvas.addEventListener('dblclick', handleCanvasDblClick); + canvas.addEventListener('wheel', handleCanvasWheel); + + // 拖拽图形事件 + setupDragAndDrop(); + + // 按钮事件 + document.getElementById('start-simulation').addEventListener('click', startSimulation); + document.getElementById('stop-simulation').addEventListener('click', stopSimulation); + document.getElementById('reset-simulation').addEventListener('click', resetSimulation); + document.getElementById('save-project').addEventListener('click', showSaveProjectDialog); + document.getElementById('load-project').addEventListener('click', showLoadProjectDialog); + document.getElementById('zoom-in').addEventListener('click', zoomIn); + document.getElementById('zoom-out').addEventListener('click', zoomOut); + + // 添加步骤按钮事件 + document.getElementById('add-step').addEventListener('click', function() { + const stepsContainer = document.getElementById('steps-container'); + const stepItems = stepsContainer.querySelectorAll('.step-item'); + const newIndex = stepItems.length; + + // 创建新步骤 + const newStep = { + name: `步骤${newIndex + 1}`, + startTime: 0, + workTime: 1.0 + }; + + // 添加到UI + addStepToUI(newStep, newIndex); + + // 更新总耗时 + updateTotalTime(); + }); + + // 模态框关闭按钮 + document.querySelectorAll('.close').forEach(btn => { + btn.addEventListener('click', function() { + this.closest('.modal').style.display = 'none'; + }); + }); + + // 模态框表单提交事件 + document.getElementById('shape-form').addEventListener('submit', function(e) { + e.preventDefault(); + saveShapeData(); + }); + + document.getElementById('connection-form').addEventListener('submit', function(e) { + e.preventDefault(); + saveConnectionData(); + }); + + document.getElementById('file-form').addEventListener('submit', function(e) { + e.preventDefault(); + handleFileSubmit(); + }); + + // 取消按钮事件 + document.getElementById('cancel-edit').addEventListener('click', function() { + document.getElementById('shape-modal').style.display = 'none'; + }); + + document.getElementById('cancel-connection-edit').addEventListener('click', function() { + document.getElementById('connection-modal').style.display = 'none'; + }); + + document.getElementById('cancel-file-action').addEventListener('click', function() { + document.getElementById('file-modal').style.display = 'none'; + }); + + // 删除连接按钮 + document.getElementById('delete-connection').addEventListener('click', deleteSelectedConnection); + } + + // 设置拖拽功能 + function setupDragAndDrop() { + const shapeItems = document.querySelectorAll('.shape-item'); + + shapeItems.forEach(item => { + item.addEventListener('dragstart', function(e) { + e.dataTransfer.setData('shape-type', this.getAttribute('data-shape-type')); + e.dataTransfer.effectAllowed = 'copy'; + }); + }); + + canvas.addEventListener('dragover', function(e) { + e.preventDefault(); + e.dataTransfer.dropEffect = 'copy'; + }); + + canvas.addEventListener('drop', function(e) { + e.preventDefault(); + const shapeType = e.dataTransfer.getData('shape-type'); + if (shapeType) { + const rect = canvas.getBoundingClientRect(); + const x = (e.clientX - rect.left - panOffset.x) / zoomLevel; + const y = (e.clientY - rect.top - panOffset.y) / zoomLevel; + + createNewShape(shapeType, x, y); + } + }); + } + + // 处理画布鼠标按下事件 + function handleCanvasMouseDown(e) { + const mousePos = getMousePos(e); + + // 检查是否点击在连接点上 + hoveredConnectionPoint = getConnectionPointAt(mousePos.x, mousePos.y); + + if (hoveredConnectionPoint) { + // 开始连接操作 + isConnecting = true; + connectingFrom = hoveredConnectionPoint.shape; + connectingToPoint = mousePos; + return; + } + + // 检查是否点击在连接线上 + const clickedConnection = getConnectionAt(mousePos.x, mousePos.y); + if (clickedConnection) { + selectedConnection = clickedConnection; + selectedShape = null; + drawCanvas(); + return; + } + + // 检查是否点击在形状上 + const clickedShape = getShapeAt(mousePos.x, mousePos.y); + + if (clickedShape) { + // 选择并准备拖动形状 + selectedShape = clickedShape; + selectedConnection = null; + draggedShape = clickedShape; + isDragging = true; + dragOffset.x = mousePos.x - clickedShape.x; + dragOffset.y = mousePos.y - clickedShape.y; + } else { + // 点击在空白区域,取消选择并准备平移 + selectedShape = null; + selectedConnection = null; + isPanning = true; + lastMousePos = mousePos; + } + + drawCanvas(); + } + + // 处理画布鼠标移动事件 + function handleCanvasMouseMove(e) { + const mousePos = getMousePos(e); + + if (isConnecting) { + // 更新连接目标点 + connectingToPoint = mousePos; + drawCanvas(); + return; + } + + if (isDragging && draggedShape) { + // 移动形状 + draggedShape.x = snapToGrid(mousePos.x - dragOffset.x); + draggedShape.y = snapToGrid(mousePos.y - dragOffset.y); + drawCanvas(); + return; + } + + if (isPanning) { + // 平移画布 + panOffset.x += (mousePos.x - lastMousePos.x) * zoomLevel; + panOffset.y += (mousePos.y - lastMousePos.y) * zoomLevel; + lastMousePos = mousePos; + drawCanvas(); + return; + } + + // 检查鼠标是否悬停在连接点上 + const connectionPoint = getConnectionPointAt(mousePos.x, mousePos.y); + + if (connectionPoint) { + canvas.style.cursor = 'crosshair'; + hoveredConnectionPoint = connectionPoint; + } else { + // 检查是否悬停在形状上 + const hoverShape = getShapeAt(mousePos.x, mousePos.y); + canvas.style.cursor = hoverShape ? 'move' : 'default'; + hoveredConnectionPoint = null; + } + + drawCanvas(); + } + + // 处理画布鼠标松开事件 + function handleCanvasMouseUp(e) { + if (isConnecting) { + const mousePos = getMousePos(e); + const targetShape = getShapeAt(mousePos.x, mousePos.y); + + if (targetShape && targetShape !== connectingFrom) { + // 创建新连接 + createConnection(connectingFrom, targetShape); + } + + isConnecting = false; + connectingFrom = null; + } + + isDragging = false; + draggedShape = null; + isPanning = false; + + drawCanvas(); + } + + // 处理画布双击事件 + function handleCanvasDblClick(e) { + if (simulationRunning) return; + + const mousePos = getMousePos(e); + const clickedShape = getShapeAt(mousePos.x, mousePos.y); + + if (clickedShape) { + // 打开编辑对话框 + openShapeEditor(clickedShape); + } + } + + // 添加键盘事件监听删除功能 + window.addEventListener('keydown', function(e) { + if (e.key === 'Delete' && selectedShape && !simulationRunning) { + deleteSelectedShape(); + } + }); + + // 删除选定的形状 + function deleteSelectedShape() { + if (!selectedShape) return; + + // 删除所有与该形状相关的连接 + connections = connections.filter(conn => { + const isConnected = conn.fromId === selectedShape.id || conn.toId === selectedShape.id; + + if (isConnected) { + // 更新其他形状的输入输出 + shapes.forEach(shape => { + if (conn.fromId === selectedShape.id && conn.toId === shape.id) { + // 从目标形状的输入中移除 + shape.inputs = shape.inputs.filter(id => id !== selectedShape.id); + } + if (conn.toId === selectedShape.id && conn.fromId === shape.id) { + // 从源形状的输出中移除 + shape.outputs = shape.outputs.filter(id => id !== selectedShape.id); + } + }); + } + + return !isConnected; + }); + + // 删除形状 + shapes = shapes.filter(shape => shape.id !== selectedShape.id); + + // 重新计算产能 + calculateAllThroughputs(); + + // 更新状态 + selectedShape = null; + updateStatus('已删除形状'); + drawCanvas(); + } + + // 处理画布滚轮事件 + function handleCanvasWheel(e) { + e.preventDefault(); + + const mousePos = getMousePos(e); + const zoomFactor = e.deltaY < 0 ? 1.1 : 0.9; + + // 以鼠标位置为中心进行缩放 + zoomCanvas(zoomFactor, mousePos); + } + + // 获取鼠标在画布中的位置 + function getMousePos(e) { + const rect = canvas.getBoundingClientRect(); + return { + x: (e.clientX - rect.left - panOffset.x) / zoomLevel, + y: (e.clientY - rect.top - panOffset.y) / zoomLevel + }; + } + + // 缩放画布 + function zoomCanvas(factor, center) { + const oldZoom = zoomLevel; + zoomLevel *= factor; + + // 限制缩放范围 + zoomLevel = Math.max(0.2, Math.min(zoomLevel, 5)); + + if (center) { + // 调整偏移量,使缩放以鼠标位置为中心 + panOffset.x = center.x * zoomLevel - center.x * oldZoom + panOffset.x; + panOffset.y = center.y * zoomLevel - center.y * oldZoom + panOffset.y; + } + + // 更新缩放显示 + document.getElementById('zoom-level').textContent = Math.round(zoomLevel * 100) + '%'; + + drawCanvas(); + } + + // 放大 + function zoomIn() { + const center = { + x: canvas.width / 2, + y: canvas.height / 2 + }; + zoomCanvas(1.1, center); + } + + // 缩小 + function zoomOut() { + const center = { + x: canvas.width / 2, + y: canvas.height / 2 + }; + zoomCanvas(0.9, center); + } + + // 创建新形状 + function createNewShape(shapeType, x, y) { + const size = SHAPE_SIZES[shapeType]; + + // 创建新形状对象 + const newShape = { + id: nextShapeId++, + type: shapeType, + x: snapToGrid(x - size.width / 2), + y: snapToGrid(y - size.height / 2), + width: size.width, + height: size.height, + name: getDefaultShapeName(shapeType), + params: getDefaultParams(shapeType), + inputs: [], + outputs: [], + calculatedThroughput: 0, + processedItems: 0, + buffer: 0, + status: SHAPE_STATUS.IDLE, + realTimeThroughput: 0, // 实时产能 + lastProcessTime: 0, // 上次处理时间 + waitingForNext: false, // 是否等待下一步 + waitingForPrevious: true // 是否等待上一步 + }; + + shapes.push(newShape); + selectedShape = newShape; + + // 打开形状编辑对话框 + openShapeEditor(newShape); + + drawCanvas(); + return newShape; + } + + // 获取默认形状名称 + function getDefaultShapeName(shapeType) { + switch(shapeType) { + case SHAPE_TYPES.START: + return '开始 ' + nextShapeId; + case SHAPE_TYPES.PROCESS: + return '普通机构 ' + nextShapeId; + case SHAPE_TYPES.TRANSPORT: + return '运输机构 ' + nextShapeId; + case SHAPE_TYPES.ENDPOINT: + return '收料机构 ' + nextShapeId; + default: + return '未命名 ' + nextShapeId; + } + } + + // 获取默认参数 + function getDefaultParams(shapeType) { + switch(shapeType) { + case SHAPE_TYPES.START: + return { + outputRate: 5.0 // 每分钟产出数量 + }; + case SHAPE_TYPES.PROCESS: + return { + batchSize: 1, + steps: [ + { + name: "步骤1", + startTime: 0, + workTime: 1.0 + } + ] + }; + case SHAPE_TYPES.TRANSPORT: + return { + transportTime: 2.0, + transportBatch: 1, + transportCount: 1 + }; + case SHAPE_TYPES.ENDPOINT: + return { + collectionCapacity: 100 + }; + default: + return {}; + } + } + + // 打开形状编辑对话框 + function openShapeEditor(shape) { + const modal = document.getElementById('shape-modal'); + const titleElement = document.getElementById('modal-title'); + const nameInput = document.getElementById('shape-name'); + const processParams = document.getElementById('process-params'); + const transportParams = document.getElementById('transport-params'); + const endpointParams = document.getElementById('endpoint-params'); + + // 设置标题 + titleElement.textContent = '编辑' + getShapeTypeLabel(shape.type); + + // 设置名称 + nameInput.value = shape.name; + + // 隐藏所有参数区域 + processParams.style.display = 'none'; + transportParams.style.display = 'none'; + endpointParams.style.display = 'none'; + + // 根据形状类型显示对应参数 + switch(shape.type) { + case SHAPE_TYPES.PROCESS: + processParams.style.display = 'block'; + document.getElementById('batch-size').value = shape.params.batchSize; + + // 清空步骤容器 + const stepsContainer = document.getElementById('steps-container'); + stepsContainer.innerHTML = ''; + + // 添加现有步骤 + if (shape.params.steps && shape.params.steps.length > 0) { + shape.params.steps.forEach((step, index) => { + addStepToUI(step, index); + }); + } else { + // 如果没有步骤,添加一个默认步骤 + addStepToUI({name: "步骤1", startTime: 0, workTime: 1.0}, 0); + } + + // 计算并显示总耗时 + updateTotalTime(); + break; + + case SHAPE_TYPES.TRANSPORT: + transportParams.style.display = 'block'; + document.getElementById('transport-time').value = shape.params.transportTime; + document.getElementById('transport-batch').value = shape.params.transportBatch; + document.getElementById('transport-count').value = shape.params.transportCount; + break; + + case SHAPE_TYPES.ENDPOINT: + endpointParams.style.display = 'block'; + document.getElementById('collection-capacity').value = shape.params.collectionCapacity; + break; + } + + // 显示对话框 + modal.style.display = 'block'; + } + + // 获取形状类型标签 + function getShapeTypeLabel(type) { + switch(type) { + case SHAPE_TYPES.START: + return '开始'; + case SHAPE_TYPES.PROCESS: + return '普通机构'; + case SHAPE_TYPES.TRANSPORT: + return '运输机构'; + case SHAPE_TYPES.ENDPOINT: + return '收料机构'; + default: + return '未知类型'; + } + } + + // 添加步骤到UI + function addStepToUI(step, index) { + const stepsContainer = document.getElementById('steps-container'); + const stepItem = document.createElement('div'); + stepItem.className = 'step-item'; + stepItem.dataset.index = index; + + // 创建步骤内容 + stepItem.innerHTML = ` +
+
步骤 ${index + 1}
+ +
+
+
+ + +
+
+ + +
+
+ + +
+
+ `; + + stepsContainer.appendChild(stepItem); + + // 添加删除步骤事件 + const removeBtn = stepItem.querySelector('.step-remove'); + removeBtn.addEventListener('click', function() { + removeStep(parseInt(this.dataset.index)); + }); + + // 添加输入变化事件以更新总耗时 + const inputs = stepItem.querySelectorAll('input[type="number"]'); + inputs.forEach(input => { + input.addEventListener('input', updateTotalTime); + }); + } + + // 删除步骤 + function removeStep(index) { + const stepsContainer = document.getElementById('steps-container'); + const stepItems = stepsContainer.querySelectorAll('.step-item'); + + // 至少保留一个步骤 + if (stepItems.length <= 1) { + alert('至少需要保留一个步骤'); + return; + } + + // 删除指定步骤 + stepItems[index].remove(); + + // 重新编号步骤 + const remainingSteps = stepsContainer.querySelectorAll('.step-item'); + remainingSteps.forEach((item, i) => { + item.dataset.index = i; + item.querySelector('.step-title').textContent = `步骤 ${i + 1}`; + item.querySelector('.step-remove').dataset.index = i; + + // 更新输入框ID + const inputs = item.querySelectorAll('input'); + inputs[0].id = `step-name-${i}`; + inputs[1].id = `step-start-${i}`; + inputs[2].id = `step-work-${i}`; + }); + + // 更新总耗时 + updateTotalTime(); + } + + // 计算并更新总耗时 + function updateTotalTime() { + const stepsContainer = document.getElementById('steps-container'); + const stepItems = stepsContainer.querySelectorAll('.step-item'); + let maxEndTime = 0; + + stepItems.forEach((item, index) => { + const startTime = parseFloat(document.getElementById(`step-start-${index}`).value) || 0; + const workTime = parseFloat(document.getElementById(`step-work-${index}`).value) || 0; + const endTime = startTime + workTime; + + if (endTime > maxEndTime) { + maxEndTime = endTime; + } + }); + + document.getElementById('total-time').textContent = maxEndTime.toFixed(1); + } + + // 保存形状数据 + function saveShapeData() { + if (!selectedShape) return; + + // 获取基本信息 + selectedShape.name = document.getElementById('shape-name').value; + + // 根据形状类型获取特定参数 + switch(selectedShape.type) { + case SHAPE_TYPES.PROCESS: + selectedShape.params.batchSize = parseInt(document.getElementById('batch-size').value) || 1; + + // 获取所有步骤数据 + const stepsContainer = document.getElementById('steps-container'); + const stepItems = stepsContainer.querySelectorAll('.step-item'); + const steps = []; + + stepItems.forEach((item, index) => { + steps.push({ + name: document.getElementById(`step-name-${index}`).value, + startTime: parseFloat(document.getElementById(`step-start-${index}`).value) || 0, + workTime: parseFloat(document.getElementById(`step-work-${index}`).value) || 0.1 + }); + }); + + selectedShape.params.steps = steps; + break; + + case SHAPE_TYPES.TRANSPORT: + selectedShape.params.transportTime = parseFloat(document.getElementById('transport-time').value) || 2.0; + selectedShape.params.transportBatch = parseInt(document.getElementById('transport-batch').value) || 1; + selectedShape.params.transportCount = parseInt(document.getElementById('transport-count').value) || 1; + break; + + case SHAPE_TYPES.ENDPOINT: + selectedShape.params.collectionCapacity = parseInt(document.getElementById('collection-capacity').value) || 100; + break; + } + + // 计算产能 + calculateThroughput(selectedShape); + + // 关闭对话框 + document.getElementById('shape-modal').style.display = 'none'; + + // 重绘画布 + drawCanvas(); + } + + // 创建连接 + function createConnection(fromShape, toShape) { + // 检查是否已有相同的连接 + const existingConnection = connections.find(conn => + conn.fromId === fromShape.id && conn.toId === toShape.id); + + if (existingConnection) { + alert('连接已存在'); + return; + } + + // 创建新连接 + const connection = { + id: nextConnectionId++, + fromId: fromShape.id, + toId: toShape.id, + delay: 0, + startPosition: hoveredConnectionPoint ? hoveredConnectionPoint.position : 'right', + endPosition: 'left', // 默认连接到左侧 + particles: [], // 动态粒子 + controlPoints: [] // 用于贝塞尔曲线的控制点 + }; + + // 自动计算合适的控制点,使曲线更自然 + updateConnectionControlPoints(connection); + + // 更新形状的输入输出关系 + fromShape.outputs.push(toShape.id); + toShape.inputs.push(fromShape.id); + + connections.push(connection); + + // 重新计算所有产能 + calculateAllThroughputs(); + + // 重绘画布 + drawCanvas(); + } + + // 更新连接的控制点 + function updateConnectionControlPoints(connection) { + const fromShape = shapes.find(s => s.id === connection.fromId); + const toShape = shapes.find(s => s.id === connection.toId); + + if (!fromShape || !toShape) return; + + // 获取连接起点和终点 + const startPoint = getConnectionPointCoordinates(fromShape, connection.startPosition); + const endPoint = getConnectionPointCoordinates(toShape, connection.endPosition); + + // 计算两点间距离 + const dx = endPoint.x - startPoint.x; + const dy = endPoint.y - startPoint.y; + const distance = Math.sqrt(dx * dx + dy * dy); + + // 设置控制点,使曲线更自然 + const controlOffset = Math.min(distance * 0.4, 150); + + // 根据起点和终点位置设置控制点 + let cp1x, cp1y, cp2x, cp2y; + +// 从起点位置确定第一控制点方向 + const dir1 = getDirectionFromPosition(connection.startPosition); + cp1x = startPoint.x + dir1.x * controlOffset; + cp1y = startPoint.y + dir1.y * controlOffset; + + // 从终点位置确定第二控制点方向 + const dir2 = getDirectionFromPosition(connection.endPosition); + cp2x = endPoint.x + dir2.x * controlOffset; + cp2y = endPoint.y + dir2.y * controlOffset; + + connection.controlPoints = [ + { x: cp1x, y: cp1y }, + { x: cp2x, y: cp2y } + ]; + } + + // 根据位置获取方向向量 + function getDirectionFromPosition(position) { + switch(position) { + case 'left': return { x: -1, y: 0 }; + case 'right': return { x: 1, y: 0 }; + case 'top': return { x: 0, y: -1 }; + case 'bottom': return { x: 0, y: 1 }; + default: return { x: 1, y: 0 }; + } + } + + // 获取连接点坐标 + function getConnectionPointCoordinates(shape, position) { + switch(position) { + case 'left': + return { x: shape.x, y: shape.y + shape.height / 2 }; + case 'right': + return { x: shape.x + shape.width, y: shape.y + shape.height / 2 }; + case 'top': + return { x: shape.x + shape.width / 2, y: shape.y }; + case 'bottom': + return { x: shape.x + shape.width / 2, y: shape.y + shape.height }; + default: + return { x: shape.x + shape.width, y: shape.y + shape.height / 2 }; + } + } + + // 打开连接编辑对话框 + function openConnectionEditor(connection) { + const modal = document.getElementById('connection-modal'); + document.getElementById('connection-delay').value = connection.delay || 0; + + // 存储当前连接用于保存 + selectedConnection = connection; + + modal.style.display = 'block'; + } + + // 保存连接数据 + function saveConnectionData() { + if (!selectedConnection) return; + + // 获取参数 + selectedConnection.delay = parseFloat(document.getElementById('connection-delay').value) || 0; + + // 关闭对话框 + document.getElementById('connection-modal').style.display = 'none'; + + // 重绘画布 + drawCanvas(); + } + + // 删除选定的连接 + function deleteSelectedConnection() { + if (!selectedConnection) return; + + // 删除形状中的引用 + const fromShape = shapes.find(s => s.id === selectedConnection.fromId); + const toShape = shapes.find(s => s.id === selectedConnection.toId); + + if (fromShape) { + fromShape.outputs = fromShape.outputs.filter(id => id !== selectedConnection.toId); + } + + if (toShape) { + toShape.inputs = toShape.inputs.filter(id => id !== selectedConnection.fromId); + } + + // 删除连接 + connections = connections.filter(c => c.id !== selectedConnection.id); + + // 重新计算所有产能 + calculateAllThroughputs(); + + // 关闭对话框 + document.getElementById('connection-modal').style.display = 'none'; + + // 重绘画布 + drawCanvas(); + } + + // 计算单个节点的产能 + function calculateThroughput(shape) { + let throughput = 0; + + switch(shape.type) { + case SHAPE_TYPES.PROCESS: + // 计算周期时间(秒) + let maxEndTime = 0; + if (shape.params.steps && shape.params.steps.length > 0) { + shape.params.steps.forEach(step => { + const endTime = step.startTime + step.workTime; + if (endTime > maxEndTime) { + maxEndTime = endTime; + } + }); + } else { + // 兼容旧数据 + maxEndTime = (shape.params.actionSteps || 1) * (shape.params.stepTime || 1); + } + + // 转换为分钟产能 (PPM) + throughput = shape.params.batchSize * 60 / maxEndTime; + break; + + case SHAPE_TYPES.TRANSPORT: + // 计算总运输时间(秒) + const transportTime = shape.params.transportTime * shape.params.transportCount; + // 转换为分钟产能 (PPM) + throughput = shape.params.transportBatch * 60 / transportTime; + break; + + case SHAPE_TYPES.ENDPOINT: + // 终端节点产能由输入决定 + throughput = 0; // 将在拓扑排序后计算 + break; + } + + shape.calculatedThroughput = throughput; + return throughput; + } + + // 计算整个流程的产能 + function calculateAllThroughputs() { + // 对节点进行拓扑排序 + let visited = new Set(); + let sortedShapes = []; + + // 深度优先搜索函数 + function dfs(shape) { + if (visited.has(shape.id)) return; + visited.add(shape.id); + + // 先处理所有输入节点 + shape.inputs.forEach(inputId => { + const inputShape = shapes.find(s => s.id === inputId); + if (inputShape) dfs(inputShape); + }); + + sortedShapes.push(shape); + } + + // 从终端节点开始反向搜索 + shapes.filter(s => s.type === SHAPE_TYPES.ENDPOINT) + .forEach(dfs); + + // 如果有未访问的节点(可能是孤立的) + shapes.forEach(shape => { + if (!visited.has(shape.id)) dfs(shape); + }); + + // 按排序计算产能 + sortedShapes.forEach(calculateThroughput); + + // 特殊处理终端节点 + shapes.filter(s => s.type === SHAPE_TYPES.ENDPOINT).forEach(endpoint => { + let inputThroughput = 0; + endpoint.inputs.forEach(inputId => { + const inputShape = shapes.find(s => s.id === inputId); + if (inputShape) { + inputThroughput += inputShape.calculatedThroughput; + } + }); + endpoint.calculatedThroughput = inputThroughput; + }); + } + + // 获取形状在指定位置 + function getShapeAt(x, y) { + // 从上到下检查,这样最上面的形状会被先选中 + for (let i = shapes.length - 1; i >= 0; i--) { + const shape = shapes[i]; + + // 检查点是否在形状内 + if (x >= shape.x && x <= shape.x + shape.width && + y >= shape.y && y <= shape.y + shape.height) { + return shape; + } + } + + return null; + } + +// 获取连接点 +function getConnectionPointAt(x, y) { + // 连接点检测半径 - 增加检测半径提高敏感度 + const hitRadius = 15; + + // 先检查是否已有开始组件 + const hasStartShape = shapes.some(s => s.type === SHAPE_TYPES.START); + + for (const shape of shapes) { + // 根据形状类型确定连接点位置 + let connectionPoints = []; + + switch(shape.type) { + case SHAPE_TYPES.START: + // 开始组件:只有右侧连接点 + connectionPoints = [ + { x: shape.x + shape.width, y: shape.y + shape.height/2, position: 'right' } // 右 + ]; + break; + + case SHAPE_TYPES.PROCESS: + // 如果已经有开始组件,且当前形状不是开始组件的输出目标,则只允许左侧连接点 + if (hasStartShape && !isConnectedToStart(shape)) { + connectionPoints = [ + { x: shape.x, y: shape.y + shape.height/2, position: 'left' } // 只允许左侧连接 + ]; + } else { + // 否则允许所有连接点 + connectionPoints = [ + { x: shape.x, y: shape.y + shape.height/2, position: 'left' }, // 左 + { x: shape.x + shape.width, y: shape.y + shape.height/2, position: 'right' }, // 右 + { x: shape.x + shape.width/2, y: shape.y, position: 'top' }, // 上 + { x: shape.x + shape.width/2, y: shape.y + shape.height, position: 'bottom' } // 下 + ]; + } + break; + + case SHAPE_TYPES.TRANSPORT: + // 如果已经有开始组件,且当前形状不是开始组件的输出目标,则只允许左侧连接点 + if (hasStartShape && !isConnectedToStart(shape)) { + connectionPoints = [ + { x: shape.x, y: shape.y + shape.height/2, position: 'left' } // 只允许左侧连接 + ]; + } else { + connectionPoints = [ + { x: shape.x + shape.width/2, y: shape.y, position: 'top' }, // 上 + { x: shape.x + shape.width, y: shape.y + shape.height/2, position: 'right' }, // 右 + { x: shape.x + shape.width/2, y: shape.y + shape.height, position: 'bottom' }, // 下 + { x: shape.x, y: shape.y + shape.height/2, position: 'left' } // 左 + ]; + } + break; + + case SHAPE_TYPES.ENDPOINT: + // 椭圆:只在左侧有连接点 + connectionPoints = [ + { x: shape.x, y: shape.y + shape.height/2, position: 'left' } // 左 + ]; + break; + } + + // 检测连接点显示灵敏度的额外加强 + // 对于新拖入的组件,增加一个标记来促使连接点更容易显示 + const isNewShape = !shape.outputs || shape.outputs.length === 0; + const effectiveHitRadius = isNewShape ? hitRadius * 1.5 : hitRadius; + + // 检查每个连接点 + for (const point of connectionPoints) { + const dx = x - point.x; + const dy = y - point.y; + const distance = Math.sqrt(dx * dx + dy * dy); + + if (distance <= effectiveHitRadius) { + return { + shape: shape, + x: point.x, + y: point.y, + position: point.position + }; + } + } + } + + return null; +} + +// 检查形状是否已连接到开始组件 +function isConnectedToStart(shape) { + const startShape = shapes.find(s => s.type === SHAPE_TYPES.START); + if (!startShape) return false; + + // 检查是否有从开始组件到此形状的直接连接 + const directConnection = connections.some(conn => + conn.fromId === startShape.id && conn.toId === shape.id + ); + if (directConnection) return true; + + // 递归检查是否通过其他形状间接连接到开始组件 + function checkConnection(currentShape, visited = new Set()) { + if (visited.has(currentShape.id)) return false; + visited.add(currentShape.id); + + // 检查当前形状的所有输入 + for (const inputId of currentShape.inputs) { + const inputShape = shapes.find(s => s.id === inputId); + if (!inputShape) continue; + + if (inputShape.type === SHAPE_TYPES.START) return true; + if (checkConnection(inputShape, visited)) return true; + } + + return false; + } + + return checkConnection(shape); +} + + // 获取连接 + function getConnectionAt(x, y) { + // 连接线检测范围 + const hitDistance = 5; + + for (const connection of connections) { + const fromShape = shapes.find(s => s.id === connection.fromId); + const toShape = shapes.find(s => s.id === connection.toId); + + if (!fromShape || !toShape) continue; + + const startPoint = getConnectionPointCoordinates(fromShape, connection.startPosition); + const endPoint = getConnectionPointCoordinates(toShape, connection.endPosition); + + // 使用线段到点的距离检测 + if (isPointNearLine(x, y, startPoint, endPoint, hitDistance)) { + return connection; + } + } + + return null; + } + + // 检查点是否靠近线段 + function isPointNearLine(px, py, start, end, maxDistance) { + const dx = end.x - start.x; + const dy = end.y - start.y; + const length = Math.sqrt(dx * dx + dy * dy); + maxDistance = Math.max(maxDistance, 10); // 增加最小检测范围 + + // 避免除以零 + if (length === 0) return false; + + // 计算点到线的距离 + const t = ((px - start.x) * dx + (py - start.y) * dy) / (length * length); + + // 如果t < 0,最近点在线段外的起点一侧 + if (t < 0) { + return distanceSquared(px, py, start.x, start.y) <= maxDistance * maxDistance; + } + + // 如果t > 1,最近点在线段外的终点一侧 + if (t > 1) { + return distanceSquared(px, py, end.x, end.y) <= maxDistance * maxDistance; + } + + // 最近点在线段上 + const nearestX = start.x + t * dx; + const nearestY = start.y + t * dy; + + return distanceSquared(px, py, nearestX, nearestY) <= maxDistance * maxDistance; + } + + // 计算两点间距离的平方 + function distanceSquared(x1, y1, x2, y2) { + return (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2); + } + + // 绘制画布 + function drawCanvas() { + ctx.clearRect(0, 0, canvas.width, canvas.height); + + // 应用缩放和平移 + ctx.save(); + ctx.translate(panOffset.x, panOffset.y); + ctx.scale(zoomLevel, zoomLevel); + + // 绘制所有连接线 + connections.forEach(drawConnection); + + // 绘制所有形状 + shapes.forEach(drawShape); + + // 绘制正在创建的连接线 + if (isConnecting && connectingFrom) { + drawTemporaryConnection(); + } + + // 绘制悬停的连接点 + if (hoveredConnectionPoint) { + drawHoveredConnectionPoint(); + } + + ctx.restore(); + } + + // 绘制形状 + function drawShape(shape) { + ctx.save(); + + // 设置基本样式 + ctx.lineWidth = shape === selectedShape ? 3 : 2; + ctx.strokeStyle = SHAPE_COLORS[shape.type]; + ctx.fillStyle = 'white'; + + // 根据状态调整边框颜色 + if (simulationRunning) { + if (shape.status === SHAPE_STATUS.WORKING) { + ctx.strokeStyle = '#FF5722'; // 工作中 - 橙色 + } else if (shape.status === SHAPE_STATUS.WAITING) { + ctx.strokeStyle = '#2196F3'; // 等待下一步 - 蓝色 + } + } + + // 根据形状类型绘制不同图形 + switch(shape.type) { + case SHAPE_TYPES.START: + // 绘制圆形 + drawCircle(shape); + break; + + case SHAPE_TYPES.PROCESS: + // 绘制圆角矩形 + drawRoundedRect(shape); + break; + + case SHAPE_TYPES.TRANSPORT: + // 绘制菱形 + drawDiamond(shape); + break; + + case SHAPE_TYPES.ENDPOINT: + // 绘制椭圆 + drawEllipse(shape); + break; + } + + // 绘制文本和状态信息 + drawShapeInfo(shape); + + ctx.restore(); + } + + // 绘制开始组件(圆角矩形) + function drawCircle(shape) { + const radius = 10; + const x = shape.x; + const y = shape.y; + const width = shape.width; + const height = shape.height; + + ctx.beginPath(); + ctx.moveTo(x + radius, y); + ctx.lineTo(x + width - radius, y); + ctx.arcTo(x + width, y, x + width, y + radius, radius); + ctx.lineTo(x + width, y + height - radius); + ctx.arcTo(x + width, y + height, x + width - radius, y + height, radius); + ctx.lineTo(x + radius, y + height); + ctx.arcTo(x, y + height, x, y + height - radius, radius); + ctx.lineTo(x, y + radius); + ctx.arcTo(x, y, x + radius, y, radius); + ctx.closePath(); + + ctx.fill(); + ctx.stroke(); + } + + // 绘制圆角矩形 + function drawRoundedRect(shape) { + const radius = 10; + const x = shape.x; + const y = shape.y; + const width = shape.width; + const height = shape.height; + + ctx.beginPath(); + ctx.moveTo(x + radius, y); + ctx.lineTo(x + width - radius, y); + ctx.arcTo(x + width, y, x + width, y + radius, radius); + ctx.lineTo(x + width, y + height - radius); + ctx.arcTo(x + width, y + height, x + width - radius, y + height, radius); + ctx.lineTo(x + radius, y + height); + ctx.arcTo(x, y + height, x, y + height - radius, radius); + ctx.lineTo(x, y + radius); + ctx.arcTo(x, y, x + radius, y, radius); + ctx.closePath(); + + ctx.fill(); + ctx.stroke(); + } + + // 绘制菱形 + function drawDiamond(shape) { + const x = shape.x; + const y = shape.y; + const width = shape.width; + const height = shape.height; + const centerX = x + width / 2; + const centerY = y + height / 2; + + ctx.beginPath(); + ctx.moveTo(centerX, y); // 顶点 + ctx.lineTo(x + width, centerY); // 右点 + ctx.lineTo(centerX, y + height); // 底点 + ctx.lineTo(x, centerY); // 左点 + ctx.closePath(); + + ctx.fill(); + ctx.stroke(); + } + + // 绘制椭圆 + function drawEllipse(shape) { + const x = shape.x; + const y = shape.y; + const width = shape.width; + const height = shape.height; + const centerX = x + width / 2; + const centerY = y + height / 2; + + ctx.beginPath(); + ctx.ellipse(centerX, centerY, width / 2, height / 2, 0, 0, Math.PI * 2); + ctx.closePath(); + + ctx.fill(); + ctx.stroke(); + } + + // 绘制形状内的信息 + function drawShapeInfo(shape) { + const x = shape.x; + const y = shape.y; + const width = shape.width; + const height = shape.height; + const centerX = x + width / 2; + + // 绘制名称 + ctx.fillStyle = '#000'; + ctx.font = 'bold 12px Arial'; + ctx.textAlign = 'center'; + ctx.fillText(shape.name, centerX, y + 20, width - 10); + + // 根据形状类型绘制不同信息 + switch(shape.type) { + case SHAPE_TYPES.PROCESS: + // 显示状态 + ctx.font = '10px Arial'; + ctx.fillText(shape.status, centerX, y + 35, width - 10); + + // 显示当前步骤 + if (shape.status === SHAPE_STATUS.WORKING && shape.currentStepName) { + ctx.font = '10px Arial'; + ctx.fillStyle = '#FF5722'; + ctx.fillText(`当前: ${shape.currentStepName}`, centerX, y + 50, width - 10); + } + + // 显示理论产能 + ctx.font = 'bold 10px Arial'; + ctx.fillStyle = '#FF5722'; + ctx.fillText(`理论: ${shape.calculatedThroughput.toFixed(1)} PPM`, centerX, y + 65, width - 10); + + // 显示实时产能 + ctx.font = '10px Arial'; + ctx.fillStyle = '#2196F3'; + ctx.fillText(`实时: ${shape.realTimeThroughput.toFixed(1)} PPM`, centerX, y + 80, width - 10); + break; + + case SHAPE_TYPES.TRANSPORT: + // 显示状态 + ctx.font = '10px Arial'; + ctx.fillText(shape.status, centerX, y + 35, width - 10); + + // 显示理论产能 + ctx.font = 'bold 10px Arial'; + ctx.fillStyle = '#FF5722'; + ctx.fillText(`理论: ${shape.calculatedThroughput.toFixed(1)} PPM`, centerX, y + 50, width - 10); + + // 显示实时产能 + ctx.font = '10px Arial'; + ctx.fillStyle = '#2196F3'; + ctx.fillText(`实时: ${shape.realTimeThroughput.toFixed(1)} PPM`, centerX, y + 65, width - 10); + break; + + case SHAPE_TYPES.ENDPOINT: + // 显示收集数量 + ctx.font = 'bold 11px Arial'; + ctx.fillStyle = '#000'; + ctx.fillText(`收集数量: ${shape.processedItems}`, centerX, y + 35, width - 10); + + // 移除系统产能显示 + break; + } + } + + // 绘制连接线 + function drawConnection(connection) { + const fromShape = shapes.find(s => s.id === connection.fromId); + const toShape = shapes.find(s => s.id === connection.toId); + + if (!fromShape || !toShape) return; + + const startPoint = getConnectionPointCoordinates(fromShape, connection.startPosition); + const endPoint = getConnectionPointCoordinates(toShape, connection.endPosition); + + // 高亮选中的连接 + ctx.strokeStyle = connection === selectedConnection ? '#f44336' : '#2196F3'; + ctx.lineWidth = connection === selectedConnection ? 3 : 2; + + // 设置虚线样式,使用动画移动虚线 + ctx.setLineDash([8, 4]); + // 使用simulationTime创建移动效果,让虚线随时间流动 + ctx.lineDashOffset = -simulationTime * 60 * 5; // 乘以60将分钟转为秒,乘以5增加移动速度 + + // 绘制直线或正交连接 + drawOrthogonalConnection(connection, startPoint, endPoint); + + // 绘制箭头 + drawArrow(endPoint, getDirectionVectorTowards(endPoint, connection.lastPoint || startPoint)); + + // 清除虚线设置 + ctx.setLineDash([]); + + // 注意:我们不再需要粒子来表示动态效果,因为已经使用了虚线动画 + } + + // 绘制正交连接(直角连接) + function drawOrthogonalConnection(connection, start, end) { + const fromShape = shapes.find(s => s.id === connection.fromId); + const toShape = shapes.find(s => s.id === connection.toId); + + if (!fromShape || !toShape) return; + + // 计算连接点的路径 + let path = calculateOrthogonalPath(start, end, fromShape, toShape, connection); + + // 保存路径点用于粒子动画 + connection.pathPoints = path; + connection.lastPoint = path.length > 0 ? path[path.length - 1] : start; + + // 绘制路径 + ctx.beginPath(); + ctx.moveTo(start.x, start.y); + + for (const point of path) { + ctx.lineTo(point.x, point.y); + } + + ctx.lineTo(end.x, end.y); + ctx.stroke(); + } + + // 计算正交路径 + function calculateOrthogonalPath(start, end, fromShape, toShape, connection) { + const path = []; + + // 获取方向向量 + const startDir = getDirectionFromPosition(connection.startPosition); + const endDir = getDirectionFromPosition(connection.endPosition); + + // 计算控制点的偏移量 + const offset = 20; + + // 第一个控制点(从起点沿起点方向延伸) + const firstPoint = { + x: start.x + startDir.x * offset, + y: start.y + startDir.y * offset + }; + path.push(firstPoint); + + // 判断是否需要中间点 + if (Math.abs(startDir.x) === Math.abs(endDir.x) && + Math.abs(startDir.y) === Math.abs(endDir.y)) { + // 方向平行或相反,需要两个中间点 + + // 计算中点 + const midX = (start.x + end.x) / 2; + const midY = (start.y + end.y) / 2; + + if (startDir.x !== 0) { + // 水平方向起点 + path.push({ x: midX, y: firstPoint.y }); + path.push({ x: midX, y: end.y - endDir.y * offset }); + } else { + // 垂直方向起点 + path.push({ x: firstPoint.x, y: midY }); + path.push({ x: end.x - endDir.x * offset, y: midY }); + } + } else { + // 方向不同,只需要一个拐点 + if (startDir.x !== 0) { + // 水平方向起点 + path.push({ x: end.x - endDir.x * offset, y: firstPoint.y }); + } else { + // 垂直方向起点 + path.push({ x: firstPoint.x, y: end.y - endDir.y * offset }); + } + } + + return path; + } + + // 获取朝向某点的方向向量 + function getDirectionVectorTowards(point, fromPoint) { + const dx = point.x - fromPoint.x; + const dy = point.y - fromPoint.y; + const length = Math.sqrt(dx * dx + dy * dy) || 1; // 避免除以零 + + return { + x: dx / length, + y: dy / length + }; + } + + // 绘制箭头 + function drawArrow(point, direction) { + const arrowSize = 8; + const arrowAngle = Math.PI / 6; // 30度 + + // 计算箭头角度 + const angle = Math.atan2(direction.y, direction.x); + + // 绘制箭头 + ctx.beginPath(); + ctx.moveTo(point.x, point.y); + ctx.lineTo( + point.x - arrowSize * Math.cos(angle - arrowAngle), + point.y - arrowSize * Math.sin(angle - arrowAngle) + ); + ctx.lineTo( + point.x - arrowSize * Math.cos(angle + arrowAngle), + point.y - arrowSize * Math.sin(angle + arrowAngle) + ); + ctx.closePath(); + + ctx.fillStyle = ctx.strokeStyle; + ctx.fill(); + } + + // 绘制临时连接线 + function drawTemporaryConnection() { + if (!connectingFrom || !hoveredConnectionPoint) return; + + const startPoint = getConnectionPointCoordinates( + connectingFrom, + hoveredConnectionPoint.position + ); + + ctx.strokeStyle = '#2196F3'; + ctx.lineWidth = 2; + ctx.setLineDash([5, 3]); + + // 绘制临时连接线 + drawTemporaryOrthogonalLine(startPoint, connectingToPoint, hoveredConnectionPoint.position); + + ctx.setLineDash([]); + } + + // 绘制临时正交线 + function drawTemporaryOrthogonalLine(start, end, startPosition) { + const startDir = getDirectionFromPosition(startPosition); + const offset = 20; + + // 第一个控制点 + const firstPoint = { + x: start.x + startDir.x * offset, + y: start.y + startDir.y * offset + }; + + // 判断连接类型并绘制 + ctx.beginPath(); + ctx.moveTo(start.x, start.y); + ctx.lineTo(firstPoint.x, firstPoint.y); + + if (startDir.x !== 0) { + // 水平方向起点 + ctx.lineTo(end.x, firstPoint.y); + } else { + // 垂直方向起点 + ctx.lineTo(firstPoint.x, end.y); + } + + ctx.lineTo(end.x, end.y); + ctx.stroke(); + } + + // 绘制悬停的连接点 + function drawHoveredConnectionPoint() { + if (!hoveredConnectionPoint) return; + + ctx.fillStyle = 'rgba(33, 150, 243, 0.6)'; + ctx.strokeStyle = '#2196F3'; + ctx.lineWidth = 2; + + ctx.beginPath(); + ctx.arc(hoveredConnectionPoint.x, hoveredConnectionPoint.y, 8, 0, Math.PI * 2); + ctx.fill(); + ctx.stroke(); + + // 绘制加号 + ctx.fillStyle = 'white'; + ctx.font = 'bold 12px Arial'; + ctx.textAlign = 'center'; + ctx.textBaseline = 'middle'; + ctx.fillText('+', hoveredConnectionPoint.x, hoveredConnectionPoint.y); + } + + // 绘制动态粒子 + function drawParticles(connection) { + if (!connection.particles || !connection.pathPoints) return; + + const fromShape = shapes.find(s => s.id === connection.fromId); + const toShape = shapes.find(s => s.id === connection.toId); + + if (!fromShape || !toShape) return; + + const startPoint = getConnectionPointCoordinates(fromShape, connection.startPosition); + const endPoint = getConnectionPointCoordinates(toShape, connection.endPosition); + + // 构建完整路径 + const fullPath = [startPoint, ...connection.pathPoints, endPoint]; + + // 绘制每个粒子 + for (const particle of connection.particles) { + const pos = calculateParticlePosition(particle.progress, fullPath); + + ctx.fillStyle = '#FF9800'; + ctx.beginPath(); + ctx.arc(pos.x, pos.y, 4, 0, Math.PI * 2); + ctx.fill(); + } + } + + // 计算粒子在路径上的位置 + function calculateParticlePosition(progress, path) { + if (path.length < 2) return path[0]; + + // 计算路径总长度和各段长度 + let totalLength = 0; + const segmentLengths = []; + + for (let i = 0; i < path.length - 1; i++) { + const dx = path[i+1].x - path[i].x; + const dy = path[i+1].y - path[i].y; + const length = Math.sqrt(dx*dx + dy*dy); + segmentLengths.push(length); + totalLength += length; + } + + // 根据进度找到对应段 + const targetDistance = progress * totalLength; + let distanceTraveled = 0; + + for (let i = 0; i < segmentLengths.length; i++) { + if (distanceTraveled + segmentLengths[i] >= targetDistance) { + // 找到了段,计算位置 + const segmentProgress = (targetDistance - distanceTraveled) / segmentLengths[i]; + return { + x: path[i].x + (path[i+1].x - path[i].x) * segmentProgress, + y: path[i].y + (path[i+1].y - path[i].y) * segmentProgress + }; + } + distanceTraveled += segmentLengths[i]; + } + + // 如果到达这里,返回路径终点 + return path[path.length - 1]; + } + + // 将坐标对齐到网格 + function snapToGrid(value) { + return Math.round(value / GRID_SIZE) * GRID_SIZE; + } + + // 更新状态信息 + function updateStatus(message) { + document.getElementById('status-message').textContent = message; + } + + // 重置仿真 + function resetSimulation() { + // 停止当前仿真 + if (simulationRunning) { + stopSimulation(); + } + + // 重置所有形状的状态 + shapes.forEach(shape => { + shape.processedItems = 0; + shape.buffer = 0; + shape.status = SHAPE_STATUS.IDLE; + shape.waitingForNext = false; + shape.waitingForPrevious = true; + shape.realTimeThroughput = 0; + shape.lastProcessTime = 0; + }); + + // 清空所有连接上的粒子 + connections.forEach(connection => { + connection.particles = []; + }); + + // 重置仿真时间 + simulationTime = 0; + + // 更新统计信息 + updateSimulationStats(); + + // 重绘画布 + drawCanvas(); + + updateStatus('仿真已重置'); + } + + // 开始仿真 + function startSimulation() { + if (simulationRunning) return; + + // 设置固定的仿真速度,完全按照机构的实际速度进行 + simulationSpeed = 1; // 使仿真时间与现实时间保持一致 + + // 重置仿真状态 + resetSimulation(); + + // 不再需要初始化粒子动画,因为使用虚线实现动态效果 + // initializeConnectionAnimations(); + + // 更新按钮文本 + document.getElementById('start-simulation').textContent = '正在仿真'; + document.getElementById('start-simulation').disabled = true; + + simulationRunning = true; + + // 记录仿真开始的真实时间 + let simulationStartTime = Date.now(); + let lastUpdateTime = simulationStartTime; + + // 启动仿真计时器 - 使用更小的时间间隔使动画更流畅 + simulationInterval = setInterval(() => { + // 获取当前真实时间 + const currentTime = Date.now(); + + // 计算真实经过的时间差(毫秒转换为分钟) + const realTimeDiff = (currentTime - lastUpdateTime) / (1000 * 60); + + // 更新仿真时间(按真实时间流逝) + simulationTime += realTimeDiff; + + // 更新上次更新时间 + lastUpdateTime = currentTime; + + // 更新仿真逻辑 + updateSimulation(); + + // 更新统计信息 + updateSimulationStats(); + + // 重绘画布 + drawCanvas(); + + // 仿真持续进行,直到用户手动停止 + // 不再根据设定时间自动停止 + + // 更新状态栏显示当前仿真时间(以秒为单位) + updateStatus(`仿真进行中 - ${Math.floor(simulationTime * 60)}秒`) + }, 10); // 使用10毫秒的间隔使动画更流畅 + + updateStatus('仿真进行中'); + } + + // 初始化连接线动画效果 + function initializeConnectionAnimations() { + // 为每条连接线添加初始粒子 + connections.forEach(connection => { + // 清空现有粒子 + connection.particles = []; + + // 添加2-3个随机分布的粒子 + const particleCount = 2 + Math.floor(Math.random() * 2); + for (let i = 0; i < particleCount; i++) { + connection.particles.push({ + // 随机初始位置 + progress: Math.random(), + speed: 0.05 // 使用固定速度,不再依赖速度倍率 + }); + } + }); + } + + // 停止仿真 + function stopSimulation() { + if (!simulationRunning) return; + + clearInterval(simulationInterval); + simulationRunning = false; + + // 更新按钮文本 + document.getElementById('start-simulation').textContent = '开始仿真'; + document.getElementById('start-simulation').disabled = false; + + updateStatus('仿真已停止'); + } + + // 更新仿真逻辑 + function updateSimulation() { + // 首先计算每个形状的输入流量 + calculateInputFlows(); + + // 更新每个形状的状态和输出 + updateShapeStates(); + + // 更新连接上的粒子移动 + updateParticles(); + } + + // 计算各个形状的输入流量 + function calculateInputFlows() { + shapes.forEach(shape => { + // 开始组件不等待输入 + if (shape.type === SHAPE_TYPES.START) { + shape.waitingForPrevious = false; + // 确保开始组件不会被阻塞 + shape.waitingForNext = false; + shape.status = SHAPE_STATUS.WORKING; + return; + } + + // 检查输入形状的状态 + let hasActiveInput = false; + let inputBuffer = 0; + let hasStartShapeInput = false; + + // 如果没有输入连接,则不等待上游 + if (shape.inputs.length === 0) { + shape.waitingForPrevious = false; + return; + } + + shape.inputs.forEach(inputId => { + const inputShape = shapes.find(s => s.id === inputId); + if (inputShape) { + // 检查是否有开始组件作为输入 + if (inputShape.type === SHAPE_TYPES.START) { + hasStartShapeInput = true; + hasActiveInput = true; // 开始组件总是被视为活跃输入 + } + // 只要上游机构有产品,就认为有活跃输入 + else if (inputShape.buffer > 0) { + hasActiveInput = true; + inputBuffer += inputShape.buffer; + } + } + }); + + // 更新形状的等待状态 + if (shape.type !== SHAPE_TYPES.ENDPOINT) { + // 如果有开始组件作为输入,则不等待上游 + if (hasStartShapeInput) { + shape.waitingForPrevious = false; + shape.status = SHAPE_STATUS.WORKING; + } else { + // 只有当上游没有产品时才等待 + shape.waitingForPrevious = inputBuffer === 0; + } + } else { + // 终端节点不等待输入 + shape.waitingForPrevious = false; + } + }); + + // 第二次遍历,确保所有连接到开始组件的下游组件都能自动开始工作 + shapes.forEach(shape => { + if (shape.type === SHAPE_TYPES.START) { + // 激活所有连接到开始组件的下游组件 + shape.outputs.forEach(outputId => { + const outputShape = shapes.find(s => s.id === outputId); + if (outputShape) { + outputShape.waitingForPrevious = false; + outputShape.status = SHAPE_STATUS.WORKING; + } + }); + } + }); + } + + // 更新形状状态和输出 + function updateShapeStates() { + // 首先更新所有机构的等待状态 + updateWaitingStates(); + + // 然后按照拓扑顺序更新机构状态,确保上游机构先更新 + // 这样可以正确传递产能限制信息 + const processedShapes = new Set(); + + // 首先处理起始节点 + shapes.filter(shape => shape.type === SHAPE_TYPES.START).forEach(shape => { + processShape(shape, processedShapes); + }); + + // 确保所有节点都被处理 + shapes.forEach(shape => { + if (!processedShapes.has(shape.id)) { + processShape(shape, processedShapes); + } + }); + } + + // 按照拓扑顺序处理节点 + function processShape(shape, processedShapes) { + // 如果已处理过,直接返回 + if (processedShapes.has(shape.id)) return; + + // 先处理所有输入节点 + shape.inputs.forEach(inputId => { + const inputShape = shapes.find(s => s.id === inputId); + if (inputShape && !processedShapes.has(inputShape.id)) { + processShape(inputShape, processedShapes); + } + }); + + // 根据形状类型更新状态 + switch(shape.type) { + case SHAPE_TYPES.START: + updateStartShape(shape); + break; + + case SHAPE_TYPES.PROCESS: + updateProcessShape(shape); + break; + + case SHAPE_TYPES.TRANSPORT: + updateTransportShape(shape); + break; + + case SHAPE_TYPES.ENDPOINT: + updateEndpointShape(shape); + break; + } + + // 标记为已处理 + processedShapes.add(shape.id); + } + + // 更新开始组件 + function updateStartShape(shape) { + // 开始组件始终处于工作状态 + shape.status = SHAPE_STATUS.WORKING; + + // 开始组件不累积物料,只作为流程标记 + shape.buffer = 0; + + // 确保开始组件不会被阻塞 + shape.waitingForPrevious = false; + shape.waitingForNext = false; + + // 直接激活所有下游组件 + shape.outputs.forEach(outputId => { + const outputShape = shapes.find(s => s.id === outputId); + if (outputShape) { + // 标记下游组件不需要等待上游 + outputShape.waitingForPrevious = false; + + // 无论下游组件有多少输入,都直接设置为工作状态 + // 这确保了开始组件能够正确触发所有下游组件 + outputShape.status = SHAPE_STATUS.WORKING; + + // 特别处理运输组件 + if (outputShape.type === SHAPE_TYPES.TRANSPORT) { + // 确保运输组件不会等待上游 + outputShape.waitingForPrevious = false; + // 确保运输组件不会等待下游 + outputShape.waitingForNext = false; + // 初始化处理时间,确保能立即开始工作 + outputShape.lastProcessTime = 0; + } + } + }); + + // 调用transferProducts函数来创建粒子动画 + transferProducts(shape); + + // 开始组件仅作为流程标记,不设置任何产能值 + shape.realTimeThroughput = 0; + } + +// 更新普通机构 +function updateProcessShape(shape) { + // 初始化当前步骤和总周期时间 + if (!shape.currentStepIndex) { + shape.currentStepIndex = 0; + } + + // 获取步骤数据 + const steps = shape.params.steps || [ + // 兼容旧数据 + { + name: "步骤1", + startTime: 0, + workTime: (shape.params.actionSteps || 1) * (shape.params.stepTime || 1) + } + ]; + + // 计算总周期时间(分钟) + let maxEndTime = 0; + steps.forEach(step => { + const endTime = step.startTime + step.workTime; + if (endTime > maxEndTime) { + maxEndTime = endTime; + } + }); + const cycleTimeMinutes = maxEndTime / 60; + + // 如果上游机构未完成,等待上游机构传送产品 + if (shape.waitingForPrevious) { + shape.status = SHAPE_STATUS.IDLE; + // 不重置处理时间,保持当前进度 + return; + } + + // 检查是否有产品在缓冲区等待传送 + if (shape.buffer > 0) { + // 检查下游机构是否可接收 + const outputBlocked = checkOutputBlocked(shape); + if (outputBlocked) { + // 下游机构阻塞,无法传送产品,停止生产 + shape.waitingForNext = true; + shape.status = SHAPE_STATUS.WAITING; + return; // 停止处理,不继续生产 + } else { + // 下游机构可接收,传送产品 + transferProducts(shape); + // transferProducts函数会重置waitingForNext状态 + } + } else { + shape.waitingForNext = false; + } + + // 检查下游机构是否可接收 - 即使当前没有缓冲产品也要检查 + // 这是为了模拟现实中的情况:如果下游机构无法接收,则不应继续生产 + const outputBlocked = checkOutputBlocked(shape); + if (outputBlocked) { + // 下游机构阻塞,无法接收产品,停止生产 + shape.waitingForNext = true; + shape.status = SHAPE_STATUS.WAITING; + return; // 停止处理,不继续生产 + } + + // 只有当下游机构可以接收产品时,才继续生产 + shape.status = SHAPE_STATUS.WORKING; + + // 累积工作时间 + shape.lastProcessTime += SIMULATION_TICK; + + // 更新当前执行的步骤 + const currentTime = shape.lastProcessTime * 60; // 转换为秒 + let activeStepFound = false; + + // 查找当前时间正在执行的步骤 + for (let i = 0; i < steps.length; i++) { + const step = steps[i]; + const stepStartTime = step.startTime; + const stepEndTime = step.startTime + step.workTime; + + if (currentTime >= stepStartTime && currentTime <= stepEndTime) { + shape.currentStepIndex = i; + shape.currentStepName = step.name; + activeStepFound = true; + break; + } + } + + // 如果没有找到活动步骤,可能是在步骤之间的间隙 + if (!activeStepFound) { + shape.currentStepName = "等待下一步骤"; + } + + // 如果完成了一个处理周期 + if (shape.lastProcessTime >= cycleTimeMinutes) { + // 生产产品 + shape.buffer += shape.params.batchSize; + shape.totalProduced = (shape.totalProduced || 0) + shape.params.batchSize; + + // 计算实时产能 (PPM) - 使用理论周期时间计算 + if (simulationTime > 0) { + // 使用理论周期时间计算实时产能,而不是累计产量除以总时间 + const theoreticalCyclesCompleted = Math.floor(simulationTime / cycleTimeMinutes); + const theoreticalProduction = theoreticalCyclesCompleted * shape.params.batchSize; + shape.realTimeThroughput = theoreticalProduction / simulationTime; + } + + // 重置处理时间和步骤索引 + shape.lastProcessTime = 0; + shape.currentStepIndex = 0; + shape.currentStepName = steps[0].name; + + // 检查下游机构是否可接收 + const outputBlocked = checkOutputBlocked(shape); + if (outputBlocked) { + // 下游机构阻塞,无法传送产品 + shape.waitingForNext = true; + shape.status = SHAPE_STATUS.WAITING; + } else { + // 下游机构可接收,传送产品 + transferProducts(shape); + shape.waitingForNext = false; + } + } +} + +// 更新运输机构 - 使其逻辑与普通组件一致 +function updateTransportShape(shape) { + // 计算运输周期时间(分钟) + const transportTimeMinutes = shape.params.transportTime * shape.params.transportCount / 60; + + // 如果上游机构未完成,等待上游机构传送产品 + if (shape.waitingForPrevious) { + shape.status = SHAPE_STATUS.IDLE; + // 不重置处理时间,保持当前进度 + return; + } + + // 检查是否有产品在缓冲区等待传送 + if (shape.buffer > 0) { + // 检查下游机构是否可接收 + const outputBlocked = checkOutputBlocked(shape); + if (outputBlocked) { + // 下游机构阻塞,无法传送产品,停止生产 + shape.waitingForNext = true; + shape.status = SHAPE_STATUS.WAITING; + return; // 停止处理,不继续生产 + } else { + // 下游机构可接收,传送产品 + transferProducts(shape); + // transferProducts函数会重置waitingForNext状态 + } + } else { + shape.waitingForNext = false; + } + + // 检查下游机构是否可接收 - 即使当前没有缓冲产品也要检查 + // 这是为了模拟现实中的情况:如果下游机构无法接收,则不应继续生产 + const outputBlocked = checkOutputBlocked(shape); + if (outputBlocked) { + // 下游机构阻塞,无法接收产品,停止生产 + shape.waitingForNext = true; + shape.status = SHAPE_STATUS.WAITING; + return; // 停止处理,不继续生产 + } + + // 只有当下游机构可以接收产品时,才继续生产 + shape.status = SHAPE_STATUS.WORKING; + + // 累积工作时间 + shape.lastProcessTime += SIMULATION_TICK; + + // 如果完成了一个运输周期 + if (shape.lastProcessTime >= transportTimeMinutes) { + // 生产产品 + shape.buffer += shape.params.transportBatch; + shape.totalTransported = (shape.totalTransported || 0) + shape.params.transportBatch; + + // 计算实时产能 (PPM) + if (simulationTime > 0) { + // 使用理论周期时间计算实时产能 + const theoreticalCyclesCompleted = Math.floor(simulationTime / transportTimeMinutes); + const theoreticalTransported = theoreticalCyclesCompleted * shape.params.transportBatch; + shape.realTimeThroughput = theoreticalTransported / simulationTime; + } + + // 重置处理时间 + shape.lastProcessTime = 0; + + // 检查下游机构是否可接收 + const outputBlocked = checkOutputBlocked(shape); + if (outputBlocked) { + // 下游机构阻塞,无法传送产品 + shape.waitingForNext = true; + shape.status = SHAPE_STATUS.WAITING; + } else { + // 下游机构可接收,传送产品 + transferProducts(shape); + // 如果传递后仍有物料,说明下游产能有限 + shape.waitingForNext = shape.buffer > 0; + // 更新状态 + shape.status = shape.waitingForNext ? SHAPE_STATUS.WAITING : SHAPE_STATUS.WORKING; + } + } +} + + // 更新终端收料机构 + function updateEndpointShape(shape) { + // 终端节点始终处于活跃状态 + shape.status = SHAPE_STATUS.WORKING; + + // 从所有输入形状接收产品 + let receivedItems = 0; + + shape.inputs.forEach(inputId => { + const inputShape = shapes.find(s => s.id === inputId); + if (inputShape && inputShape.buffer > 0) { + // 创建从输入到此终端节点的粒子 + const connection = connections.find(c => + c.fromId === inputShape.id && c.toId === shape.id); + + if (connection) { + for (let i = 0; i < inputShape.buffer; i++) { + // 添加新粒子 + connection.particles.push({ + progress: 0, // 起点 + speed: 0.02 * simulationSpeed / 100 // 速度根据仿真速度调整 + }); + } + } + + // 清空输入形状的缓冲区 + inputShape.buffer = 0; + + // 输入形状不再等待 + inputShape.waitingForNext = false; + } + }); + + // 更新终端节点的处理产品数量 + shape.processedItems = shape.processedItems || 0; + + // 更新实时产能 (PPM) + if (simulationTime > 0) { + // 计算系统实际产能 + const systemThroughput = shape.processedItems / simulationTime; + shape.realTimeThroughput = systemThroughput; + + // 更新系统产能显示 + document.getElementById('system-throughput').textContent = + systemThroughput.toFixed(1); + + // 更新总产出显示 + document.getElementById('total-output').textContent = + shape.processedItems; + } + } + + // 检查下游机构是否可接收产品 + function checkOutputBlocked(shape) { + // 如果没有输出连接,则不阻塞 + if (shape.outputs.length === 0) return false; + + // 检查所有下游节点是否都已阻塞 + let allBlocked = true; + + shape.outputs.forEach(outputId => { + const outputShape = shapes.find(s => s.id === outputId); + if (outputShape && !outputShape.waitingForNext) { + allBlocked = false; + } + }); + + return allBlocked; + } + +// 尝试向下游传递产品 +function transferProducts(shape) { + // 如果是开始组件,不传递实际物料,只激活下游组件 + if (shape.type === SHAPE_TYPES.START) { + // 获取所有下游节点 + const outputs = shape.outputs + .map(id => shapes.find(s => s.id === id)) + .filter(s => s); + + // 激活所有下游组件 + outputs.forEach(outputShape => { + outputShape.waitingForPrevious = false; + outputShape.status = SHAPE_STATUS.WORKING; + + // 特别处理运输组件 + if (outputShape.type === SHAPE_TYPES.TRANSPORT) { + // 确保运输组件不会等待上游 + outputShape.waitingForPrevious = false; + // 确保运输组件不会等待下游 + outputShape.waitingForNext = false; + // 初始化处理时间,确保能立即开始工作 + outputShape.lastProcessTime = 0; + // 运输组件的物料处理逻辑与普通组件一致 + outputShape.buffer = (outputShape.buffer || 0) + itemsToTransfer; + outputShape.status = SHAPE_STATUS.WORKING; + } + + // 为每个连接创建粒子动画,增强可视化效果 + const connection = connections.find(c => + c.fromId === shape.id && c.toId === outputShape.id); + + if (connection) { + if (!connection.particles) connection.particles = []; + // 添加一个粒子表示信号传递 + connection.particles.push({ + progress: 0, + speed: 0.05 * simulationSpeed / 100 + }); + } + }); + + // 开始组件不等待下游 + shape.waitingForNext = false; + return; + } + + if (shape.buffer <= 0 || shape.outputs.length === 0) return; + + // 获取可用的下游节点 - 包括终端节点和非终端节点 + const availableOutputs = shape.outputs + .map(id => shapes.find(s => s.id === id)) + .filter(s => s && (s.type === SHAPE_TYPES.ENDPOINT || !s.waitingForNext)); + + if (availableOutputs.length === 0) { + // 所有下游都被阻塞,但不应该停止整个系统 + // 仅标记当前节点等待下游,但允许继续累积物料 + shape.waitingForNext = true; + return; + } + + // 考虑下游机构的产能限制 + let maxTransferAmount = shape.buffer; + + // 检查下游机构的产能限制 + availableOutputs.forEach(outputShape => { + // 如果不是终端节点,检查其产能 + if (outputShape.type !== SHAPE_TYPES.ENDPOINT) { + // 获取下游机构的理论产能 + let downstreamCapacity = 0; + + if (outputShape.type === SHAPE_TYPES.PROCESS) { + // 计算处理机构的理论产能 + const steps = outputShape.params.steps || [ + { + name: "步骤1", + startTime: 0, + workTime: (outputShape.params.actionSteps || 1) * (outputShape.params.stepTime || 1) + } + ]; + + // 计算总周期时间(分钟) + let maxEndTime = 0; + steps.forEach(step => { + const endTime = step.startTime + step.workTime; + if (endTime > maxEndTime) { + maxEndTime = endTime; + } + }); + const cycleTimeMinutes = maxEndTime / 60; + + // 计算理论产能 + if (cycleTimeMinutes > 0) { + downstreamCapacity = outputShape.params.batchSize / cycleTimeMinutes; + } + } else if (outputShape.type === SHAPE_TYPES.TRANSPORT) { + // 计算运输机构的理论产能 + const transportTimeMinutes = outputShape.params.transportTime * outputShape.params.transportCount / 60; + if (transportTimeMinutes > 0) { + downstreamCapacity = outputShape.params.transportBatch / transportTimeMinutes; + } + } + + // 如果下游机构有产能限制,调整传输量,但确保至少传递一些物料 + if (downstreamCapacity > 0 && shape.realTimeThroughput > downstreamCapacity) { + // 根据下游产能比例调整传输量 + const capacityRatio = downstreamCapacity / shape.realTimeThroughput; + const adjustedAmount = Math.max(1, Math.ceil(shape.buffer * capacityRatio)); + maxTransferAmount = Math.min(maxTransferAmount, adjustedAmount); + } + } + }); + + // 计算每个下游节点应接收的产品数量,考虑产能限制 + // 确保至少传递1个物料,避免完全停滞 + const itemsPerOutput = Math.max(1, Math.floor(maxTransferAmount / availableOutputs.length)); + let remainingItems = maxTransferAmount % availableOutputs.length; + + // 创建粒子并传递产品 + availableOutputs.forEach(outputShape => { + // 分配产品数量 + let itemsToTransfer = itemsPerOutput; + if (remainingItems > 0) { + itemsToTransfer++; + remainingItems--; + } + + if (itemsToTransfer <= 0) return; + + // 创建从此形状到输出形状的粒子 + const connection = connections.find(c => + c.fromId === shape.id && c.toId === outputShape.id); + + if (connection) { + // 所有机构瞬间传递物料到下游 + if (outputShape.type === SHAPE_TYPES.ENDPOINT) { + // 如果是终端节点,直接增加处理数量 + outputShape.processedItems = (outputShape.processedItems || 0) + itemsToTransfer; + + // 更新系统产能 - 使用理论计算方式 + if (simulationTime > 0) { + // 使用系统理论周期时间计算 + const systemThroughput = outputShape.processedItems / simulationTime; + outputShape.realTimeThroughput = systemThroughput; + } + } else { + // 非终端节点,直接增加缓冲区 + outputShape.buffer = (outputShape.buffer || 0) + itemsToTransfer; + // 更新下游机构状态 + outputShape.waitingForPrevious = false; + outputShape.status = SHAPE_STATUS.WORKING; + + // 确保下游组件知道它有新的物料需要处理 + if (outputShape.type === SHAPE_TYPES.TRANSPORT) { + // 如果下游是运输组件,确保它知道有物料可以传递 + outputShape.waitingForNext = false; + } + } + + // 创建粒子动画(仅用于可视化) + for (let i = 0; i < itemsToTransfer; i++) { + connection.particles.push({ + progress: 0, + speed: 0.05 * simulationSpeed / 100 + }); + } + } + }); + + // 更新缓冲区,保留未传递的物料 + const transferredAmount = Math.min(shape.buffer, maxTransferAmount); + shape.buffer -= transferredAmount; + + // 如果成功传送了物料,则允许机构继续生产 + // 但如果缓冲区仍有物料,说明下游产能有限,应限制上游生产 + // 但不应完全阻止生产,只是标记状态 + shape.waitingForNext = shape.buffer > 0; + + // 通知上游机构可以继续生产 + // 即使当前机构缓冲区已满,也不应完全阻止上游生产 + shape.inputs.forEach(inputId => { + const inputShape = shapes.find(s => s.id === inputId); + if (inputShape) { + // 允许上游继续生产,但可能会限制产能 + inputShape.waitingForNext = false; + } + }); +} + + // 更新连接上的粒子 - 简化实现,主要依赖虚线动画 + function updateParticles() { + // 由于我们使用了虚线动画替代粒子,这个函数简化为主要处理开始组件特殊情况的逻辑 + connections.forEach(connection => { + // 获取源形状和目标形状 + const fromShape = shapes.find(s => s.id === connection.fromId); + const toShape = shapes.find(s => s.id === connection.toId); + + // 特殊处理开始组件的连接 + if (fromShape && toShape && fromShape.type === SHAPE_TYPES.START) { + // 开始组件连接的下游组件不等待上游 + toShape.waitingForPrevious = false; + toShape.status = SHAPE_STATUS.WORKING; + + // 特别处理运输组件 + if (toShape.type === SHAPE_TYPES.TRANSPORT) { + toShape.waitingForPrevious = false; + toShape.status = SHAPE_STATUS.WORKING; + toShape.waitingForNext = false; + toShape.lastProcessTime = 0; + } + } + + // 粒子动画部分不再需要,因为使用虚线效果代替 + }); + } + + + // 更新仿真统计信息 + function updateSimulationStats() { + // 更新仿真时间显示(转换为秒) + const timeInSeconds = simulationTime * 60; // 将分钟转换为秒 + document.getElementById('elapsed-time').textContent = timeInSeconds.toFixed(1); + + // 找到终端节点计算系统吞吐量 + const endpoints = shapes.filter(s => s.type === SHAPE_TYPES.ENDPOINT); + + if (endpoints.length > 0) { + // 计算所有终端节点的总产出 + const totalOutput = endpoints.reduce((sum, endpoint) => sum + endpoint.processedItems, 0); + + // 显示总产出 + document.getElementById('total-output').textContent = totalOutput; + + // 计算系统产能 (PPS - 每秒产能) + let systemThroughput = 0; + if (simulationTime > 0) { + systemThroughput = totalOutput / (simulationTime * 60); // 转换为每秒产能 + } + + // 显示系统产能 + document.getElementById('system-throughput').textContent = systemThroughput.toFixed(2); + } + } + + // 显示保存项目对话框 + function showSaveProjectDialog() { + const modal = document.getElementById('file-modal'); + document.getElementById('file-modal-title').textContent = '保存项目'; + document.getElementById('file-action-btn').textContent = '保存'; + document.getElementById('saved-projects-container').style.display = 'none'; + document.getElementById('file-form').dataset.action = 'save'; + + // 显示对话框 + modal.style.display = 'block'; + } + + // 显示加载项目对话框 + function showLoadProjectDialog() { + const modal = document.getElementById('file-modal'); + document.getElementById('file-modal-title').textContent = '加载项目'; + document.getElementById('file-action-btn').textContent = '加载'; + document.getElementById('saved-projects-container').style.display = 'block'; + document.getElementById('file-form').dataset.action = 'load'; + + // 加载已保存的项目列表 + loadProjectList(); + + // 显示对话框 + modal.style.display = 'block'; + } + + // 加载已保存项目列表 + function loadProjectList() { + const projectsList = document.getElementById('saved-projects-list'); + projectsList.innerHTML = ''; + + // 从localStorage获取已保存的项目 + let savedProjects = localStorage.getItem('flowSimProjects'); + if (savedProjects) { + try { + savedProjects = JSON.parse(savedProjects); + + // 为每个项目创建列表项 + Object.keys(savedProjects).forEach(projectName => { + const li = document.createElement('li'); + li.textContent = projectName; + li.addEventListener('click', function() { + document.getElementById('project-name').value = projectName; + }); + + // 创建删除按钮 + const deleteBtn = document.createElement('button'); + deleteBtn.textContent = '删除'; + deleteBtn.className = 'delete-btn'; + deleteBtn.addEventListener('click', function(e) { + e.stopPropagation(); + if (confirm(`确定删除项目 "${projectName}"?`)) { + delete savedProjects[projectName]; + localStorage.setItem('flowSimProjects', JSON.stringify(savedProjects)); + loadProjectList(); + } + }); + + li.appendChild(deleteBtn); + projectsList.appendChild(li); + }); + } catch (e) { + console.error('加载项目列表失败:', e); + } + } + + // 如果没有项目,显示提示信息 + if (projectsList.children.length === 0) { + const li = document.createElement('li'); + li.textContent = '没有已保存的项目'; + li.style.textAlign = 'center'; + li.style.cursor = 'default'; + projectsList.appendChild(li); + } + } + + // 处理文件表单提交 + function handleFileSubmit() { + const form = document.getElementById('file-form'); + const action = form.dataset.action; + const projectName = document.getElementById('project-name').value.trim(); + + if (!projectName) { + alert('请输入项目名称'); + return; + } + + if (action === 'save') { + saveProject(projectName); + } else if (action === 'load') { + loadProject(projectName); + } + + // 关闭对话框 + document.getElementById('file-modal').style.display = 'none'; + } + + // 保存项目 + function saveProject(projectName) { + // 收集项目数据 + const projectData = { + shapes: shapes, + connections: connections, + nextShapeId: nextShapeId, + nextConnectionId: nextConnectionId + }; + + // 获取已保存的项目 + let savedProjects = localStorage.getItem('flowSimProjects'); + if (!savedProjects) { + savedProjects = {}; + } else { + savedProjects = JSON.parse(savedProjects); + } + + // 检查是否覆盖现有项目 + if (savedProjects[projectName] && !confirm(`项目 "${projectName}" 已存在,是否覆盖?`)) { + return; + } + + // 保存项目 + savedProjects[projectName] = projectData; + localStorage.setItem('flowSimProjects', JSON.stringify(savedProjects)); + + alert(`项目 "${projectName}" 已保存`); + } + + // 加载项目 + function loadProject(projectName) { + // 获取已保存的项目 + let savedProjects = localStorage.getItem('flowSimProjects'); + if (!savedProjects) { + alert('没有找到已保存的项目'); + return; + } + + savedProjects = JSON.parse(savedProjects); + + // 检查项目是否存在 + if (!savedProjects[projectName]) { + alert(`项目 "${projectName}" 不存在`); + return; + } + + const projectData = savedProjects[projectName]; + + // 加载项目数据 + shapes = projectData.shapes; + connections = projectData.connections; + nextShapeId = projectData.nextShapeId; + nextConnectionId = projectData.nextConnectionId; + + // 重置选择状态 + selectedShape = null; + selectedConnection = null; + + // 重置仿真状态 + resetSimulation(); + + alert(`项目 "${projectName}" 已加载`); + } +}); diff --git a/002_练手例程/时序仿真/styles.css b/002_练手例程/时序仿真/styles.css new file mode 100644 index 0000000..e11ca07 --- /dev/null +++ b/002_练手例程/时序仿真/styles.css @@ -0,0 +1,684 @@ +* { + margin: 0; + padding: 0; + box-sizing: border-box; +} + +body { + font-family: 'Microsoft YaHei', sans-serif; + background-color: #f5f5f5; + color: #333; +} + +.container { + display: flex; + height: 100vh; + overflow: hidden; +} + +/* 侧边栏样式 */ +.sidebar { + width: 300px; + background-color: #fff; + border-right: 1px solid #ddd; + padding: 15px; + display: flex; + flex-direction: column; + overflow-y: auto; +} + +.sidebar h2, .sidebar h3 { + margin-bottom: 15px; + color: #333; + text-align: center; +} + +.sidebar h3 { + margin: 10px 0; + font-size: 16px; + border-bottom: 1px solid #eee; + padding-bottom: 5px; +} + +/* 图形库样式 */ +.shape-container { + margin-bottom: 20px; +} + +.shape-group { + margin-bottom: 15px; +} + +.shape-item { + padding: 10px; + border: 1px solid #ddd; + border-radius: 5px; + margin-bottom: 8px; + cursor: grab; + user-select: none; + background-color: #f9f9f9; + transition: all 0.2s; +} + +.shape-item:hover { + background-color: #e3f2fd; + border-color: #2196F3; +} + +.shape-item:active { + cursor: grabbing; +} + +/* 图形样式 */ +.start-shape { + width: 100%; + height: 40px; + background-color: #fff; + border: 2px solid #ff0000; + border-radius: 10px; + display: flex; + align-items: center; + justify-content: center; + font-size: 14px; + position: relative; + text-align: center; +} + +.start-shape::after { + content: ""; + position: absolute; + right: -6px; + top: 50%; + transform: translateY(-50%); + width: 12px; + height: 12px; + background-color: #ff0000; + border-radius: 50%; +} + +.process-shape { + width: 100%; + height: 40px; + background-color: #fff; + border: 2px solid #4CAF50; + border-radius: 10px; + display: flex; + align-items: center; + justify-content: center; + font-size: 14px; +} + +.transport-shape { + width: 80px; + height: 40px; + margin: 0 auto; + position: relative; + background-color: #fff; + border: none; + display: flex; + align-items: center; + justify-content: center; + font-size: 14px; +} + +.transport-shape::before { + content: ""; + position: absolute; + top: 0; + left: 0; + width: 100%; + height: 100%; + border: 2px solid #FF9800; + clip-path: polygon(50% 0%, 100% 50%, 50% 100%, 0% 50%); +} + +.endpoint-shape { + width: 100px; + height: 40px; + margin: 0 auto; + background-color: #fff; + border: 2px solid #9C27B0; + border-radius: 50%; + display: flex; + align-items: center; + justify-content: center; + font-size: 14px; +} + +/* 控制面板样式 */ +.control-panel { + display: flex; + flex-direction: column; + gap: 10px; + margin-bottom: 15px; + padding: 10px; + border: 1px solid #ddd; + border-radius: 5px; + background-color: #f9f9f9; +} + +.control-panel button { + padding: 8px 12px; + background-color: #4CAF50; + color: white; + border: none; + border-radius: 4px; + cursor: pointer; + transition: background-color 0.3s; +} + +.control-panel button:hover { + background-color: #45a049; +} + +#stop-simulation { + background-color: #f44336; +} + +#stop-simulation:hover { + background-color: #d32f2f; +} + +#reset-simulation { + background-color: #2196F3; +} + +#reset-simulation:hover { + background-color: #1976D2; +} + +.simulation-settings { + margin-top: 10px; + padding-top: 10px; + border-top: 1px solid #ddd; +} + +.project-actions { + margin-top: 10px; + padding-top: 10px; + border-top: 1px solid #ddd; + display: flex; + gap: 10px; +} + +.project-actions button { + flex: 1; + background-color: #673AB7; +} + +.project-actions button:hover { + background-color: #5E35B1; +} + +/* 仿真信息样式 */ +.simulation-info { + margin-top: 15px; + padding: 10px; + border: 1px solid #ddd; + border-radius: 5px; + background-color: #f9f9f9; +} + +#simulation-stats { + margin-top: 10px; + font-size: 14px; +} + +#simulation-stats div { + margin-bottom: 5px; +} + +#simulation-stats span { + font-weight: bold; + color: #FF5722; +} + +/* 主内容区域样式 */ +.main-content { + flex: 1; + display: flex; + flex-direction: column; + overflow: hidden; +} + +.canvas-container { + flex: 1; + position: relative; + background-color: #f1f1f1; + overflow: hidden; + background-image: linear-gradient(#ddd 1px, transparent 1px), + linear-gradient(90deg, #ddd 1px, transparent 1px); + background-size: 20px 20px; +} + +#flow-canvas { + width: 100%; + height: 100%; + cursor: grab; +} + +#flow-canvas:active { + cursor: grabbing; +} + +/* 状态栏样式 */ +.status-bar { + height: 30px; + display: flex; + justify-content: space-between; + align-items: center; + padding: 0 15px; + background-color: #f5f5f5; + border-top: 1px solid #ddd; +} + +#status-message { + font-size: 14px; + color: #666; +} + +#zoom-controls { + display: flex; + align-items: center; + gap: 5px; +} + +#zoom-controls button { + width: 24px; + height: 24px; + display: flex; + align-items: center; + justify-content: center; + background-color: #f1f1f1; + border: 1px solid #ddd; + border-radius: 3px; + cursor: pointer; +} + +#zoom-controls button:hover { + background-color: #e0e0e0; +} + +#zoom-level { + font-size: 14px; + color: #666; + width: 50px; + text-align: center; +} + +/* 模态框样式 */ +.modal { + display: none; + position: fixed; + z-index: 100; + left: 0; + top: 0; + width: 100%; + height: 100%; + background-color: rgba(0,0,0,0.5); +} + +.modal-content { + background-color: #fff; + margin: 10% auto; + padding: 20px; + border-radius: 5px; + width: 60%; + max-width: 600px; + max-height: 80vh; + overflow-y: auto; +} + +.close { + color: #aaa; + float: right; + font-size: 28px; + font-weight: bold; + cursor: pointer; +} + +.close:hover { + color: #333; +} + +.form-group { + margin-bottom: 15px; +} + +.form-group label { + display: block; + margin-bottom: 5px; + font-weight: bold; +} + +.form-group input, +.form-group select { + width: 100%; + padding: 8px; + border: 1px solid #ddd; + border-radius: 4px; +} + +.form-actions { + display: flex; + justify-content: flex-end; + gap: 10px; + margin-top: 20px; +} + +.form-actions button { + padding: 8px 15px; + border-radius: 4px; + cursor: pointer; +} + +.form-actions button[type="submit"] { + background-color: #4CAF50; + color: white; + border: none; +} + +.form-actions button[type="button"] { + background-color: #f1f1f1; + border: 1px solid #ddd; +} + +.delete-btn { + background-color: #f44336 !important; + color: white !important; +} + +.add-btn { + background-color: #4CAF50 !important; + color: white !important; + padding: 5px 10px; + border: none; + border-radius: 4px; + cursor: pointer; + margin-top: 10px; +} + +.step-item { + border: 1px solid #ddd; + border-radius: 4px; + padding: 10px; + margin-bottom: 10px; + position: relative; + background-color: #f9f9f9; +} + +.step-header { + display: flex; + justify-content: space-between; + align-items: center; + margin-bottom: 10px; +} + +.step-title { + font-weight: bold; +} + +.step-remove { + background-color: #f44336; + color: white; + border: none; + border-radius: 50%; + width: 24px; + height: 24px; + cursor: pointer; + display: flex; + align-items: center; + justify-content: center; + font-size: 14px; +} + +.step-content { + display: flex; + flex-wrap: wrap; + gap: 10px; +} + +.step-field { + flex: 1; + min-width: 100px; +} + +.steps-actions { + margin-top: 10px; + text-align: center; +} + +/* 画布上的图形和连接样式 */ +.flow-shape { + position: absolute; + cursor: move; + user-select: none; +} + +.flow-start { + width: 160px; + height: 80px; + background-color: white; + border: 2px solid #ff0000; + border-radius: 10px; + display: flex; + align-items: center; + justify-content: center; + position: relative; + text-align: center; + padding: 0; +} + +.flow-start::after { + content: ""; + position: absolute; + right: -6px; + top: 50%; + transform: translateY(-50%); + width: 12px; + height: 12px; + background-color: #ff0000; + border-radius: 50%; +} + +.flow-process { + width: 160px; + height: 80px; + background-color: white; + border: 2px solid #4CAF50; + border-radius: 10px; + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; +} + +.flow-transport { + width: 140px; + height: 80px; + background-color: white; + border: none; + transform: rotate(0deg); + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + position: relative; +} + +.flow-transport::before { + content: ""; + position: absolute; + top: 0; + left: 0; + width: 100%; + height: 100%; + border: 2px solid #FF9800; + clip-path: polygon(50% 0%, 100% 50%, 50% 100%, 0% 50%); +} + +.flow-endpoint { + width: 160px; + height: 80px; + background-color: white; + border: 2px solid #9C27B0; + border-radius: 40px; + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; +} + +.shape-title { + font-weight: bold; + margin-bottom: 5px; + max-width: 90%; + text-align: center; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.shape-info { + font-size: 12px; + color: #666; + margin-bottom: 2px; +} + +.shape-throughput { + font-size: 13px; + color: #FF5722; + font-weight: bold; +} + +.connection-point { + position: absolute; + width: 16px; + height: 16px; + background-color: #2196F3; + border-radius: 50%; + cursor: pointer; + z-index: 100; + transition: transform 0.2s, background-color 0.2s; +} + +.connection-point:hover { + transform: scale(1.3); + background-color: #1976D2; +} + +.connection-point.output { + right: 0; + top: 50%; + transform: translate(50%, -50%); +} + +.connection-point.input { + left: 0; + top: 50%; + transform: translate(-50%, -50%); +} + +.connection-helper { + position: absolute; + width: 24px; + height: 24px; + background-color: rgba(33, 150, 243, 0.3); + border-radius: 50%; + border: 2px solid #2196F3; + display: flex; + align-items: center; + justify-content: center; + color: white; + font-weight: bold; + cursor: pointer; + z-index: 10; + transform: translate(-50%, -50%); +} + +.connection-helper:hover { + background-color: rgba(33, 150, 243, 0.6); +} + +/* 连接线样式 */ +.connection-line { + stroke: #2196F3; + stroke-width: 2; + fill: none; +} + +.connection-arrow { + fill: #2196F3; +} + +.connection-label { + font-size: 12px; + fill: #333; + text-anchor: middle; + dominant-baseline: central; +} + +.connection-label-bg { + fill: white; + stroke: #ddd; + stroke-width: 1; + rx: 3; + ry: 3; +} + +/* 物料流动动画 */ +.material-particle { + fill: #FF9800; + stroke: #F57C00; + stroke-width: 1; +} + +/* 已保存项目列表样式 */ +#saved-projects-list { + list-style: none; + margin-top: 10px; +} + +#saved-projects-list li { + padding: 8px; + border: 1px solid #ddd; + border-radius: 4px; + margin-bottom: 5px; + cursor: pointer; + display: flex; + justify-content: space-between; + align-items: center; +} + +#saved-projects-list li:hover { + background-color: #e3f2fd; +} + +#saved-projects-list .project-actions { + display: flex; + gap: 5px; + border: none; + margin: 0; + padding: 0; +} + +#saved-projects-list .project-actions button { + padding: 3px 6px; + font-size: 12px; +} + +/* 响应式设计 */ +@media (max-width: 768px) { + .container { + flex-direction: column; + } + + .sidebar { + width: 100%; + height: 300px; + } + + .modal-content { + width: 90%; + } +} diff --git a/002_练手例程/机械设计云平台.html b/002_练手例程/机械设计云平台.html new file mode 100644 index 0000000..76832e2 --- /dev/null +++ b/002_练手例程/机械设计云平台.html @@ -0,0 +1,699 @@ + + + + + + 机械设计云平台 + + + + + + + +
+
+
+ +
+ +
+ +
+
+

功能区域

+

Hello 星程技术

+
+
+ +
+ 网络状态: 在线 | 系统版本: V1.0.0 | 开发者: 星程技术 +
+
+ + + + + + + + + + + + + diff --git a/Conda命令.txt b/Conda命令.txt new file mode 100644 index 0000000..1f9f96a --- /dev/null +++ b/Conda命令.txt @@ -0,0 +1,5 @@ +查看所有已创建的虚拟环境:conda env list +进入(激活)指定环境:conda activate 环境名 +退出当前环境:conda deactivate +创建新环境:conda create --name 环境名 python=版本号 +删除环境:conda remove --name 环境名 --all diff --git a/Django命令.txt b/Django命令.txt new file mode 100644 index 0000000..6fe28af --- /dev/null +++ b/Django命令.txt @@ -0,0 +1,6 @@ +安装django:pip install django +显示帮助:django-admin --help +创建新项目:django-admin startproject 项目名称 +显示启动项目帮助:python manage.py --help +启动项目:python manage.py runserver 端口号 +创建项目后应用数据库迁移:python manage.py migrate diff --git a/Git命令.txt b/Git命令.txt new file mode 100644 index 0000000..7652fa9 --- /dev/null +++ b/Git命令.txt @@ -0,0 +1,2 @@ +设置 Git 提交的用户名:git config --global user.name "你的用户名" +设置 Git 提交的邮箱地址:git config --global user.email "你的邮箱地址" \ No newline at end of file diff --git a/LICENSE b/LICENSE index e901570..9f12471 100644 --- a/LICENSE +++ b/LICENSE @@ -208,8 +208,8 @@ If you develop a new program, and you want it to be of the greatest possible use To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the “copyright” line and a pointer to where the full notice is found. - 001-Study - Copyright (C) 2025 XCSERVER + Python-Project + Copyright (C) 2024 XC-Project This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. @@ -221,7 +221,7 @@ Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: - 001-Study Copyright (C) 2025 XCSERVER + Python-Project Copyright (C) 2024 XC-Project This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. diff --git a/Pycharm插件.txt b/Pycharm插件.txt new file mode 100644 index 0000000..ef26c91 --- /dev/null +++ b/Pycharm插件.txt @@ -0,0 +1,7 @@ +1、翻译插件 +translation +2、网页预览 +live edit +3、AI辅助 +通义灵码 +4、 \ No newline at end of file diff --git a/README.md b/README.md index fe259f9..52a827a 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,44 @@ # 001-Study -代码学习 \ No newline at end of file +学习用仓库 + +项目结构(前后端分离Django+HTML+CSS+JavaScript): + +我们的项目采用了**前后端分离架构**,即前端和后端在开发和部署时是完全独立的。在使用Django作为后端,HTML、CSS、JavaScript作为前端的项目中,合理的项目结构可以帮助你更好地管理代码,保护后端逻辑,并方便后续的功能扩展。以下是一个推荐的项目结构和配置步骤: + +``` +my_project/ # 项目根目录 +│ +├── backend/ # 后端目录 +│ ├── manage.py # Django管理脚本 +│ ├── my_project/ # Django项目配置目录 +│ │ ├── __init__.py +│ │ ├── settings.py # Django设置文件 +│ │ ├── urls.py # URL路由配置 +│ │ ├── wsgi.py # WSGI入口 +│ │ └── asgi.py # ASGI入口 +│ ├── app1/ # 功能模块1的Django应用 +│ │ ├── migrations/ # 数据库迁移文件 +│ │ ├── __init__.py +│ │ ├── admin.py # 管理员界面配置 +│ │ ├── apps.py # 应用配置 +│ │ ├── models.py # 数据模型 +│ │ ├── tests.py # 测试文件 +│ │ ├── views.py # 视图逻辑 +│ │ └── urls.py # 应用的URL配置 +│ └── app2/ # 功能模块2的Django应用 +│ ├── ... # 同上 +│ +├── frontend/ # 前端目录 +│ ├── app1/ # 功能模块1的前端 +│ │ ├── index.html # HTML文件 +│ │ ├── style.css # CSS文件 +│ │ └── script.js # JavaScript文件 +│ └── app2/ # 功能模块2的前端 +│ ├── ... # 同上 +│ +└── static/ # 静态文件目录 + ├── css/ # 全局CSS文件 + ├── js/ # 全局JavaScript文件 + └── images/ # 图片资源 +```