feat(项目十): 新增综合章节源码、章节正文与教材 docx
- textbook/main.c:单文件控制台程序(约 400 行、13 个函数),覆盖项目一~九知识点 - textbook/项目十-章节正文.md:章节正文源稿 - textbook/figs:8 张控制台运行结果截图(真实回显) - textbook/tools:截图与 docx 生成脚本 - 10.16C语言程序设计教材初稿 - 项目十.docx:按原稿样式生成的综合章节(28 页)
No files matched your search
@@ -0,0 +1,70 @@
|
||||
# 项目十 融会贯通——智能家居中控系统综合实战(教材配套源码)
|
||||
|
||||
本目录是教材《C语言程序设计项目化教程——智能家居控制系统开发实战》**项目十(综合章节)**的配套材料:
|
||||
单文件控制台程序、章节正文、运行结果插图,以及生成这些产物的脚本。
|
||||
|
||||
## 目录结构
|
||||
|
||||
```
|
||||
textbook/
|
||||
├── main.c # 项目十完整源码(单文件,约 400 行,13 个函数)
|
||||
├── 项目十-章节正文.md # 章节正文源稿(docx 由此生成)
|
||||
├── figs/ # 8 张运行结果截图(控制台真实回显)
|
||||
│ ├── fig10-1.png … fig10-8.png
|
||||
└── tools/
|
||||
├── gen_screens.py # 按脚本喂输入 → 回显注入 → 渲染控制台截图
|
||||
└── build_chapter_docx.py # 以原稿为模板生成 项目十.docx
|
||||
```
|
||||
|
||||
章节成品:仓库根目录 `10.16C语言程序设计教材初稿 - 项目十.docx`。
|
||||
|
||||
## 编译与运行
|
||||
|
||||
Windows 下用 MinGW-w64(CLion 自带即可):
|
||||
|
||||
```powershell
|
||||
cd textbook
|
||||
D:\CLion\bin\mingw\bin\gcc.exe -std=c17 -Wall -Wextra -o main.exe main.c
|
||||
./main.exe
|
||||
```
|
||||
|
||||
或用 Visual Studio 2026:新建空项目,添加 `main.c`,`Ctrl+F5` 运行。
|
||||
|
||||
程序启动后进入主菜单,输入 0~8 选择功能:
|
||||
|
||||
```
|
||||
1.查看设备台账 2.控制设备 3.状态标志位管理 4.场景联动
|
||||
5.统计报表 6.保存配置 7.加载配置 8.查看运行日志
|
||||
0.退出系统
|
||||
```
|
||||
|
||||
运行时会在当前目录生成 `devices.cfg`(设备台账)与 `smart_home.log`(运行日志),
|
||||
这两个文件是程序产物,不入库。
|
||||
|
||||
## 覆盖的教材知识点
|
||||
|
||||
| 任务 | 功能 | 知识点 | 对应项目 |
|
||||
|---|---|---|---|
|
||||
| 任务一 | 设备台账、主菜单 | 结构体数组、typedef、`do-while`+`switch`、格式化输出 | 一 / 二 / 五 / 八 |
|
||||
| 任务二 | 设备控制、状态标志位 | 顺序查找、参数校验、位掩码(`\|`、`&~`、`^`、`&`)、循环移位 | 三 / 四 / 九 |
|
||||
| 任务三 | 场景联动、统计报表 | 批量遍历、多分支级联、求和/均值/最值、指针出参 | 二 / 四 / 五 / 七 |
|
||||
| 任务四 | 配置持久化、运行日志 | `fopen` 模式、`fprintf`/`fscanf`、`fgets`、错误处理 | 九 |
|
||||
|
||||
## 重新生成章节文档
|
||||
|
||||
```powershell
|
||||
# 1) 编译程序(截图脚本会调用 main.exe / case10_1.exe)
|
||||
gcc -std=c17 -Wall -Wextra -o main.exe main.c
|
||||
|
||||
# 2) 重新截图(可选)
|
||||
python tools/gen_screens.py
|
||||
|
||||
# 3) 由 Markdown + 插图生成 docx
|
||||
python tools/build_chapter_docx.py
|
||||
```
|
||||
|
||||
`build_chapter_docx.py` 会打开同目录的教材原稿作为**样式模板**(Heading 1/2/4、`项目引入`、
|
||||
`HTML Preformatted`、`Table Grid` 全部继承),清空正文后按章节内容重新排版,
|
||||
因此成品的字体、行距、标题层级与原稿完全一致。
|
||||
|
||||
脚本依赖:Python 3、`python-docx`、`Pillow`。
|
||||
|
After Width: | Height: | Size: 9.8 KiB |
|
After Width: | Height: | Size: 29 KiB |
|
After Width: | Height: | Size: 28 KiB |
|
After Width: | Height: | Size: 29 KiB |
|
After Width: | Height: | Size: 31 KiB |
|
After Width: | Height: | Size: 17 KiB |
|
After Width: | Height: | Size: 25 KiB |
|
After Width: | Height: | Size: 3.9 KiB |
@@ -0,0 +1,436 @@
|
||||
#define _CRT_SECURE_NO_WARNINGS
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
#define MAX_DEVICES 8
|
||||
#define CONFIG_FILE "devices.cfg"
|
||||
#define LOG_FILE "smart_home.log"
|
||||
|
||||
/* 状态标志位:一个字节同时记录 4 种状态 */
|
||||
#define FLAG_ONLINE 0x01 /* bit0 在线:0000 0001 */
|
||||
#define FLAG_FAULT 0x02 /* bit1 故障:0000 0010 */
|
||||
#define FLAG_LOCKED 0x04 /* bit2 锁定:0000 0100 */
|
||||
#define FLAG_SAVING 0x08 /* bit3 节能:0000 1000 */
|
||||
|
||||
/* 设备档案:把一台设备的全部信息封装成一个整体 */
|
||||
typedef struct {
|
||||
int id; /* 设备编号 */
|
||||
char name[20]; /* 设备名称 */
|
||||
int type; /* 0灯 1空调 2门锁 3传感器 */
|
||||
int on; /* 0关闭 1开启 */
|
||||
int level; /* 亮度 0~100 或 温度 16~30 */
|
||||
unsigned char flags; /* 状态标志位 */
|
||||
} Device;
|
||||
|
||||
Device devices[MAX_DEVICES]; /* 设备台账:结构体数组 */
|
||||
int device_count = 0; /* 台账中的设备数量 */
|
||||
|
||||
void init_devices(void);
|
||||
void show_devices(void);
|
||||
int find_device(int id);
|
||||
void write_log(const char *text);
|
||||
void show_log(void);
|
||||
void control_device(void);
|
||||
void manage_flags(void);
|
||||
void run_scene(void);
|
||||
void calc_stats(int *on_count, int *avg_level,
|
||||
int *max_level, int *min_level);
|
||||
void show_report(void);
|
||||
void save_config(void);
|
||||
void load_config(void);
|
||||
void print_menu(void);
|
||||
|
||||
int main(void)
|
||||
{
|
||||
int choice;
|
||||
init_devices();
|
||||
write_log("系统启动,设备台账初始化完成");
|
||||
|
||||
do {
|
||||
print_menu();
|
||||
printf("请选择功能(0-8):");
|
||||
(void)scanf("%d", &choice);
|
||||
printf("\n");
|
||||
|
||||
switch (choice) {
|
||||
case 1:
|
||||
show_devices();
|
||||
break;
|
||||
case 2:
|
||||
control_device();
|
||||
break;
|
||||
case 3:
|
||||
manage_flags();
|
||||
break;
|
||||
case 4:
|
||||
run_scene();
|
||||
break;
|
||||
case 5:
|
||||
show_report();
|
||||
break;
|
||||
case 6:
|
||||
save_config();
|
||||
break;
|
||||
case 7:
|
||||
load_config();
|
||||
break;
|
||||
case 8:
|
||||
show_log();
|
||||
break;
|
||||
case 0:
|
||||
write_log("用户退出系统");
|
||||
printf("感谢使用智联·悦居智能家居中控系统,再见!\n");
|
||||
break;
|
||||
default:
|
||||
printf("输入错误:请输入 0-8 之间的数字。\n");
|
||||
break;
|
||||
}
|
||||
} while (choice != 0);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* 初始化设备台账 */
|
||||
void init_devices(void)
|
||||
{
|
||||
Device tpl[] = {
|
||||
{1, "客厅主灯", 0, 1, 80, FLAG_ONLINE},
|
||||
{2, "卧室壁灯", 0, 0, 0, FLAG_ONLINE},
|
||||
{3, "客厅空调", 1, 1, 26, FLAG_ONLINE},
|
||||
{4, "智能门锁", 2, 1, 0, FLAG_ONLINE | FLAG_LOCKED},
|
||||
{5, "温湿度传感器", 3, 1, 25, FLAG_ONLINE},
|
||||
{6, "烟感传感器", 3, 1, 0, FLAG_ONLINE | FLAG_FAULT}
|
||||
};
|
||||
int i;
|
||||
int n = (int)(sizeof(tpl) / sizeof(tpl[0]));
|
||||
|
||||
device_count = n;
|
||||
for (i = 0; i < n; i++) {
|
||||
devices[i] = tpl[i];
|
||||
}
|
||||
}
|
||||
|
||||
/* 显示设备台账 */
|
||||
void show_devices(void)
|
||||
{
|
||||
int i;
|
||||
const char *type_name[4] = {"灯光", "空调", "门锁", "传感器"};
|
||||
|
||||
printf("-------------------- 设备台账 --------------------\n");
|
||||
for (i = 0; i < device_count; i++) {
|
||||
printf("[%d] %s | 类型:%s | 状态:%s | 参数:%d | 标志:0x%02X\n",
|
||||
devices[i].id, devices[i].name, type_name[devices[i].type],
|
||||
devices[i].on ? "开启" : "关闭",
|
||||
devices[i].level, devices[i].flags);
|
||||
}
|
||||
printf("--------------------------------------------------\n");
|
||||
printf("共 %d 台设备\n", device_count);
|
||||
}
|
||||
|
||||
/* 按编号查找设备,返回数组下标,找不到返回 -1 */
|
||||
int find_device(int id)
|
||||
{
|
||||
int i;
|
||||
for (i = 0; i < device_count; i++) {
|
||||
if (devices[i].id == id) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* 写运行日志(追加方式) */
|
||||
void write_log(const char *text)
|
||||
{
|
||||
FILE *fp = fopen(LOG_FILE, "a");
|
||||
if (fp == NULL) {
|
||||
printf("日志文件打开失败!\n");
|
||||
return;
|
||||
}
|
||||
fprintf(fp, "%s\n", text);
|
||||
fclose(fp);
|
||||
}
|
||||
|
||||
/* 查看运行日志 */
|
||||
void show_log(void)
|
||||
{
|
||||
FILE *fp = fopen(LOG_FILE, "r");
|
||||
char line[128];
|
||||
int count = 0;
|
||||
|
||||
if (fp == NULL) {
|
||||
printf("暂无日志记录。\n");
|
||||
return;
|
||||
}
|
||||
printf("-------------------- 运行日志 --------------------\n");
|
||||
while (fgets(line, sizeof(line), fp) != NULL) {
|
||||
printf("%s", line);
|
||||
count++;
|
||||
}
|
||||
fclose(fp);
|
||||
printf("------------------ 共 %d 条记录 ------------------\n", count);
|
||||
}
|
||||
|
||||
/* 控制设备:开关与参数调节 */
|
||||
void control_device(void)
|
||||
{
|
||||
int id, idx, op, value;
|
||||
|
||||
printf("请输入设备编号:");
|
||||
(void)scanf("%d", &id);
|
||||
idx = find_device(id);
|
||||
if (idx < 0) {
|
||||
printf("查找失败:编号 %d 的设备不存在。\n", id);
|
||||
return;
|
||||
}
|
||||
printf("当前设备:%s,状态:%s,参数:%d\n",
|
||||
devices[idx].name, devices[idx].on ? "开启" : "关闭",
|
||||
devices[idx].level);
|
||||
printf("1.开启 2.关闭 3.调节参数\n请选择操作:");
|
||||
(void)scanf("%d", &op);
|
||||
|
||||
if (op == 1) {
|
||||
devices[idx].on = 1;
|
||||
printf("操作完成:%s 已开启。\n", devices[idx].name);
|
||||
} else if (op == 2) {
|
||||
devices[idx].on = 0;
|
||||
printf("操作完成:%s 已关闭。\n", devices[idx].name);
|
||||
} else if (op == 3) {
|
||||
printf("请输入参数值:");
|
||||
(void)scanf("%d", &value);
|
||||
if (devices[idx].type == 0 && (value < 0 || value > 100)) {
|
||||
printf("参数越界:灯光亮度应在 0~100 之间。\n");
|
||||
return;
|
||||
}
|
||||
if (devices[idx].type == 1 && (value < 16 || value > 30)) {
|
||||
printf("参数越界:空调温度应在 16~30 之间。\n");
|
||||
return;
|
||||
}
|
||||
devices[idx].level = value;
|
||||
printf("操作完成:%s 参数已设为 %d。\n", devices[idx].name, value);
|
||||
} else {
|
||||
printf("操作非法:请输入 1~3。\n");
|
||||
return;
|
||||
}
|
||||
write_log("执行设备控制操作");
|
||||
}
|
||||
|
||||
/* 状态标志位管理:置位、清零、取反、查询、循环移位 */
|
||||
void manage_flags(void)
|
||||
{
|
||||
int id, idx, op, bit;
|
||||
unsigned char mask;
|
||||
|
||||
printf("请输入设备编号:");
|
||||
(void)scanf("%d", &id);
|
||||
idx = find_device(id);
|
||||
if (idx < 0) {
|
||||
printf("查找失败:编号 %d 的设备不存在。\n", id);
|
||||
return;
|
||||
}
|
||||
printf("设备 %s 当前标志:0x%02X\n",
|
||||
devices[idx].name, devices[idx].flags);
|
||||
printf("1.置位 2.清零 3.取反 4.查询 5.循环左移\n请选择操作:");
|
||||
(void)scanf("%d", &op);
|
||||
|
||||
if (op == 1 || op == 2 || op == 3) {
|
||||
printf("请选择标志(1在线 2故障 3锁定 4节能):");
|
||||
(void)scanf("%d", &bit);
|
||||
if (bit < 1 || bit > 4) {
|
||||
printf("标志选择非法。\n");
|
||||
return;
|
||||
}
|
||||
mask = (unsigned char)(1 << (bit - 1));
|
||||
if (op == 1) {
|
||||
devices[idx].flags |= mask; /* 置位 */
|
||||
} else if (op == 2) {
|
||||
devices[idx].flags &= (unsigned char)~mask; /* 清零 */
|
||||
} else {
|
||||
devices[idx].flags ^= mask; /* 取反 */
|
||||
}
|
||||
printf("操作完成,新标志:0x%02X\n", devices[idx].flags);
|
||||
} else if (op == 4) {
|
||||
printf("在线:%s 故障:%s 锁定:%s 节能:%s\n",
|
||||
(devices[idx].flags & FLAG_ONLINE) ? "是" : "否",
|
||||
(devices[idx].flags & FLAG_FAULT) ? "是" : "否",
|
||||
(devices[idx].flags & FLAG_LOCKED) ? "是" : "否",
|
||||
(devices[idx].flags & FLAG_SAVING) ? "是" : "否");
|
||||
} else if (op == 5) {
|
||||
devices[idx].flags = (unsigned char)((devices[idx].flags << 1) |
|
||||
(devices[idx].flags >> 7));
|
||||
printf("循环左移完成,新标志:0x%02X\n", devices[idx].flags);
|
||||
} else {
|
||||
printf("操作非法:请输入 1~5。\n");
|
||||
return;
|
||||
}
|
||||
write_log("执行状态标志位操作");
|
||||
}
|
||||
|
||||
/* 场景联动:一次操作批量控制多台设备 */
|
||||
void run_scene(void)
|
||||
{
|
||||
int scene, i;
|
||||
|
||||
printf("1.回家模式 2.离家模式 3.睡眠模式 4.节能模式\n请选择场景:");
|
||||
(void)scanf("%d", &scene);
|
||||
if (scene < 1 || scene > 4) {
|
||||
printf("场景选择非法。\n");
|
||||
return;
|
||||
}
|
||||
for (i = 0; i < device_count; i++) {
|
||||
if (scene == 1) { /* 回家:开灯、开空调、解锁 */
|
||||
if (devices[i].type == 0) {
|
||||
devices[i].on = 1;
|
||||
devices[i].level = 70;
|
||||
}
|
||||
if (devices[i].type == 1) {
|
||||
devices[i].on = 1;
|
||||
devices[i].level = 26;
|
||||
}
|
||||
if (devices[i].type == 2) {
|
||||
devices[i].flags &= (unsigned char)~FLAG_LOCKED;
|
||||
}
|
||||
} else if (scene == 2) { /* 离家:全关、上锁 */
|
||||
devices[i].on = 0;
|
||||
if (devices[i].type == 2) {
|
||||
devices[i].flags |= FLAG_LOCKED;
|
||||
}
|
||||
} else if (scene == 3) { /* 睡眠:关灯、空调 26、上锁 */
|
||||
if (devices[i].type == 0) {
|
||||
devices[i].on = 0;
|
||||
}
|
||||
if (devices[i].type == 1) {
|
||||
devices[i].on = 1;
|
||||
devices[i].level = 26;
|
||||
}
|
||||
if (devices[i].type == 2) {
|
||||
devices[i].flags |= FLAG_LOCKED;
|
||||
}
|
||||
} else { /* 节能:灯光降亮、置节能位 */
|
||||
if (devices[i].type == 0) {
|
||||
devices[i].level = 30;
|
||||
devices[i].flags |= FLAG_SAVING;
|
||||
}
|
||||
}
|
||||
}
|
||||
write_log("执行场景联动");
|
||||
printf("场景执行完成,可查看设备台账确认结果。\n");
|
||||
}
|
||||
|
||||
/* 统计计算:通过指针参数一次返回 4 个结果 */
|
||||
void calc_stats(int *on_count, int *avg_level,
|
||||
int *max_level, int *min_level)
|
||||
{
|
||||
int i, sum = 0, count = 0;
|
||||
|
||||
*on_count = 0;
|
||||
*avg_level = 0;
|
||||
*max_level = 0;
|
||||
*min_level = 100;
|
||||
for (i = 0; i < device_count; i++) {
|
||||
if (devices[i].on == 1) {
|
||||
(*on_count)++; /* 开机台数 */
|
||||
}
|
||||
if (devices[i].type == 0) { /* 只统计灯光亮度 */
|
||||
sum += devices[i].level;
|
||||
count++;
|
||||
if (devices[i].level > *max_level) {
|
||||
*max_level = devices[i].level;
|
||||
}
|
||||
if (devices[i].level < *min_level) {
|
||||
*min_level = devices[i].level;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (count > 0) {
|
||||
*avg_level = sum / count;
|
||||
}
|
||||
}
|
||||
|
||||
/* 统计报表 */
|
||||
void show_report(void)
|
||||
{
|
||||
int on_count, avg_level, max_level, min_level;
|
||||
int type_count[4] = {0, 0, 0, 0};
|
||||
int i, online = 0;
|
||||
|
||||
calc_stats(&on_count, &avg_level, &max_level, &min_level);
|
||||
for (i = 0; i < device_count; i++) {
|
||||
type_count[devices[i].type]++;
|
||||
if (devices[i].flags & FLAG_ONLINE) {
|
||||
online++;
|
||||
}
|
||||
}
|
||||
printf("-------------------- 统计报表 --------------------\n");
|
||||
printf("设备总数:%d 台,开机:%d 台,在线:%d 台\n",
|
||||
device_count, on_count, online);
|
||||
printf("灯光 %d 台,空调 %d 台,门锁 %d 台,传感器 %d 台\n",
|
||||
type_count[0], type_count[1], type_count[2], type_count[3]);
|
||||
printf("灯光亮度:平均 %d,最高 %d,最低 %d\n",
|
||||
avg_level, max_level, min_level);
|
||||
printf("-------------------------------------------------\n");
|
||||
}
|
||||
|
||||
/* 保存配置到文本文件 */
|
||||
void save_config(void)
|
||||
{
|
||||
FILE *fp = fopen(CONFIG_FILE, "w");
|
||||
int i;
|
||||
|
||||
if (fp == NULL) {
|
||||
printf("配置文件打开失败,保存未完成!\n");
|
||||
return;
|
||||
}
|
||||
fprintf(fp, "%d\n", device_count);
|
||||
for (i = 0; i < device_count; i++) {
|
||||
fprintf(fp, "%d %s %d %d %d %d\n", devices[i].id, devices[i].name,
|
||||
devices[i].type, devices[i].on, devices[i].level,
|
||||
devices[i].flags);
|
||||
}
|
||||
fclose(fp);
|
||||
write_log("保存设备配置");
|
||||
printf("保存成功:%d 台设备已写入 %s。\n", device_count, CONFIG_FILE);
|
||||
}
|
||||
|
||||
/* 从文本文件加载配置 */
|
||||
void load_config(void)
|
||||
{
|
||||
FILE *fp = fopen(CONFIG_FILE, "r");
|
||||
int i, n;
|
||||
|
||||
if (fp == NULL) {
|
||||
printf("配置文件不存在,请先执行保存操作。\n");
|
||||
return;
|
||||
}
|
||||
if (fscanf(fp, "%d", &n) != 1 || n > MAX_DEVICES) {
|
||||
printf("配置文件格式错误,加载失败。\n");
|
||||
fclose(fp);
|
||||
return;
|
||||
}
|
||||
for (i = 0; i < n; i++) {
|
||||
int flags_value;
|
||||
if (fscanf(fp, "%d %19s %d %d %d %d", &devices[i].id,
|
||||
devices[i].name, &devices[i].type, &devices[i].on,
|
||||
&devices[i].level, &flags_value) != 6) {
|
||||
break;
|
||||
}
|
||||
devices[i].flags = (unsigned char)flags_value;
|
||||
}
|
||||
device_count = i;
|
||||
fclose(fp);
|
||||
write_log("加载设备配置");
|
||||
printf("加载成功:已从 %s 读入 %d 台设备。\n",
|
||||
CONFIG_FILE, device_count);
|
||||
}
|
||||
|
||||
/* 主菜单 */
|
||||
void print_menu(void)
|
||||
{
|
||||
printf("\n========== 智联·悦居 智能家居中控系统 ==========\n");
|
||||
printf(" 1.查看设备台账 2.控制设备\n");
|
||||
printf(" 3.状态标志位管理 4.场景联动\n");
|
||||
printf(" 5.统计报表 6.保存配置\n");
|
||||
printf(" 7.加载配置 8.查看运行日志\n");
|
||||
printf(" 0.退出系统\n");
|
||||
printf("================================================\n");
|
||||
}
|
||||
@@ -0,0 +1,405 @@
|
||||
"""Build the 项目十 chapter DOCX using the original textbook as a style template."""
|
||||
import os
|
||||
import re
|
||||
|
||||
from docx import Document
|
||||
from docx.enum.table import WD_TABLE_ALIGNMENT
|
||||
from docx.enum.text import WD_ALIGN_PARAGRAPH
|
||||
from docx.oxml import OxmlElement
|
||||
from docx.oxml.ns import qn
|
||||
from docx.shared import Inches, Pt, RGBColor
|
||||
|
||||
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # textbook/
|
||||
PROJECT_DIR = os.path.dirname(BASE_DIR) # 仓库根目录
|
||||
FIG_DIR = os.path.join(BASE_DIR, "figs")
|
||||
SRC_DOCX = os.path.join(PROJECT_DIR, "10.16C语言程序设计教材初稿 - 项目版.docx")
|
||||
OUT_DOCX = os.path.join(PROJECT_DIR, "10.16C语言程序设计教材初稿 - 项目十.docx")
|
||||
MD = os.path.join(BASE_DIR, "项目十-章节正文.md")
|
||||
|
||||
FIG_CAPTIONS = {
|
||||
"10-1": ("fig10-1.png", "设备台账运行结果"),
|
||||
"10-2": ("fig10-2.png", "主菜单运行结果"),
|
||||
"10-3": ("fig10-3.png", "设备控制运行结果"),
|
||||
"10-4": ("fig10-4.png", "状态标志位操作运行结果"),
|
||||
"10-5": ("fig10-5.png", "场景联动运行结果"),
|
||||
"10-6": ("fig10-6.png", "统计报表运行结果"),
|
||||
"10-7": ("fig10-7.png", "配置保存与加载运行结果"),
|
||||
"10-8": ("fig10-8.png", "运行日志查看结果"),
|
||||
}
|
||||
|
||||
ASSESS_ROWS = [
|
||||
("一、知识掌握(40 分)", "一、知识掌握(40 分)", "", "", ""),
|
||||
("结构体与结构体数组", "能正确定义设备结构体、声明结构体数组并初始化", "", "", ""),
|
||||
("菜单与分支", "能写出 do-while + switch 菜单框架,正确使用 break、default", "", "", ""),
|
||||
("数组与统计", "能完成求和、均值、最值、分类计数的代码编写", "", "", ""),
|
||||
("指针出参", "能说明“为什么统计函数要用指针参数”,并正确调用", "", "", ""),
|
||||
("位运算", "能写出置位、清零、取反、取位、循环移位的表达式", "", "", ""),
|
||||
("文件操作", "能正确选择 \"r\"/\"w\"/\"a\" 模式,并检查 fopen 返回值", "", "", ""),
|
||||
("二、技能应用(40 分)", "二、技能应用(40 分)", "", "", ""),
|
||||
("系统集成", "九个菜单项全部可用,功能之间数据一致", "", "", ""),
|
||||
("数据持久化", "保存后重启能完整恢复台账", "", "", ""),
|
||||
("异常处理", "非法编号、越界参数、文件缺失均有提示且不崩溃", "", "", ""),
|
||||
("运行验证", "能独立完成“改参数→保存→重启→加载”的全流程演示", "", "", ""),
|
||||
("三、学习素养(20 分)", "三、学习素养(20 分)", "", "", ""),
|
||||
("代码规范", "缩进统一、命名清晰、关键语句有中文注释", "", "", ""),
|
||||
("调试能力", "能定位并修正至少一处自己引入的逻辑错误", "", "", ""),
|
||||
("文档习惯", "实训报告包含功能清单、测试用例与运行截图", "", "", ""),
|
||||
("总分", "自评 ______ 互评 ______ 教师 ______", "", "", ""),
|
||||
]
|
||||
|
||||
|
||||
def clear_body(doc):
|
||||
body = doc.element.body
|
||||
sect = body.find(qn("w:sectPr"))
|
||||
for child in list(body):
|
||||
if child is sect:
|
||||
continue
|
||||
body.remove(child)
|
||||
|
||||
|
||||
|
||||
PPR_AFTER_SNAP = {"spacing", "ind", "contextualSpacing", "mirrorIndents",
|
||||
"suppressOverlap", "jc", "textDirection", "textAlignment",
|
||||
"textboxTightWrap", "outlineLvl", "divId", "cnfStyle",
|
||||
"rPr", "sectPr", "pPrChange"}
|
||||
|
||||
|
||||
def no_grid(par):
|
||||
"""Disable snap-to-grid so line spacing is not doubled by the document grid."""
|
||||
pPr = par._p.get_or_add_pPr()
|
||||
if pPr.find(qn("w:snapToGrid")) is not None:
|
||||
return par
|
||||
el = OxmlElement("w:snapToGrid")
|
||||
el.set(qn("w:val"), "0")
|
||||
for child in list(pPr):
|
||||
name = child.tag.split("}")[1]
|
||||
if name in PPR_AFTER_SNAP:
|
||||
child.addprevious(el)
|
||||
return par
|
||||
pPr.append(el)
|
||||
return par
|
||||
|
||||
def add_runs(par, text, bold=False):
|
||||
"""Add text honouring **bold** and `code` spans."""
|
||||
for tok in re.split(r"(\*\*.+?\*\*|`[^`]+`)", text):
|
||||
if not tok:
|
||||
continue
|
||||
if tok.startswith("**") and tok.endswith("**") and len(tok) > 4:
|
||||
run = par.add_run(tok[2:-2])
|
||||
run.bold = True
|
||||
elif tok.startswith("`") and tok.endswith("`") and len(tok) > 2:
|
||||
run = par.add_run(tok[1:-1])
|
||||
run.font.name = "Consolas"
|
||||
run._element.rPr.rFonts.set(qn("w:eastAsia"), "宋体")
|
||||
run.font.size = Pt(10)
|
||||
else:
|
||||
run = par.add_run(tok)
|
||||
run.bold = bold
|
||||
run._element.set(qn("xml:space"), "preserve")
|
||||
|
||||
|
||||
def body_par(doc, text, indent=True):
|
||||
if text.startswith("- "):
|
||||
p = doc.add_paragraph(style="Normal")
|
||||
pf = p.paragraph_format
|
||||
pf.left_indent = Inches(0.32)
|
||||
pf.first_line_indent = Inches(-0.18)
|
||||
add_runs(p, "· " + text[2:])
|
||||
return p
|
||||
p = doc.add_paragraph(style="Normal")
|
||||
add_runs(p, text)
|
||||
return p
|
||||
|
||||
|
||||
def caption_par(doc, text, bold=True):
|
||||
p = doc.add_paragraph(style="Normal")
|
||||
p.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
||||
p.paragraph_format.keep_with_next = True
|
||||
for run in []:
|
||||
pass
|
||||
no_grid(p)
|
||||
r = p.add_run(text)
|
||||
r.bold = bold
|
||||
r.font.name = "Times New Roman"
|
||||
r._element.rPr.rFonts.set(qn("w:eastAsia"), "宋体")
|
||||
return p
|
||||
|
||||
|
||||
|
||||
def harden_table(table, header=True):
|
||||
for ri, row in enumerate(table.rows):
|
||||
trPr = row._tr.get_or_add_trPr()
|
||||
if trPr.find(qn("w:cantSplit")) is None:
|
||||
trPr.append(OxmlElement("w:cantSplit"))
|
||||
if header and ri == 0 and trPr.find(qn("w:tblHeader")) is None:
|
||||
trPr.append(OxmlElement("w:tblHeader"))
|
||||
|
||||
def add_table(doc, rows, header=True):
|
||||
cols = max(len(r) for r in rows)
|
||||
table = doc.add_table(rows=len(rows), cols=cols)
|
||||
table.style = "Table Grid"
|
||||
table.alignment = WD_TABLE_ALIGNMENT.CENTER
|
||||
for ri, row in enumerate(rows):
|
||||
for ci in range(cols):
|
||||
cell = table.cell(ri, ci)
|
||||
text = row[ci] if ci < len(row) else ""
|
||||
text = text.replace("`", "").replace("**", "")
|
||||
par = cell.paragraphs[0]
|
||||
par.alignment = WD_ALIGN_PARAGRAPH.CENTER if (ri == 0 or header and ri == 0) else WD_ALIGN_PARAGRAPH.LEFT
|
||||
run = par.add_run(text)
|
||||
run.font.size = Pt(10)
|
||||
run.font.name = "宋体"
|
||||
run._element.rPr.rFonts.set(qn("w:eastAsia"), "宋体")
|
||||
if ri == 0 and header:
|
||||
run.bold = True
|
||||
harden_table(table, header=header)
|
||||
doc.add_paragraph(style="Normal")
|
||||
return table
|
||||
|
||||
|
||||
def add_assessment(doc):
|
||||
cols = 5
|
||||
table = doc.add_table(rows=len(ASSESS_ROWS) + 2, cols=cols)
|
||||
table.style = "Table Grid"
|
||||
table.alignment = WD_TABLE_ALIGNMENT.CENTER
|
||||
|
||||
head = table.cell(0, 0).merge(table.cell(0, 4))
|
||||
head.paragraphs[0].add_run("姓名:____________ 所在小组:____________ 日期:____________")
|
||||
head.paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.CENTER
|
||||
|
||||
titles = ["评价维度", "评价标准", "学生自评(25%)", "学生互评(25%)", "教师评价(50%)"]
|
||||
for ci, t in enumerate(titles):
|
||||
cell = table.cell(1, ci)
|
||||
run = cell.paragraphs[0].add_run(t)
|
||||
run.bold = True
|
||||
run.font.size = Pt(8.5)
|
||||
cell.paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.CENTER
|
||||
|
||||
for ri, row in enumerate(ASSESS_ROWS, start=2):
|
||||
section = row[1] == row[0] or row[0] in ("总分",)
|
||||
if row[0].startswith(("一、", "二、", "三、")):
|
||||
merged = table.cell(ri, 0).merge(table.cell(ri, 4))
|
||||
run = merged.paragraphs[0].add_run(row[0])
|
||||
run.bold = True
|
||||
run.font.size = Pt(8.5)
|
||||
merged.paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.LEFT
|
||||
continue
|
||||
if row[0] == "总分":
|
||||
c0 = table.cell(ri, 0)
|
||||
c1 = table.cell(ri, 1).merge(table.cell(ri, 4))
|
||||
for cell, txt, bold in ((c0, "总分", True), (c1, row[1], False)):
|
||||
run = cell.paragraphs[0].add_run(txt)
|
||||
run.bold = bold
|
||||
run.font.size = Pt(8.5)
|
||||
continue
|
||||
for ci in range(cols):
|
||||
cell = table.cell(ri, ci)
|
||||
txt = row[ci] if ci < len(row) else ""
|
||||
run = cell.paragraphs[0].add_run(txt)
|
||||
run.font.size = Pt(8.5)
|
||||
if ci == 0:
|
||||
cell.paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.CENTER
|
||||
widths = [Inches(1.15), Inches(2.15), Inches(0.85), Inches(0.85), Inches(0.85)]
|
||||
table.autofit = False
|
||||
for idx, w in enumerate(widths):
|
||||
table.columns[idx].width = w
|
||||
for row in table.rows:
|
||||
for idx, w in enumerate(widths):
|
||||
try:
|
||||
row.cells[idx].width = w
|
||||
except IndexError:
|
||||
pass
|
||||
harden_table(table, header=True)
|
||||
doc.add_paragraph(style="Normal")
|
||||
|
||||
|
||||
def add_figure(doc, case_no):
|
||||
fname, cap = FIG_CAPTIONS[case_no]
|
||||
path = os.path.join(FIG_DIR, fname)
|
||||
from PIL import Image
|
||||
w, h = Image.open(path).size
|
||||
width = 4.2
|
||||
height = width * h / w
|
||||
if height > 7.2:
|
||||
height = 7.2
|
||||
width = height * w / h
|
||||
p = doc.add_paragraph(style="Normal")
|
||||
p.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
||||
p.paragraph_format.keep_with_next = True
|
||||
p.add_run().add_picture(path, width=Inches(width))
|
||||
caption_par(doc, f"图{case_no} {cap}")
|
||||
|
||||
|
||||
def add_code_line(doc, text):
|
||||
p = doc.add_paragraph(style="HTML Preformatted")
|
||||
pf = p.paragraph_format
|
||||
pf.first_line_indent = Inches(0)
|
||||
pf.space_before = Pt(0)
|
||||
pf.space_after = Pt(0)
|
||||
no_grid(p)
|
||||
run = p.add_run(text if text.strip() else " ")
|
||||
run.font.name = "Consolas"
|
||||
run.font.size = Pt(8.5)
|
||||
run._element.rPr.rFonts.set(qn("w:eastAsia"), "宋体")
|
||||
run._element.set(qn("xml:space"), "preserve")
|
||||
return p
|
||||
|
||||
|
||||
def parse_table_row(line):
|
||||
cells = re.split(r"(?<!\\)\|", line.strip().strip("|"))
|
||||
return [c.strip().replace("\\|", "|") for c in cells]
|
||||
|
||||
|
||||
def build():
|
||||
doc = Document(SRC_DOCX)
|
||||
clear_body(doc)
|
||||
doc.styles["Heading 2"].font.size = Pt(15)
|
||||
|
||||
lines = open(MD, encoding="utf-8").read().splitlines()
|
||||
i = 0
|
||||
current_case = None
|
||||
in_assessment = False
|
||||
|
||||
while i < len(lines):
|
||||
line = lines[i]
|
||||
stripped = line.strip()
|
||||
|
||||
if stripped.startswith("```"):
|
||||
lang = stripped[3:].strip()
|
||||
i += 1
|
||||
block = []
|
||||
while i < len(lines) and not lines[i].strip().startswith("```"):
|
||||
block.append(lines[i])
|
||||
i += 1
|
||||
i += 1
|
||||
if lang == "c":
|
||||
for code_line in block:
|
||||
add_code_line(doc, code_line)
|
||||
elif lang == "text":
|
||||
block_text = "\n".join(block)
|
||||
is_run_result = ("请选择功能" in block_text) or (current_case == "10-1")
|
||||
if current_case in FIG_CAPTIONS and is_run_result:
|
||||
add_figure(doc, current_case)
|
||||
else:
|
||||
for code_line in block:
|
||||
add_code_line(doc, code_line)
|
||||
continue
|
||||
|
||||
if stripped.startswith("#### "):
|
||||
title = stripped[5:].strip()
|
||||
m = re.search(r"案例\s*(\d+-\d+)", title)
|
||||
current_case = m.group(1) if m else None
|
||||
doc.add_paragraph(title, style="Heading 4")
|
||||
i += 1
|
||||
continue
|
||||
|
||||
if stripped.startswith("## "):
|
||||
title = stripped[3:].strip()
|
||||
if title.startswith("任务"):
|
||||
h2 = doc.add_paragraph(title, style="Heading 2")
|
||||
h2.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
||||
h2.paragraph_format.first_line_indent = Inches(0)
|
||||
no_grid(h2)
|
||||
elif title.startswith("过程性考核"):
|
||||
in_assessment = True
|
||||
doc.add_paragraph(title, style="项目引入")
|
||||
add_assessment(doc)
|
||||
else:
|
||||
in_assessment = False
|
||||
doc.add_paragraph(title, style="项目引入")
|
||||
i += 1
|
||||
continue
|
||||
|
||||
if stripped.startswith("# "):
|
||||
h = doc.add_paragraph(stripped[2:].strip(), style="Heading 1")
|
||||
h.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
||||
h.paragraph_format.first_line_indent = Inches(0)
|
||||
h.paragraph_format.line_spacing = 1.0
|
||||
h.paragraph_format.space_before = Pt(12)
|
||||
h.paragraph_format.space_after = Pt(12)
|
||||
no_grid(h)
|
||||
i += 1
|
||||
continue
|
||||
|
||||
if stripped.startswith("### "):
|
||||
doc.add_paragraph(stripped[4:].strip(), style="项目引入")
|
||||
i += 1
|
||||
continue
|
||||
|
||||
if in_assessment:
|
||||
# skip markdown tables of the assessment section; built programmatically
|
||||
if stripped.startswith("|") or stripped == "":
|
||||
i += 1
|
||||
continue
|
||||
if stripped.startswith("## "):
|
||||
in_assessment = False
|
||||
else:
|
||||
i += 1
|
||||
continue
|
||||
|
||||
if stripped.startswith("|"):
|
||||
rows = []
|
||||
while i < len(lines) and lines[i].strip().startswith("|"):
|
||||
raw = lines[i].strip()
|
||||
if not re.match(r"^\|[\s\-:|]+\|$", raw):
|
||||
rows.append(parse_table_row(raw))
|
||||
i += 1
|
||||
if rows:
|
||||
add_table(doc, rows)
|
||||
continue
|
||||
|
||||
if stripped.startswith("**表"):
|
||||
caption_par(doc, stripped.strip("*").strip())
|
||||
i += 1
|
||||
continue
|
||||
|
||||
if stripped.startswith(">"):
|
||||
quote = []
|
||||
while i < len(lines) and lines[i].strip().startswith(">"):
|
||||
quote.append(lines[i].strip().lstrip(">").strip())
|
||||
i += 1
|
||||
quote = [q for q in quote if q]
|
||||
if quote:
|
||||
first = quote[0]
|
||||
if first.startswith("思政点睛"):
|
||||
doc.add_paragraph(first.replace("**", ""), style="项目引入")
|
||||
for extra in quote[1:]:
|
||||
body_par(doc, extra.replace("**", ""))
|
||||
else:
|
||||
for extra in quote:
|
||||
body_par(doc, extra)
|
||||
continue
|
||||
|
||||
if stripped == "":
|
||||
i += 1
|
||||
continue
|
||||
|
||||
if stripped.startswith("---"):
|
||||
i += 1
|
||||
continue
|
||||
|
||||
body_par(doc, stripped)
|
||||
i += 1
|
||||
|
||||
# 表 10-1 列宽微调,避免首列过窄
|
||||
for t in doc.tables:
|
||||
if len(t.columns) == 4 and t.rows[0].cells[0].text.strip() == "菜单项":
|
||||
widths = [Inches(1.25), Inches(1.75), Inches(1.75), Inches(0.95)]
|
||||
t.autofit = False
|
||||
for idx, w in enumerate(widths):
|
||||
t.columns[idx].width = w
|
||||
for row in t.rows:
|
||||
for idx, w in enumerate(widths):
|
||||
row.cells[idx].width = w
|
||||
tblW = t._tbl.tblPr.find(qn("w:tblW"))
|
||||
if tblW is not None:
|
||||
tblW.set(qn("w:type"), "dxa")
|
||||
tblW.set(qn("w:w"), str(int(sum(x.inches for x in widths) * 1440)))
|
||||
break
|
||||
|
||||
doc.save(OUT_DOCX)
|
||||
print("saved", OUT_DOCX)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
build()
|
||||
@@ -0,0 +1,140 @@
|
||||
"""Capture real console sessions, inject the typed keys at prompt positions,
|
||||
crop to a readable window and render console-style screenshots."""
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
|
||||
BASE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
OUT = os.path.join(BASE, "figs")
|
||||
FONT_PATH = r"C:\Windows\Fonts\simsun.ttc"
|
||||
FONT_INDEX = 1
|
||||
FONT_SIZE = 15
|
||||
LINE_H = 21
|
||||
PAD = 10
|
||||
BG = (12, 12, 12)
|
||||
FG = (212, 212, 212)
|
||||
|
||||
PROMPTS = [
|
||||
"请选择功能(0-8):",
|
||||
"请输入设备编号:",
|
||||
"请选择操作:",
|
||||
"请输入参数值:",
|
||||
"请选择标志(1在线 2故障 3锁定 4节能):",
|
||||
"请选择场景:",
|
||||
]
|
||||
|
||||
|
||||
def run(exe, inputs, cwd=BASE):
|
||||
data = ("\n".join(inputs) + "\n").encode("utf-8")
|
||||
p = subprocess.run([os.path.join(cwd, exe)], input=data,
|
||||
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd=cwd)
|
||||
return p.stdout.decode("utf-8", "replace")
|
||||
|
||||
|
||||
def inject(text, inputs):
|
||||
out = []
|
||||
i = 0
|
||||
k = 0
|
||||
while i < len(text):
|
||||
hit = None
|
||||
for p in PROMPTS:
|
||||
if text.startswith(p, i):
|
||||
hit = p
|
||||
break
|
||||
if hit is not None and k < len(inputs):
|
||||
out.append(hit)
|
||||
out.append(inputs[k] + "\r\n")
|
||||
i += len(hit)
|
||||
k += 1
|
||||
else:
|
||||
out.append(text[i])
|
||||
i += 1
|
||||
if k != len(inputs):
|
||||
print(f" WARN: injected {k}/{len(inputs)} inputs", file=sys.stderr)
|
||||
return "".join(out)
|
||||
|
||||
|
||||
def window(lines, start_pat, end_pat, before=1, after=2):
|
||||
i = next((n for n, l in enumerate(lines) if start_pat in l), None)
|
||||
if i is None:
|
||||
return lines
|
||||
j = next((n for n in range(i, len(lines)) if end_pat in lines[n]), i)
|
||||
return lines[max(0, i - before): j + after + 1]
|
||||
|
||||
|
||||
def render(lines, path):
|
||||
lines = [l.rstrip("\r") for l in lines]
|
||||
while lines and not lines[-1].strip():
|
||||
lines.pop()
|
||||
while lines and not lines[0].strip():
|
||||
lines.pop(0)
|
||||
font = ImageFont.truetype(FONT_PATH, FONT_SIZE, index=FONT_INDEX)
|
||||
width = max(int(font.getlength(l)) for l in lines) if lines else 400
|
||||
w = max(width + 2 * PAD, 500)
|
||||
h = len(lines) * LINE_H + 2 * PAD
|
||||
img = Image.new("RGB", (w, h), BG)
|
||||
d = ImageDraw.Draw(img)
|
||||
for n, l in enumerate(lines):
|
||||
d.text((PAD, PAD + n * LINE_H), l, font=font, fill=FG)
|
||||
d.rectangle([0, 0, w - 1, h - 1], outline=(58, 58, 58))
|
||||
img.save(path)
|
||||
return len(lines), w, h
|
||||
|
||||
|
||||
def fresh():
|
||||
for f in ("devices.cfg", "smart_home.log"):
|
||||
p = os.path.join(BASE, f)
|
||||
if os.path.exists(p):
|
||||
os.remove(p)
|
||||
|
||||
|
||||
SPECS = {
|
||||
"fig10-1": ("case10_1.exe", [], None),
|
||||
"fig10-2": ("main.exe", ["1", "9", "0"], None),
|
||||
"fig10-3": ("main.exe", ["2", "1", "3", "55", "2", "3", "3", "10", "0"], None),
|
||||
"fig10-4": ("main.exe", ["3", "1", "1", "2", "3", "4", "5", "0"], None),
|
||||
"fig10-5": ("main.exe", ["4", "3", "1", "0"], None),
|
||||
"fig10-6": ("main.exe", ["5", "0"], None),
|
||||
"fig10-8": ("main.exe", ["2", "1", "1", "3", "4", "4", "4", "3", "8", "0"],
|
||||
("-------------------- 运行日志", "条记录", 2, 1)),
|
||||
}
|
||||
|
||||
|
||||
def main():
|
||||
os.makedirs(OUT, exist_ok=True)
|
||||
for name, (exe, inputs, crop) in SPECS.items():
|
||||
fresh()
|
||||
text = inject(run(exe, inputs), inputs)
|
||||
lines = text.split("\n")
|
||||
if crop:
|
||||
lines = window(lines, crop[0], crop[1], crop[2], crop[3])
|
||||
n, w, h = render(lines, os.path.join(OUT, name + ".png"))
|
||||
with open(os.path.join(OUT, name + ".txt"), "w", encoding="utf-8") as f:
|
||||
f.write("\n".join(lines))
|
||||
print(f"{name}: lines={n} size=({w}x{h})")
|
||||
|
||||
# 图10-7: save+exit, restart, load+ledger
|
||||
fresh()
|
||||
t1 = inject(run("main.exe", ["6", "0"]), ["6", "0"])
|
||||
l1 = window(t1.split("\n"), "==========", "保存成功", 0, 1)
|
||||
t2 = inject(run("main.exe", ["7", "1", "0"]), ["7", "1", "0"])
|
||||
l2 = window(t2.split("\n"), "加载成功", "共 6 台设备", 1, 1)
|
||||
p1 = os.path.join(OUT, "fig10-7a.png")
|
||||
p2 = os.path.join(OUT, "fig10-7b.png")
|
||||
render(l1, p1)
|
||||
render(l2, p2)
|
||||
a, b = Image.open(p1), Image.open(p2)
|
||||
w = max(a.width, b.width)
|
||||
canvas = Image.new("RGB", (w, a.height + b.height + 14), (30, 30, 30))
|
||||
canvas.paste(a, (0, 0))
|
||||
canvas.paste(b, (0, a.height + 14))
|
||||
canvas.save(os.path.join(OUT, "fig10-7.png"))
|
||||
with open(os.path.join(OUT, "fig10-7.txt"), "w", encoding="utf-8") as f:
|
||||
f.write("\n".join(l1) + "\n=== 重新启动 ===\n" + "\n".join(l2))
|
||||
print(f"fig10-7: size=({canvas.width}x{canvas.height}) parts=({len(l1)},{len(l2)})")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||