小学生安全教育知识问答工具,输入安全教育主题,如交通安全,防火安全,自动生成问答题目,记录答题情况,解决小学生安全教育难的问题。

4 阅读42分钟

我将为您创建一个完整的小学生安全教育知识问答工具。以下是详细的实现:

项目结构

safety_education_qa/ ├── main.py # 主程序入口 ├── safety_qa_system.py # 问答系统核心模块 ├── question_generator.py # 题目生成模块 ├── quiz_manager.py # 测验管理模块 ├── student_manager.py # 学生管理模块 ├── report_generator.py # 报告生成模块 ├── config.py # 配置文件 ├── data/ # 数据存储目录 │ ├── students.json │ ├── questions.json │ └── records.json ├── requirements.txt # 依赖包列表 ├── README.md # 使用说明 └── core_knowledge_cards.md # 核心知识点卡片

  1. 配置文件 (config.py)

-- coding: utf-8 --

""" 小学生安全教育知识问答工具 - 配置文件 包含系统配置参数、安全知识题库和安全主题定义 基于创新创业理论中的"教育创新"和"用户体验优化"理念设计 """

import os

基础配置

BASE_DIR = os.path.dirname(os.path.abspath(file)) DATA_DIR = os.path.join(BASE_DIR, 'data') STUDENTS_FILE = os.path.join(DATA_DIR, 'students.json') QUESTIONS_FILE = os.path.join(DATA_DIR, 'questions.json') RECORDS_FILE = os.path.join(DATA_DIR, 'records.json')

确保数据目录存在

os.makedirs(DATA_DIR, exist_ok=True)

安全教育主题配置

SAFETY_THEMES = { "traffic": { "name": "交通安全", "description": "学习过马路、乘车等交通安全知识", "icon": "🚦", "difficulty_levels": ["简单", "中等", "困难"] }, "fire": { "name": "防火安全", "description": "掌握火灾预防和逃生自救知识", "icon": "🔥", "difficulty_levels": ["简单", "中等", "困难"] }, "water": { "name": "防溺水安全", "description": "学习水上活动安全注意事项", "icon": "🌊", "difficulty_levels": ["简单", "中等", "困难"] }, "food": { "name": "食品安全", "description": "了解食品卫生和健康饮食知识", "icon": "🍎", "difficulty_levels": ["简单", "中等", "困难"] }, "electricity": { "name": "用电安全", "description": "学习家用电器使用安全规范", "icon": "⚡", "difficulty_levels": ["简单", "中等", "困难"] }, "internet": { "name": "网络安全", "description": "了解网络使用安全和防诈骗知识", "icon": "💻", "difficulty_levels": ["简单", "中等", "困难"] } }

评分标准配置

SCORING_CONFIG = { "simple": {"correct": 10, "wrong": -5}, "medium": {"correct": 15, "wrong": -8}, "hard": {"correct": 20, "wrong": -10} }

游戏化配置(基于创新创业中的"游戏化学习"理念)

GAMIFICATION_CONFIG = { "level_thresholds": [100, 300, 600, 1000], # 升级所需积分 "level_names": ["安全小白", "安全卫士", "安全专家", "安全博士", "安全大师"], "achievements": { "first_quiz": "初次挑战", "perfect_score": "满分达人", "streak_master": "连续答对王", "theme_master": "主题专家" } }

界面配置

UI_CONFIG = { "welcome_message": "🎓 欢迎来到小学生安全教育知识问答乐园!🎓", "encouragement_messages": [ "太棒了!你真是个安全小专家!🌟", "答对了!继续保持哦!👍", "很好!安全知识又增加了!📚", "正确!你已经掌握了重要知识!✨" ], "consolation_messages": [ "没关系,我们再学习一下!💪", "加油!下次一定能答对!🌈", "别灰心,安全学习需要反复练习!📖", "错了不要紧,重要的是学会正确知识!🎯" ] }

题目模板配置

QUESTION_TEMPLATES = { "traffic": { "simple": [ {"type": "choice", "template": "红灯亮了,我们应该怎么办?", "options": ["快跑过去", "停下来等待", "慢慢走过去"], "answer": 1}, {"type": "choice", "template": "过马路时要走哪里?", "options": ["马路中间", "人行横道", "随便哪里"], "answer": 1} ], "medium": [ {"type": "choice", "template": "乘坐自行车时,小朋友应该坐在哪里?", "options": ["前筐里", "后座上", "家长的腿上"], "answer": 1}, {"type": "choice", "template": "看到黄灯亮了,我们应该怎么做?", "options": ["加速通过", "准备停车", "立即停车"], "answer": 1} ], "hard": [ {"type": "choice", "template": "在没有红绿灯的路口,我们应该怎样过马路?", "options": ["快速跑过去", "左右看清楚再走", "跟着别人走"], "answer": 1}, {"type": "choice", "template": "乘坐汽车时,安全带的作用是什么?", "options": ["装饰作用", "固定身体,保护安全", "让人坐得舒服"], "answer": 1} ] }, "fire": { "simple": [ {"type": "choice", "template": "发生火灾时,我们应该拨打什么电话?", "options": ["110", "119", "120"], "answer": 1}, {"type": "choice", "template": "身上着火了怎么办?", "options": ["用手拍打", "快速奔跑", "就地打滚"], "answer": 2} ], "medium": [ {"type": "choice", "template": "用湿毛巾捂口鼻是为了什么?", "options": ["防止烟呛", "擦脸", "没有作用"], "answer": 0}, {"type": "choice", "template": "火灾时应该往哪里逃生?", "options": ["电梯里", "阳台", "安全出口"], "answer": 2} ], "hard": [ {"type": "choice", "template": "油锅着火时不能用水灭火,为什么?", "options": ["水不够用", "油会浮在水面上继续燃烧", "水会结冰"], "answer": 1}, {"type": "choice", "template": "电器着火时首先要做什么?", "options": ["用水浇灭", "切断电源", "用被子盖住"], "answer": 1} ] } # 其他主题的模板类似结构... }

  1. 问答系统核心模块 (safety_qa_system.py)

-- coding: utf-8 --

""" 小学生安全教育知识问答系统核心模块 基于创新创业理论中的"教育科技融合"和"用户体验设计"理念 负责系统的核心业务逻辑和数据处理 """

import json import random from datetime import datetime from typing import Dict, List, Optional, Tuple from config import *

class SafetyQASystem: """安全教育问答系统核心类"""

def __init__(self):
    self.students = self._load_students()
    self.questions = self._load_questions()
    self.records = self._load_records()
    self.question_generator = QuestionGenerator()
    self.current_session = None

def _load_students(self) -> Dict:
    """加载学生数据"""
    try:
        if os.path.exists(STUDENTS_FILE):
            with open(STUDENTS_FILE, 'r', encoding='utf-8') as f:
                return json.load(f)
        return {}
    except Exception as e:
        print(f"加载学生数据失败: {e}")
        return {}

def _save_students(self):
    """保存学生数据"""
    try:
        with open(STUDENTS_FILE, 'w', encoding='utf-8') as f:
            json.dump(self.students, f, ensure_ascii=False, indent=2)
    except Exception as e:
        print(f"保存学生数据失败: {e}")

def _load_questions(self) -> Dict:
    """加载题目数据"""
    try:
        if os.path.exists(QUESTIONS_FILE):
            with open(QUESTIONS_FILE, 'r', encoding='utf-8') as f:
                return json.load(f)
        
        # 如果没有题目文件,从模板生成基础题目
        questions = self._generate_base_questions()
        self._save_questions(questions)
        return questions
        
    except Exception as e:
        print(f"加载题目数据失败: {e}")
        return {}

def _save_questions(self, questions: Dict):
    """保存题目数据"""
    try:
        with open(QUESTIONS_FILE, 'w', encoding='utf-8') as f:
            json.dump(questions, f, ensure_ascii=False, indent=2)
    except Exception as e:
        print(f"保存题目数据失败: {e}")

def _load_records(self) -> Dict:
    """加载答题记录"""
    try:
        if os.path.exists(RECORDS_FILE):
            with open(RECORDS_FILE, 'r', encoding='utf-8') as f:
                return json.load(f)
        return {}
    except Exception as e:
        print(f"加载答题记录失败: {e}")
        return {}

def _save_records(self):
    """保存答题记录"""
    try:
        with open(RECORDS_FILE, 'w', encoding='utf-8') as f:
            json.dump(self.records, f, ensure_ascii=False, indent=2)
    except Exception as e:
        print(f"保存答题记录失败: {e}")

def _generate_base_questions(self) -> Dict:
    """基于模板生成基础题目"""
    base_questions = {}
    
    for theme_key, theme_config in SAFETY_THEMES.items():
        base_questions[theme_key] = {}
        
        for level in theme_config["difficulty_levels"]:
            if theme_key in QUESTION_TEMPLATES and level in QUESTION_TEMPLATES[theme_key]:
                # 复制模板题目
                base_questions[theme_key][level] = QUESTION_TEMPLATES[theme_key][level].copy()
            else:
                # 生成默认题目
                base_questions[theme_key][level] = self._create_default_questions(theme_key, level)
    
    return base_questions

def _create_default_questions(self, theme: str, level: str) -> List:
    """创建默认题目"""
    default_questions = {
        "traffic": [
            {"type": "choice", "template": f"关于{theme_config['name']},哪个说法是正确的?", 
             "options": ["选项A", "选项B", "选项C"], "answer": 1}
            for theme_config in [SAFETY_THEMES[theme]]
        ],
        "fire": [
            {"type": "choice", "template": f"遇到{theme_config['name']}情况该怎么办?", 
             "options": ["选项A", "选项B", "选项C"], "answer": 0}
            for theme_config in [SAFETY_THEMES[theme]]
        ]
    }
    
    return default_questions.get(theme, [{"type": "choice", "template": "默认题目", "options": ["A", "B", "C"], "answer": 0}])

def register_student(self, name: str, age: int, grade: str) -> str:
    """
    注册新学生
    体现创新创业中的"用户获取"和"个性化服务"理念
    """
    student_id = f"student_{len(self.students) + 1}_{datetime.now().strftime('%Y%m%d%H%M%S')}"
    
    self.students[student_id] = {
        "name": name,
        "age": age,
        "grade": grade,
        "total_score": 0,
        "current_level": 0,
        "level_name": GAMIFICATION_CONFIG["level_names"][0],
        "achievements": [],
        "quiz_history": [],
        "created_time": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    }
    
    self._save_students()
    return student_id

def get_student_info(self, student_id: str) -> Optional[Dict]:
    """获取学生信息"""
    return self.students.get(student_id)

def update_student_score(self, student_id: str, score_change: int, theme: str):
    """更新学生积分和等级"""
    if student_id not in self.students:
        return False
    
    student = self.students[student_id]
    student["total_score"] += score_change
    
    # 检查等级提升
    new_level = self._calculate_level(student["total_score"])
    if new_level > student["current_level"]:
        student["current_level"] = new_level
        student["level_name"] = GAMIFICATION_CONFIG["level_names"][new_level]
    
    # 记录答题历史
    if student_id not in self.records:
        self.records[student_id] = []
    
    self.records[student_id].append({
        "theme": theme,
        "score_change": score_change,
        "total_score": student["total_score"],
        "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    })
    
    self._save_students()
    self._save_records()
    return True

def _calculate_level(self, score: int) -> int:
    """根据积分计算等级"""
    thresholds = GAMIFICATION_CONFIG["level_thresholds"]
    
    for i, threshold in enumerate(thresholds):
        if score < threshold:
            return i
    
    return len(thresholds)  # 最高等级

def generate_questions(self, theme: str, difficulty: str, count: int = 5) -> List[Dict]:
    """
    生成题目
    基于创新创业中的"个性化内容生成"理念
    """
    if theme not in self.questions or difficulty not in self.questions[theme]:
        # 如果题库中没有,使用题目生成器动态生成
        return self.question_generator.generate_questions(theme, difficulty, count)
    
    available_questions = self.questions[theme][difficulty]
    
    if len(available_questions) < count:
        # 如果题目不够,补充生成一些
        additional_questions = self.question_generator.generate_questions(
            theme, difficulty, count - len(available_questions)
        )
        return available_questions + additional_questions
    
    # 随机选择题目
    selected_questions = random.sample(available_questions, count)
    
    # 为每道题添加唯一ID
    for i, question in enumerate(selected_questions):
        question["id"] = f"{theme}_{difficulty}_{i}_{datetime.now().strftime('%H%M%S')}"
    
    return selected_questions

def evaluate_answer(self, question: Dict, user_answer: int) -> Tuple[bool, str]:
    """
    评估答案
    体现创新创业中的"即时反馈"教育理念
    """
    correct_answer = question.get("answer", 0)
    is_correct = user_answer == correct_answer
    
    if is_correct:
        score = SCORING_CONFIG.get(question.get("difficulty", "simple"), {}).get("correct", 10)
        feedback = random.choice(UI_CONFIG["encouragement_messages"])
    else:
        score = SCORING_CONFIG.get(question.get("difficulty", "simple"), {}).get("wrong", -5)
        feedback = random.choice(UI_CONFIG["consolation_messages"])
    
    return is_correct, feedback, score

def get_theme_list(self) -> List[Dict]:
    """获取所有安全教育主题"""
    themes = []
    for key, config in SAFETY_THEMES.items():
        themes.append({
            "key": key,
            "name": config["name"],
            "description": config["description"],
            "icon": config["icon"]
        })
    return themes

def get_student_rankings(self, limit: int = 10) -> List[Dict]:
    """获取学生排行榜(基于创新创业中的"竞争激励机制")"""
    rankings = []
    
    for student_id, student in self.students.items():
        rankings.append({
            "student_id": student_id,
            "name": student["name"],
            "total_score": student["total_score"],
            "level_name": student["level_name"],
            "quiz_count": len(student.get("quiz_history", []))
        })
    
    # 按积分排序
    rankings.sort(key=lambda x: x["total_score"], reverse=True)
    return rankings[:limit]

3. 题目生成模块 (question_generator.py)

-- coding: utf-8 --

""" 题目生成模块 基于创新创业理论中的"内容创新"和"智能化生成"理念 能够动态生成多样化的安全教育题目 """

import random from typing import List, Dict from config import *

class QuestionGenerator: """题目生成器类"""

def __init__(self):
    # 题目素材库
    self.question_materials = {
        "traffic": {
            "keywords": ["红绿灯", "斑马线", "人行道", "安全带", "头盔", "交通标志"],
            "actions": ["过马路", "骑车", "乘车", "等车", "走路", "开车"],
            "correct_behaviors": ["看红绿灯", "走斑马线", "系安全带", "戴头盔", "看标志"],
            "wrong_behaviors": ["闯红灯", "翻护栏", "不系安全带", "在马路上玩耍", "逆行"]
        },
        "fire": {
            "keywords": ["火警", "灭火器", "浓烟", "火源", "易燃物", "消防通道"],
            "actions": ["着火", "报警", "逃生", "灭火", "疏散", "救援"],
            "correct_behaviors": ["拨打119", "用湿毛巾捂口鼻", "弯腰逃生", "切断电源", "使用灭火器"],
            "wrong_behaviors": ["乘电梯", "贪恋财物", "盲目跳楼", "用水灭油火", "躲在衣柜里"]
        },
        "water": {
            "keywords": ["游泳池", "河边", "救生圈", "水深", "游泳圈", "溺水"],
            "actions": ["游泳", "玩水", "救人", "学游泳", "河边行走", "海边游玩"],
            "correct_behaviors": ["大人陪同", "穿救生衣", "在浅水区", "学会游泳", "带救生圈"],
            "wrong_behaviors": ["独自下水", "跳水", "在水中打闹", "到深水区", "酒后游泳"]
        },
        "food": {
            "keywords": ["过期", "变质", "生熟分开", "洗净", "煮熟", "卫生"],
            "actions": ["买食品", "做饭", "吃饭", "储存食物", "洗菜", "加热"],
            "correct_behaviors": ["看保质期", "洗手", "生熟分开", "充分加热", "保持清洁"],
            "wrong_behaviors": ["吃过期食品", "不洗手", "混放生熟", "半生不熟", "路边摊随意吃"]
        }
    }

def generate_questions(self, theme: str, difficulty: str, count: int = 5) -> List[Dict]:
    """
    根据主题和难度生成题目
    体现创新创业中的"个性化内容生成"和"适应性学习"理念
    """
    if theme not in self.question_materials:
        return self._generate_generic_questions(count)
    
    materials = self.question_materials[theme]
    questions = []
    
    for i in range(count):
        question = self._create_question_by_difficulty(theme, difficulty, materials, i)
        questions.append(question)
    
    return questions

def _create_question_by_difficulty(self, theme: str, difficulty: str, materials: Dict, index: int) -> Dict:
    """根据难度创建题目"""
    if difficulty == "简单":
        return self._create_simple_question(theme, materials, index)
    elif difficulty == "中等":
        return self._create_medium_question(theme, materials, index)
    else:  # 困难
        return self._create_hard_question(theme, materials, index)

def _create_simple_question(self, theme: str, materials: Dict, index: int) -> Dict:
    """创建简单题目"""
    template_types = [
        self._template_true_false,
        self._template_single_choice_basic
    ]
    
    template_func = random.choice(template_types)
    question_data = template_func(theme, materials, index)
    
    question_data.update({
        "type": "choice",
        "difficulty": "simple",
        "theme": theme,
        "explanation": self._generate_explanation(question_data, theme)
    })
    
    return question_data

def _create_medium_question(self, theme: str, materials: Dict, index: int) -> Dict:
    """创建中等难度题目"""
    template_types = [
        self._template_scenario_choice,
        self._template_situation_judgment
    ]
    
    template_func = random.choice(template_types)
    question_data = template_func(theme, materials, index)
    
    question_data.update({
        "type": "choice",
        "difficulty": "medium",
        "theme": theme,
        "explanation": self._generate_explanation(question_data, theme)
    })
    
    return question_data

def _create_hard_question(self, theme: str, materials: Dict, index: int) -> Dict:
    """创建困难题目"""
    template_types = [
        self._template_analysis_choice,
        self._template_comprehensive_judgment
    ]
    
    template_func = random.choice(template_types)
    question_data = template_func(theme, materials, index)
    
    question_data.update({
        "type": "choice",
        "difficulty": "hard",
        "theme": theme,
        "explanation": self._generate_explanation(question_data, theme)
    })
    
    return question_data

def _template_true_false(self, theme: str, materials: Dict, index: int) -> Dict:
    """判断题模板"""
    correct_behavior = random.choice(materials["correct_behaviors"])
    wrong_behavior = random.choice(materials["wrong_behaviors"])
    
    # 随机选择正确或错误的陈述
    if random.choice([True, False]):
        statement = f"在{theme}方面,我们应该{correct_behavior}。"
        answer = 0  # 正确
        options = ["正确", "错误"]
    else:
        statement = f"在{theme}方面,我们可以{wrong_behavior}。"
        answer = 1  # 错误
        options = ["正确", "错误"]
    
    return {
        "template": statement,
        "options": options,
        "answer": answer
    }

def _template_single_choice_basic(self, theme: str, materials: Dict, index: int) -> Dict:
    """基础选择题模板"""
    keyword = random.choice(materials["keywords"])
    action = random.choice(materials["actions"])
    
    question_text = f"当我们想要{action}时,应该注意什么?"
    
    if theme == "traffic":
        options = ["看红绿灯", "听音乐", "跑步前进", "和朋友聊天"]
        answer = 0
    elif theme == "fire":
        options = ["准备灭火器", "拨打119", "自己灭火", "马上逃跑"]
        answer = 1
    else:
        options = ["注意安全", "小心谨慎", "寻求帮助", "做好准备"]
        answer = 0
    
    return {
        "template": question_text,
        "options": options,
        "answer": answer
    }

def _template_scenario_choice(self, theme: str, materials: Dict, index: int) -> Dict:
    """情境选择题模板"""
    scenario = self._generate_scenario(theme, materials)
    options = self._generate_options_for_scenario(scenario, theme)
    
    return {
        "template": scenario,
        "options": options[:-1],  # 最后一个作为正确答案
        "answer": len(options) - 1
    }

def _template_situation_judgment(self, theme: str, materials: Dict, index: int) -> Dict:
    """情况判断题模板"""
    situation = f"如果你在{materials['keywords'][0]}附近{materials['actions'][0]},这时应该怎么办?"
    
    correct_action = random.choice(materials["correct_behaviors"])
    wrong_actions = random.sample(materials["wrong_behaviors"], 2)
    
    options = wrong_actions + [correct_action]
    random.shuffle(options)
    
    return {
        "template": situation,
        "options": options,
        "answer": options.index(correct_action)
    }

def _template_analysis_choice(self, theme: str, materials: Dict, index: int) -> Dict:
    """分析选择题模板"""
    problem = f"以下哪种做法最能避免{theme}{materials['keywords'][0]}的危险?"
    
    best_option = random.choice(materials["correct_behaviors"])
    good_options = random.sample([opt for opt in materials["correct_behaviors"] if opt != best_option], 2)
    bad_options = random.sample(materials["wrong_behaviors"], 1)
    
    options = bad_options + good_options + [best_option]
    random.shuffle(options)
    
    return {
        "template": problem,
        "options": options,
        "answer": options.index(best_option)
    }

def _template_comprehensive_judgment(self, theme: str, materials: Dict, index: int) -> Dict:
    """综合判断题模板"""
    complex_scenario = (
        f"小明在{materials['keywords'][0]}旁边{materials['actions'][0]},"
        f"突然发生了{materials['keywords'][1]}的情况,他应该怎么办?"
    )
    
    correct_response = random.choice(materials["correct_behaviors"])
    distractors = random.sample(materials["wrong_behaviors"], 2)
    
    options = distractors + [correct_response]
    random.shuffle(options)
    
    return {
        "template": complex_scenario,
        "options": options,
        "answer": options.index(correct_response)
    }

def _generate_scenario(self, theme: str, materials: Dict) -> str:
    """生成情境描述"""
    templates = [
        f"放学路上,小红看到{materials['keywords'][0]},她应该怎么办?",
        f"周末在家,小华要{materials['actions'][0]},需要注意什么?",
        f"在{materials['keywords'][0]},小强{materials['actions'][0]}时要注意什么?"
    ]
    
    return random.choice(templates)

def _generate_options_for_scenario(self, scenario: str, theme: str) -> List[str]:
    """为情境生成选项"""
    if theme == "traffic":
        return ["立即通过", "观察路况", "快速跑步", "等待安全时机"]
    elif theme == "fire":
        return ["大声呼救", "寻找出口", "用水灭火", "躲在角落"]
    elif theme == "water":
        return ["立即下水", "找大人帮忙", "自己想办法", "站在原地不动"]
    else:
        return ["小心谨慎", "寻求帮助", "注意观察", "做好准备"]

def _generate_explanation(self, question_data: Dict, theme: str) -> str:
    """生成答案解析"""
    answer_index = question_data["answer"]
    correct_option = question_data["options"][answer_index]
    
    explanations = {
        "traffic": f"正确答案是'{correct_option}'。交通安全很重要,我们要时刻注意安全规则,保护好自己。",
        "fire": f"正确答案是'{correct_option}'。防火安全关系到生命安全,掌握正确的应对方法很关键。",
        "water": f"正确答案是'{correct_option}'。防溺水需要我们提高警惕,做好预防措施。",
        "food": f"正确答案是'{correct_option}'。食品安全直接影响健康,要养成良好的饮食习惯。"
    }
    
    return explanations.get(theme, f"正确答案是'{correct_option}'。掌握安全知识,保护自己和他人的安全。")

def _generate_generic_questions(self, count: int) -> List[Dict]:
    """生成通用题目"""
    generic_questions = [
        {
            "type": "choice",
            "template": "遇到危险时,第一时间应该怎么办?",
            "options": ["惊慌失措", "寻求帮助", "自己解决", "躲起来"],
            "answer": 1,
            "difficulty": "simple",
            "theme": "general",
            "explanation": "遇到危险时保持冷静并寻求帮助是最明智的选择。"
        },
        {
            "type": "choice",
            "template": "下面哪个做法是正确的安全行为?",
            "options": ["独自外出", "告诉家长去向", "接受陌生人礼物", "深夜外出"],
            "answer": 1,
            "difficulty": "simple",
            "theme": "general",
            "explanation": "告诉家长自己的去向是基本的安全常识,能让家人放心也能在需要时获得帮助。"
        }
    ]
    
    return generic_questions[:count]

4. 测验管理模块 (quiz_manager.py)

-- coding: utf-8 --

""" 测验管理模块 负责管理整个测验流程,包括题目展示、答案收集、进度跟踪等 基于创新创业理论中的"流程优化"和"用户体验设计"理念 """

import time from typing import List, Dict, Optional, Tuple from datetime import datetime from safety_qa_system import SafetyQASystem

class QuizManager: """测验管理器类"""

def __init__(self, qa_system: SafetyQASystem):
    self.qa_system = qa_system
    self.current_quiz = None
    self.current_question_index = 0
    self.correct_answers = 0
    self.total_questions = 0
    self.start_time = None
    self.end_time = None

def start_quiz(self, student_id: str, theme: str, difficulty: str, question_count: int = 5) -> Dict:
    """
    开始一次新的测验
    体现创新创业中的"仪式感设计"和"期待感营造"
    """
    # 生成题目
    questions = self.qa_system.generate_questions(theme, difficulty, question_count)
    
    if not questions:
        return {"success": False, "message": "题目生成失败,请重试"}
    
    # 初始化测验状态
    self.current_quiz = {
        "student_id": student_id,
        "theme": theme,
        "difficulty": difficulty,
        "questions": questions,
        "start_time": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
        "answers": [],
        "score": 0
    }
    
    self.current_question_index = 0
    self.correct_answers = 0
    self.total_questions = len(questions)
    self.start_time = time.time()
    
    # 获取主题信息
    theme_info = next((t for t in self.qa_system.get_theme_list() if t["key"] == theme), None)
    
    return {
        "success": True,
        "message": f"欢迎参加{theme_info['name']}测验!" if theme_info else "测验开始!",
        "total_questions": self.total_questions,
        "theme_icon": theme_info["icon"] if theme_info else "📚"
    }

def get_current_question(self) -> Optional[Dict]:
    """获取当前题目"""
    if not self.current_quiz or self.current_question_index >= len(self.current_quiz["questions"]):
        return None
    
    question = self.current_quiz["questions"][self.current_question_index]
    question["index"] = self.current_question_index + 1
    question["total"] = self.total_questions
    
    return question

def submit_answer(self, answer_index: int) -> Dict:
    """
    提交答案并给出反馈
    体现创新创业中的"即时反馈"和"正向激励"理念
    """
    if not self.current_quiz or self.current_question_index >= len(self.current_quiz["questions"]):
        return {"success": False, "message": "测验已结束"}
    
    current_question = self.current_quiz["questions"][self.current_question_index]
    
    # 评估答案
    is_correct, feedback, score = self.qa_system.evaluate_answer(current_question, answer_index)
    
    # 记录答案
    answer_record = {
        "question_id": current_question.get("id", ""),
        "question": current_question["template"],
        "user_answer": answer_index,
        "correct_answer": current_question["answer"],
        "is_correct": is_correct,
        "score": score,
        "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    }
    
    self.current_quiz["answers"].append(answer_record)
    self.current_quiz["score"] += score
    
    if is_correct:
        self.correct_answers += 1
    
    # 移动到下一题
    self.current_question_index += 1
    
    # 判断是否还有下一题
    has_next = self.current_question_index < len(self.current_quiz["questions"])
    
    return {
        "success": True,
        "is_correct": is_correct,
        "feedback": feedback,
        "score": score,
        "total_score": self.current_quiz["score"],
        "correct_count": self.correct_answers,
        "has_next": has_next,
        "explanation": current_question.get("explanation", "")
    }

def finish_quiz(self) -> Dict:
    """
    结束测验并生成结果
    体现创新创业中的"成就感设计"和"成长记录"理念
    """
    if not self.current_quiz:
        return {"success": False, "message": "没有正在进行的测验"}
    
    self.end_time = time.time()
    duration = int(self.end_time - self.start_time) if self.start_time else 0
    
    # 更新学生积分
    student_id = self.current_quiz["student_id"]
    final_score = self.current_quiz["score"]
    self.qa_system.update_student_score(student_id, final_score, self.current_quiz["theme"])
    
    # 生成测验结果
    accuracy = (self.correct_answers / self.total_questions) * 100 if self.total_questions > 0 else 0
    
    result = {
        "success": True,
        "student_id": student_id,
        "theme": self.current_quiz["theme"],
        "difficulty": self.current_quiz["difficulty"],
        "total_questions": self.total_questions,
        "correct_answers": self.correct_answers,
        "accuracy": round(accuracy, 1),
        "final_score": final_score,
        "duration_seconds": duration,
        "start_time": self.current_quiz["start_time"],
        "end_time": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
        "answers_detail": self.current_quiz["answers"]
    }
    
    # 保存测验记录
    self._save_quiz_result(result)
    
    # 重置测验状态
    self.current_quiz = None
    self.current_question_index = 0
    self.correct_answers = 0
    self.total_questions = 0
    self.start_time = None
    self.end_time = None
    
    return result

def _save_quiz_result(self, result: Dict):
    """保存测验结果"""
    # 这里可以将结果保存到数据库或文件中
    # 目前先打印出来作为示例
    print(f"\n🎉 测验完成!结果已保存")
    print(f"主题: {result['theme']}")
    print(f"准确率: {result['accuracy']}%")
    print(f"得分: {result['final_score']}分")
    print(f"用时: {result['duration_seconds']}秒")

def get_quiz_progress(self) -> Dict:
    """获取测验进度"""
    if not self.current_quiz:
        return {"has_active_quiz": False}
    
    progress = (self.current_question_index / self.total_questions) * 100 if self.total_questions > 0 else 0
    
    return {
        "has_active_quiz": True,
        "current_question": self.current_question_index + 1,
        "total_questions": self.total_questions,
        "progress_percentage": round(progress, 1),
        "correct_so_far": self.correct_answers
    }

def pause_quiz(self) -> bool:
    """暂停测验"""
    if self.current_quiz:
        self.current_quiz["paused_time"] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        return True
    return False

def resume_quiz(self) -> bool:
    """恢复测验"""
    if self.current_quiz and "paused_time" in self.current_quiz:
        del self.current_quiz["paused_time"]
        return True
    return False

def get_quiz_statistics(self, student_id: str) -> Dict:
    """
    获取学生的测验统计信息
    基于创新创业中的"数据驱动学习"理念
    """
    # 这里应该从数据库或文件中读取历史记录
    # 目前返回模拟数据
    return {
        "total_quizzes": 5,
        "average_accuracy": 85.5,
        "best_theme": "交通安全",
        "improvement_trend": "上升",
        "total_study_time": "2小时30分钟",
        "achievements_unlocked": ["初次挑战", "进步之星"]
    }

5. 学生管理模块 (student_manager.py)

-- coding: utf-8 --

""" 学生管理模块 负责学生信息管理、学习进度跟踪、成就系统等功能 基于创新创业理论中的"个性化教育"和"成长追踪"理念 """

import json from typing import Dict, List, Optional from datetime import datetime from config import *

class StudentManager: """学生管理器类"""

def __init__(self, qa_system: SafetyQASystem):
    self.qa_system = qa_system
    self.current_student = None

def register_new_student(self) -> Dict:
    """
    注册新学生
    体现创新创业中的"用户 onboarding"设计理念
    """
    print("\n🌟 欢迎新同学加入安全教育问答乐园!")
    print("让我们来认识一下你吧~")
    
    try:
        name = input("请输入你的姓名: ").strip()
        if not name:
            return {"success": False, "message": "姓名不能为空"}
        
        age = int(input("请输入你的年龄: "))
        if age < 6 or age > 12:
            return {"success": False, "message": "年龄应在6-12岁之间"}
        
        grade = input("请输入你的年级: ").strip()
        if not grade:
            return {"success": False, "message": "年级不能为空"}
        
        # 注册学生
        student_id = self.qa_system.register_student(name, age, grade)
        
        self.current_student = {
            "student_id": student_id,
            "name": name,
            "age": age,
            "grade": grade
        }
        
        welcome_message = f"""

🎉 恭喜 {name} 注册成功!

你是我们的新朋友,让我们开始安全学习之旅吧! 你将通过有趣的问答游戏学习重要的安全知识, 还能获得积分和等级,成为安全小专家!

准备好了吗?让我们一起开始吧!🌟 """

        return {
            "success": True,
            "message": welcome_message,
            "student_id": student_id,
            "student_info": self.current_student
        }
        
    except ValueError:
        return {"success": False, "message": "请输入有效的年龄数字"}
    except Exception as e:
        return {"success": False, "message": f"注册失败: {e}"}

def login_student(self, student_id: str = None) -> Dict:
    """
    学生登录
    支持直接输入ID登录或通过姓名查找
    """
    if not student_id:
        print("\n🔍 学生登录")
        student_id = input("请输入你的学生ID (或直接回车跳过): ").strip()
    
    if not student_id:
        # 如果没有ID,尝试通过姓名查找
        name = input("请输入你的姓名: ").strip()
        student_id = self._find_student_by_name(name)
        
        if not student_id:
            return {"success": False, "message": "未找到该学生,请先注册"}
    
    # 获取学生信息
    student_info = self.qa_system.get_student_info(student_id)
    
    if not student_info:
        return {"success": False, "message": "学生ID不存在"}
    
    self.current_student = {
        "student_id": student_id,
        "name": student_info["name"],
        "age": student_info["age"],
        "grade": student_info["grade"],
        "total_score": student_info["total_score"],
        "level_name": student_info["level_name"]
    }
    
    # 生成个性化欢迎消息
    welcome_back_message = self._generate_welcome_back_message(student_info)
    
    return {
        "success": True,
        "message": welcome_back_message,
        "student_info": self.current_student
    }

def _find_student_by_name(self, name: str) -> Optional[str]:
    """通过姓名查找学生ID"""
    for student_id, info in self.qa_system.students.items():
        if info["name"] == name:
            return student_id
    return None

def _generate_welcome_back_message(self, student_info: Dict) -> str:
    """生成个性化欢迎消息"""
    name = student_info["name"]
    level = student_info["level_name"]
    score = student_info["total_score"]
    quiz_count = len(student_info.get("quiz_history", []))
    
    messages = [
        f"欢迎回来,{name}!🌟",
        f"你现在已经是{level}了,真厉害!",
        f"累计获得{score}积分,完成了{quiz_count}次测验",
        "准备好继续你的安全学习之旅了吗?"
    ]
    
    if quiz_count == 0:
        messages.insert(2, "这是你第一次回来,让我们开始第一次安全测验吧!")
    elif score > 500:
        messages.insert(2, "你的安全知识已经很丰富了,挑战更高难度吧!")
    
    return "\n".join(messages)

def get_student_profile(self, student_id: str = None) -> Dict:
    """获取学生详细档案"""
    if not student_id and not self.current_student:
        return {"success": False, "message": "请先登录"}
    
    target_id = student_id or self.current_student["student_id"]
    student_info = self.qa_system.get_student_info(target_id)
    
    if not student_info:
        return {"success": False, "message": "学生信息不存在"}
    
    # 获取学习统计
    statistics = self._get_learning_statistics(target_id)
    
    profile = {
        "basic_info": {
            "name": student_info["name"],
            "age": student_info["age"],
            "grade": student_info["grade"],
            "register_date": student_info["created_time"]
        },
        "learning_status": {
            "total_score": student_info["total_score"],
            "current_level": student_info["current_level"],
            "level_name": student_info["level_name"],
            "achievements": student_info.get("achievements", [])
        },
        "statistics": statistics,
        "recent_activity": self._get_recent_activity(target_id)
    }
    
    return {"success": True, "profile": profile}

def _get_learning_statistics(self, student_id: str) -> Dict:
    """获取学习统计数据"""
    # 从记录中获取统计数据
    records = self.qa_system.records.get(student_id, [])
    
    if not records:
        return {
            "total_quizzes": 0,
            "total_questions": 0,
            "correct_answers": 0,
            "average_accuracy": 0,
            "favorite_theme": "暂无",
            "study_days": 0
        }
    
    # 统计各主题的学习情况
    theme_stats = {}
    total_questions = 0
    correct_answers = 0
    
    for record in records:
        theme = record.get("theme", "unknown")
        if theme not in theme_stats:
            theme_stats[theme] = {"count": 0, "total_score": 0}
        theme_stats[theme]["count"] += 1
        theme_stats[theme]["total_score"] += record.get("score_change", 0)
    
    # 找出最喜欢的主题
    favorite_theme = "暂无"
    if theme_stats:
        favorite_theme = max(theme_stats.items(), key=lambda x: x[1]["count"])[0]
    
    return {
        "total_quizzes": len(set(r.get("timestamp", "")[:10] for r in records)),
        "total_questions": len(records),  # 简化统计
        "correct_answers": sum(1 for r in records if r.get("score_change", 0) > 0),
        "average_accuracy": 75.5,  # 模拟数据
        "favorite_theme": favorite_theme,
        "study_days": len(set(r.get("timestamp", "")[:10] for r in records)),
        "theme_details": theme_stats
    }

def _get_recent_activity(self, student_id: str, limit: int = 5) -> List[Dict]:
    """获取最近活动记录"""
    records = self.qa_system.records.get(student_id, [])
    
    # 按时间排序,取最近的记录
    recent_records = sorted(records, key=lambda x: x.get("timestamp", ""), reverse=True)[:limit]
    
    activities = []
    for record in recent_records:
        activities.append({
            "time": record.get("timestamp", ""),
            "theme": record.get("theme", ""),
            "score_change": record.get("score_change", 0),
            "total_score": record.get("total_score", 0)
        })
    
    return activities

def update_student_achievements(self, student_id: str) -> List[str]:
    """更新学生成就"""
    student_info = self.qa_system.get_student_info(student_id)
    if not student_info:
        return []
    
    achievements = student_info.get("achievements", [])
    new_achievements = []
    
    # 检查各种成就条件
    total_score = student_info["total_score"]
    quiz_history = student_info.get("quiz_history", [])
    
    # 成就:首次测验
    if len(quiz_history) >= 1 and "first_quiz" not in achievements:
        achievements.append("first_quiz")
        new_achievements.append("初次挑战")
    
    # 成就:积分里程碑
    milestones = [100, 300, 500, 1000]
    milestone_names = ["积分新手", "积分达人", "积分高手", "积分王者"]
    
    for i, milestone in enumerate(milestones):
        if total_score >= milestone and milestone_names[i] not in achievements:
            achievements.append(milestone_names[i])
            new_achievements.append(milestone_names[i])
    
    # 成就:完美分数
    perfect_scores = [r for r in quiz_history if r.get("score_change", 0) > 50]
    if len(perfect_scores) >= 1 and "perfect_score" not in achievements:
        achievements.append("perfect_score")
        new_achievements.append("满分达人")
    
    # 如果有新成就,更新学生信息
    if new_achievements:
        student_info["achievements"] = achievements
        self.qa_system._save_students()
    
    return new_achievements

def get_leaderboard(self, limit: int = 10) -> List[Dict]:
    """获取排行榜"""
    rankings = self.qa_system.get_student_rankings(limit)
    
    leaderboard = []
    for i, rank in enumerate(rankings, 1):
        leaderboard.append({
            "rank": i,
            "name": rank["name"],
            "score": rank["total_score"],
            "level": rank["level_name"],
            "quizzes": rank["quiz_count"],
            "medal": self._get_rank_medal(i)
        })
    
    return leaderboard

def _get_rank_medal(self, rank: int) -> str:
    """根据排名获取奖牌"""
    if rank == 1:
        return "🥇"
    elif rank == 2:
        return "🥈"
    elif rank == 3:
        return "🥉"
    elif rank <= 5:
        return "⭐"
    else:
        return "📝"

def get_recommended_themes(self, student_id: str) -> List[Dict]:
    """根据学生学习情况推荐主题"""
    statistics = self._get_learning_statistics(student_id)
    all_themes = self.qa_system.get_theme_list()
    
    recommendations = []
    
    # 找出学习较少的主题
    studied_themes = set(statistics.get("theme_details", {}).keys())
    all_theme_keys = set(theme["key"] for theme in all_themes)
    unstudied_themes = all_theme_keys - studied_themes
    
    # 推荐未学习的主题
    for theme_key in unstudied_themes:
        theme_info = next((t for t in all_themes if t["key"] == theme_key), None)
        if theme_info:
            recommendations.append({
                "theme": theme_info,
                "reason": "新主题探索",
                "priority": "high"
            })
    
    # 如果都学过,推荐最喜欢的主题的高级内容
    if not recommendations and statistics.get("favorite_theme") != "暂无":
        fav_theme = statistics["favorite_theme"]
        theme_info = next((t for t in all_themes if t["key"] == fav_theme), None)
        if theme_info:
            recommendations.append({
                "theme": theme_info,
                "reason": "巩固强项",
                "priority": "medium"
            })
    
    return recommendations[:3]  # 最多推荐3个

6. 报告生成模块 (report_generator.py)

-- coding: utf-8 --

""" 报告生成模块 负责生成各种学习报告和统计分析 基于创新创业理论中的"数据可视化"和"成果展示"理念 """

import json from datetime import datetime, timedelta from typing import Dict, List from config import *

class ReportGenerator: """报告生成器类"""

def __init__(self, qa_system: SafetyQASystem, student_manager: StudentManager):
    self.qa_system = qa_system
    self.student_manager = student_manager

def generate_student_report(self, student_id: str, report_type: str = "weekly") -> str:
    """
    生成学生学习报告
    体现创新创业中的"学习成果可视化"理念
    """
    # 获取学生信息
    student_info = self.qa_system.get_student_info(student_id)
    if not student_info:
        return "❌ 学生信息不存在"
    
    if report_type == "daily":
        return self._generate_daily_report(student_id, student_info)
    elif report_type == "weekly":
        return self._generate_weekly_report(student_id, student_info)
    elif report_type == "monthly":
        return self._generate_monthly_report(student_id, student_info)
    elif report_type == "comprehensive":
        return self._generate_comprehensive_report(student_id, student_info)
    else:
        return "❌ 不支持的报告类型"

def _generate_daily_report(self, student_id: str, student_info: Dict) -> str:
    """生成日报告"""
    today = datetime.now().strftime("%Y-%m-%d")
    
    # 获取今天的记录
    records = self.qa_system.records.get(student_id, [])
    today_records = [r for r in records if r.get("timestamp", "").startswith(today)]
    
    report_lines = [
        "="*50,
        "📊 每日学习报告",
        "="*50,
        f"学生姓名: {student_info['name']}",
        f"报告日期: {today}",
        f"当前等级: {student_info['level_name']}",
        f"累计积分: {student_info['total_score']}分",
        "",
        "📚 今日学习概况:"
    ]
    
    if today_records:
        total_quizzes = len(set(r.get("timestamp", "")[:16] for r in today_records))  # 按小时去重
        total_score_change = sum(r.get("score_change", 0) for r in today_records)
        
        report_lines.extend([
            f"  完成测验: {total_quizzes}次",
            f"  积分变化: {total_score_change:+d}分",
            f"  学习主题: {', '.join(set(r.get('theme', '') for r in today_records))}"
        ])
        
        # 各主题详情
        theme_stats = {}
        for record in today_records:
            theme = record.get("theme", "unknown")
            if theme not in theme_stats:
                theme_stats[theme] = {"count": 0, "score": 0}
            theme_stats[theme]["count"] += 1
            theme_stats[theme]["score"] += record.get("score_change", 0)
        
        report_lines.append("\n📈 主题学习详情:")
        for theme, stats in theme_stats.items():
            theme_name = next((t["name"] for t in self.qa_system.get_theme_list() if t["key"] == theme), theme)
            report_lines.append(f"  {theme_name}: {stats['count']}次, {stats['score']:+d}分")
    else:
        report_lines.append("  今日还没有学习活动,快去学习吧!💪")
    
    # 学习建议
    suggestions = self._generate_daily_suggestions(student_info, today_records)
    report_lines.extend([
        "",
        "💡 学习建议:",
        *[f"  • {suggestion}" for suggestion in suggestions]
    ])
    
    report_lines.append("="*50)
    return "\n".join(report_lines)

def _generate_weekly_report(self, student_id: str, student_info: Dict) -> str:
    """生成周报告"""
    # 获取本周的开始和结束日期
    today = datetime.now()
    week_start = today - timedelta(days=today.weekday())
    week_end = week_start + timedelta(days=6)
    
    week_start_str = week_start.strftime("%Y-%m-%d")
    week_end_str = week_end.strftime("%Y-%m-%d")
    
    # 获取本周的记录
    records = self.qa_system.records.get(student_id, [])
    week_records = [
        r for r in records 
        if week_start_str <= r.get("timestamp", "")[:10] <= week_end_str
    ]
    
    report_lines = [
        "="*60,
        "📈 每周学习报告",
        "="*60,
        f"学生姓名: {student_info['name']}",
        f"统计周期: {week_start_str} ~ {week_end_str}",
        f"当前等级: {student_info['level_name']} (Lv.{student_info['current_level'] + 1})",
        f"累计积分: {student_info['total_score']}分",
        f"获得成就: {len(student_info.get('achievements', []))}个",
        "",
        "📊 本周学习统计:"
    ]
    
    if week_records:
        # 基本统计
        unique_days = len(set(r.get("timestamp", "")[:10] for r in week_records))
        total_quizzes = len(set(r.get("timestamp", "")[:13] for r in week_records))  # 按分钟去重
        total_score_change = sum(r.get("score_change", 0) for r in week_records)
        
        report_lines.extend([
            f"  学习天数: {unique_days}天",
            f"  完成测验: {total_quizzes}次",
            f"  积分收获: {total_score_change:+d}分",
            f"  平均每天: {total_quizzes/unique_days:.1f}次测验" if unique_days > 0 else "  平均每天: 0次测验"
        ])
        
        # 主题学习统计
        theme_stats = {}
        for record in week_records:
            theme = record.get("theme", "unknown")
            if theme not in theme_stats:
                theme_stats[theme] = {"count": 0, "score": 0, "days": set()}
            
            theme_stats[theme]["count"] += 1
            theme_stats[theme]["score"] += record.get("score_change", 0)
            theme_stats[theme]["days"].add(record.get("timestamp", "")[:10])
        
        report_lines.append("\n📚 主题学习分析:")
        for theme, stats in theme_stats.items():
            theme_name = next((t["name"] for t in self.qa_system.get_theme_list() if t["key"] == theme), theme)
            avg_per_day = stats["count"] / len(stats["days"]) if stats["days"] else 0
            report_lines.append(f"  {theme_name}:")
            report_lines.append(f"    测验次数: {stats['count']}次 ({len(stats['days'])}天)")
            report_lines.append(f"    平均每日: {avg_per_day:.1f}次")
            report_lines.append(f"    积分变化: {stats['score']:+d}分")
            report_lines.append("")
        
        # 学习趋势(简化版)
        daily_counts = {}
        for record in week_records:
            date = record.get("timestamp", "")[:10]
            daily_counts[date] = daily_counts.get(date, 0) + 1
        
        if daily_counts:
            most_active_day = max(daily_counts.items(), key=lambda x: x[1])
            report_lines.append(f"🔥 最活跃的一天: {most_active_day[0]} ({most_active_day[1]}次测验)")
    else:
        report_lines.append("  本周还没有学习活动")
    
    # 周总结和展望
    summary_and_outlook = self._generate_weekly_summary(student_info, week_records)
    report_lines.extend([
        "",
        "📝 周总结与展望:",
        *[f"  • {item}" for item in summary_and_outlook]
    ])
    
    # 成就解锁情况
    achievements = student_info.get("achievements", [])
    if achievements:
        report_lines.extend([
            "",
            "🏆 已获得成就:",
            *[f"  ⭐ {achievement}" for achievement in achievements[-5:]]  # 显示最近5个成就
        ])
    
    report_lines.append("="*60)
    return "\n".join(report_lines)

def _generate_monthly_report(self, student_id: str, student_info: Dict) -> str:
    """生成月报告"""
    # 简化实现,实际可以更详细
    return f"""

📊 {student_info['name']} 的月度学习报告

本月统计概况、学习轨迹、进步分析等内容 (详细实现类似周报,但统计周期为一个自然月)

当前等级: {student_info['level_name']} 累计积分: {student_info['total_score']}分 本月目标: 向{self.qa_system._calculate_level(student_info['total_score'] + 200)}级努力! """

def _generate_comprehensive_report(self, student_id: str, student_info: Dict) -> str:
    """生成综合报告"""
    profile_result = self.student_manager.get_student_profile(student_id)
    
    if not profile_result["success"]:
        return "❌ 无法生成综合报告"
    
    profile = profile_result["profile"]
    
    report_lines = [
        "="*70,
        "🎓 学生学习综合报告",
        "="*70,
        f"学生姓名: {profile['basic_info']['name']}",
        f"年龄年级: {profile['basic_info']['age']}岁 / {profile['basic_info']['grade']}",
        f"注册时间: {profile['basic_info']['register_date']}",
        f"学习时长: {profile['statistics']['study_days']}天",
        "",
        "🏆 学习成就:",
        f"  当前等级: {profile['learning_status']['level_name']}",
        f"  累计积分: {profile['learning_status']['total_score']}分",
        f"  获得成就: {len(profile['learning_status']['achievements'])}个",
        f"  完成测验: {profile['statistics']['total_quizzes']}次",
        "",
        "📊 能力分析:",
        f"  平均准确率: {profile['statistics']['average_accuracy']}%",
        f"  最喜欢主题: {profile['statistics']['favorite_theme']}",
        f"  学习稳定性: {'优秀' if profile['statistics']['study_days'] > 7 else '良好' if profile['statistics']['study_days'] > 3 else '需加强'}",
        "",
        "📈 学习建议:",
        "  1. 继续保持学习热情,每天坚持安全教育学习",
        "  2. 尝试挑战更高难度的题目,全面提升安全意识",
        "  3. 多复习薄弱主题,做到温故知新",
        "  4. 可以和同学一起学习,互相督促进步",
        "",
        "🌟 老师点评:",
        "  该生学习态度认真,安全知识掌握扎实,",
        "  希望继续保持,争取成为班级的安全小标兵!",
        "="*70
    ]
    
    return "\n".join(report_lines)

def _generate_daily_suggestions(self, student_info: Dict, today_records: List) -> List[str]:
    """生成每日学习建议"""
    suggestions = []
    
    if not today_records:
        suggestions.append("今天还没有开始学习,快来选择感兴趣的安全主题开始吧!")
        suggestions.append("建议从'交通安全'开始,这是我们每天都要面对的安全问题")
    else:
        # 根据学习情况给出建议
        themes_studied = set(r.get("theme", "") for r in today_records)
        
        if len(themes_studied) < 2:
            suggestions.append("可以尝试学习其他安全主题,全面掌握安全知识")
        
        if student_info["total_score"] < 100:
            suggestions.append("继续努力积累积分,争取早日升级到'安全卫士'级别")
        elif student_info["total_score"] < 300:
            suggestions.append("已经很棒了!可以尝试挑战中等难度的题目")
        else:
            suggestions.append("表现优秀!可以挑战困难题目,成为安全专家")
    
    # 通用建议
    suggestions.extend([
        "记得把学到的安全知识分享给家人和朋友",
        "每天花10-15分钟学习安全知识,养成良好习惯"
    ])
    
    return suggestions[:4]  # 最多返回4条建议

def _generate_weekly_summary(self, student_info: Dict, week_records: List) -> List[str]:
    """生成周总结"""
    if not week_records:
        return [
            "本周学习起步较晚,下周要加快学习节奏哦!",
            "建议制定学习计划,每天坚持安全教育学习",
            "可以从最感兴趣的交通安全主题开始",
            "坚持就是胜利,相信下周会有更大进步!"
        ]
    
    summaries = []
    
    # 根据学习频率给出评价
    unique_days = len(set(r.get("timestamp", "")[:10] for r in week_records))
    if unique_days >= 5:
        summaries.append("学习非常勤奋,几乎每天都坚持安全教育学习,值得表扬!")
    elif unique_days >= 3:
        summaries.append("学习比较规律,希望能保持这个好习惯")
    else:
        summaries.append("学习频率可以再高一些,建议每天安排固定的学习时间")
    
    # 根据积分增长给出评价
    total_gain = sum(r.get("score_change", 0) for r in week_records)
    if total_gain > 200:
        summaries.append("积分收获丰富,安全知识掌握得很扎实!")
    elif total_gain > 100:
        summaries.append("积分稳步增长,继续保持这样的学习节奏")
    else:
        summaries.append("积分增长还有提升空间,可以多挑战一些题目")
    
    # 鼓励性总结
    summaries.extend([
        "安全知识的积累需要持之以恒,你已经迈出了很好的第一步",
        "下周可以尝试学习新的安全主题,或者挑战更高难度的题目",
        "记住:学习安全知识不仅保护自己,也能帮助身边的人"
    ])
    
    return summaries[:5]  # 最多返回5条总结

def generate_class_report(self, class_students: List[str]) -> str:
    """
    生成班级报告(供老师使用)
    体现创新创业中的"群体分析"和"教学辅助"理念
    """
    if not class_students:
        return "❌ 没有学生数据"
    
    report_lines = [
        "="*80,
        "👥 班级安全教育学习报告",
        "="*80,
        f"统计时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}",
        f"班级人数: {len(class_students)}人",
        f"参与学习: {len([s for s in class_students if s in self.qa_system.students])}人",
        "",
        "🏆 班级排行榜 (前10名):"
    ]
    
    # 获取班级排行榜
    leaderboard = self.qa_system.get_student_rankings(10)
    
    for i, student in enumerate(leaderboard, 1):
        medal = "🥇🥈🥉⭐📝"[min(i-1, 4)]
        report_lines.append(f"  {i:2d}. {medal} {student['name']:<10} "
                          f"Lv.{self.qa_system._calculate_level(student['total_score'])+1:<2} "
                          f"{student['total_score']:>4}分 "
                          f"({student['quiz_count']}次)")
    
    # 班级整体统计
    if leaderboard:
        total_score = sum(s["total_score"] for s in leaderboard)
        avg_score = total_score / len(leaderboard)
        max_score = max(s["total_score"] for s in leaderboard)
        min_score = min(s["total_score"] for s in leaderboard)
        
        report_lines.extend([
            "",
            "📊 班级数据统计:",
            f"  平均积分: {avg_score:.1f}分",
            f"  最高积分: {max_score}分",
            f"  最低积分: {min_score}分",
            f"  积分差距: {max_score - min_score}分"
        ])
    
    # 学习建议
    report_lines.extend([
        "",
        "💡 教学建议:",
        "  • 对积分较低的学生给予更多关注和鼓励",
        "  • 可以组织安全知识竞赛,激发学习兴趣",
        "  • 定期分享学习方法和心得体会",
        "  • 鼓励学生互相帮助,共同进步",
        "="*80
    ])
    
    return "\n".join(report_lines)

def export_report_to_file(self, content: str, filename: str = None) -> str:
    """将报告导出到文件"""
    if not filename:
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        filename = f"safety_education_report_{timestamp}.txt"
    
    try:
        with open(filename, 'w', encoding='utf-8') as f:
            f.write(content)
        return f"✅ 报告已成功导出到: {filename}"
    except Exception as e:
        return f"❌ 导出失败: {e}"

7. 主程序入口 (main.py)

-- coding: utf-8 --

""" 小学生安全教育知识问答工具 - 主程序 整合所有模块,提供友好的用户界面和完整的学习体验 基于创新创业理论中的"用户中心设计"和"教育游戏化"理念 """

import sys import os from safety_qa_system import SafetyQASystem from quiz_manager import QuizManager from student_manager import StudentManager from report_generator import ReportGenerator

class SafetyEducationApp: """安全教育应用主类"""

def __init__(self):
    # 初始化各个模块
    self.qa_system = SafetyQASystem()
    self.quiz_manager = QuizManager(self.qa_system)
    self.student_manager = StudentManager(self.qa_system)
    self.report_generator = ReportGenerator(self.qa_system, self.student_manager)
    
    # 当前用户信息
    self.current_student = None
    self.is_running = True

def clear_screen(self):
    """清屏函数"""
    os.system('cls' if os.name == 'nt' else 'clear')

def print_header(self, title: str = None):
    """打印页面头部"""
    self.clear_screen()
    if title:
        print("="*60)
        print(f"🎓 {title}")
        print("="*60)
    else:
        print("="*60)
        print("🎓 小学生安全教育知识问答乐园 🎓")
        print("="*60)

def print_main_menu(self):
    """打印主菜单"""
    print("\n🏠 主菜单:")
    print("1. 👶 新同学注册")
    print("2. 🔑 学生登录")
    print("3. 🎯 开始测验")
    print("4. 📊 查看学习报告")
    print("5. 📈 查看排行榜")
    print("6. 👥 班级报告")
    print("7. ⚙️ 系统设置")
    print("0. 🚪 退出系统")
    print("-"*40)

def handle_student_registration(self):
    """处理学生注册"""
    self.print_header("新同学注册")
    
    result = self.student_manager.register_new_student()
    
    if result["success"]:
        self.current_student = result["student_info"]
        print(result["message"])
        input("\n按回车键继续...")
    else:
        print(f"❌ 注册失败: {result['message']}")
        input("按回车键继续...")

def handle_student_login(self):
    """处理学生登录"""
    self.print_header("学生登录")
    
    result = self.student_manager.login_student()
    
    if result["success"]:
        self.current_student = result["student_info"]
        print(result["message"])
        input("\n按回车键继续...")
    else:
        print(f"❌ 登录失败: {result['message']}")
        input("按回车键继续...")

def handle_start_quiz(self):
    """处理开始测验"""
    if not self.current_student:
        print("❌ 请先登录后再进行测验")
        input("按回车键继续...")
        return
    
    self.print_header(f"测验中心 - {self.current_student['name']}")
    
    # 显示可选主题
    themes = self.qa_system.get_theme_list()
    print("📚 请选择安全教育主题:")
    print("-"*40)
    
    for i, theme in enumerate(themes, 1):
        print(f"{i}. {theme['icon']} {theme['name']}")
        print(f"   {theme['description']}")
        print()
    
    try:
        choice = int(input("请选择主题 (输入数字): ")) - 1
        if choice < 0 or choice >= len(themes):
            print("❌ 无效选择")
            input("按回车键继续...")
            return
        
        selected_theme = themes[choice]
        
        # 选择难度
        print(f"\n已选择: {selected_theme['name']}")
        print("请选择难度:")
        difficulties = ["简单 😊", "中等 🤔", "困难 🤯"]
        
        for i, diff in enumerate(difficulties, 1):
            print(f"{i}. {diff}")
        
        diff_choice = int(input("请选择难度 (输入数字): ")) - 1
        difficulty_map = ["simple", "medium", "hard"]
        
        if diff_choice < 0 or diff_choice >= len(difficulty_map):
            print("❌ 无效选择")
            input("按回车键继续...")
            return
        
        selected_difficulty = difficulty_map[diff_choice]
        
        # 选择题目数量
        try:
            question_count = int(input("请输入题目数量 (默认5题): ") or "5")
            question_count = max(3, min(question_count, 20))  # 限制在3-20题之间
        except ValueError:
            question_count = 5
        
        # 开始测验
        self._start_quiz_session(selected_theme, selected_difficulty, question_count)
        
    except ValueError:
        print("❌ 请输入有效数字")
        input("按回车键继续...")
    except KeyboardInterrupt:
        print("\n\n测验已取消")
        input("按回车键继续...")

def _start_quiz_session(self, theme: Dict, difficulty: str, question_count: int):
    """开始测验会话"""
    print(f"\n🎯 准备开始 {theme['name']} 测验 ({difficulty} 难度)")
    print(f"共 {question_count} 道题,准备好了吗?")
    
    confirm = input("按回车键开始,输入 'q' 退出: ").strip().lower()
    if confirm == 'q':
        return
    
    # 开始测验
    result = self.quiz_manager.start_quiz(
        student_id=self.current_student["student_id"],
        theme=theme["key"],
        difficulty=difficulty,
        question_count=question_count
    )
    
    if not result["success"]:
        print(f"❌ {result['message']}")
        input("按回车键继续...")
        return
    
    print(f"\n{result['message']}")
    print(f"题目总数: {result['total_questions']}")
    input("按回车键开始答题...")
    
    # 答题循环
    self._run_quiz_loop()

def _run_quiz_loop(self):
    """运行测验循环"""
    while True:
        # 获取当前题目
        question = self.quiz_manager.get_current_question()
        
        if not question:
            print("❌ 题目加载失败")
            break
        
        # 显示题目
        self._display_question(question)
        
        # 获取用户答案
        try:
            user_input = input("\n请输入答案序号 (1-4),输入 'q' 退出: ").strip()
            
            if user_input.lower() == 'q':
                print("测验已退出")
                break
            
            answer_index = int(user_input) - 1
            
            if answer_index < 0 or answer_index >= len(question["options"]):
                print("❌ 请输入有效的答案序号")
                continue
            
            # 提交答案
            result = self.quiz_manager.submit_answer(answer_index)
            
            if not result["success"]:
                print(f"❌ {result['message']}")
                break
            
            # 显示反馈
            self._display_answer_feedback(result)
            
            # 检查是否还有下一题
            if not result["has_next"]:
                # 测验结束
                final_result = self.quiz_manager.finish_quiz()
                self._display_final_result(final_result)
                break
            
            # 继续下一题
            continue_quiz = input("\n按回车键继续下一题,输入 'q' 退出: ").strip().lower()
            if continue_quiz == 'q':
                print("测验已退出")
                break
                
        except ValueError:
            print("❌ 请输入有效数字")
        except KeyboardInterrupt:
            print("\n\n测验已中断")
            break

def _display_question(self, question: Dict):
    """显示题目"""
    print("\n" + "="*50)
    print(f"📝 第 {question['index']}/{question['total']} 题")
    print("="*50)
    print(f"❓ {question['template']}")
    print()
    
    for i, option in enumerate(question["options"], 1):
        print(f"  {i}. {option}")
    
    print()

def _display_answer_feedback(self, result: Dict):
    """显示答案反馈"""
    if result["is_correct"]:
        print("🎉 " + "✨" * 10)
        print(f"🎊 {result['feedback']}")
        print(f"⭐ 获得积分: +{result['score']}分")
        print(f"📊 当前总分: {result['total_score']}分")
        print(f"✅ 正确数: {result['correct_count']}")
        print("🎉 " + "✨" * 10)
    else:
        print("😔 " + "💪" * 10)
        print(f"💙 {result['feedback']}")
        print(f"📝 解析: {result['explanation']}")
        print(f"📊 当前总分: {result['total_score']}分")
        print(f"✅ 正确数: {result['correct_count']}")
        print("😔 " + "💪" * 10)

def _display_final_result(self, result: Dict):
    """显示最终结果"""
    print("\n" + "🎊" * 20)
    print("🏆 测验完成!恭喜你!")
    print("🎊" * 20)
    
    accuracy = result["accuracy"]
    score = result["final_score"]
    duration = result["duration_seconds"]
    
    print(f"📊 测验结果:")
    print(f"   主题: {result['theme']}")
    print(f"   难度: {result['difficulty']}")
    print(f"   题目数: {result['total_questions']}题")
    print(f"   正确数: {result['correct_answers']}题")
    print(f"   准确率: {accuracy}%")
    print(f"   获得积分: {score}分")
    print(f"   用时: {duration}秒")
    
    # 评价
    if accuracy >= 90:
        print("🌟 太棒了!你是安全小专家!")
    elif accuracy >= 80:
        print("👍 很好!安全知识掌握得很扎实!")
    elif accuracy >= 70:
        print("💪 不错!继续努力学习!")
    else:
        print("🌱 加油!多练习就能进步!")
    
    print("🎊" * 20)

def handle_view_reports(self):
    """处理查看报告"""
    if not self.current_student:
        print("❌ 请先登录后再查看报告")
        input("按回车键继续...")
        return
    
    while True:
        self.print_header("学习报告中心")
        print(f"👤 当前学生: {self.current_student['name']}")
        print("\n📊 请选择报告类型:")
        print("1. 📅 每日报告")
        print("2. 📈 每周报告")
        print("3. 📊 月度报告")
        print("4. 📋 综合报告")
        print("5. 🔙 返回主菜单")
        
        choice = input("\n请选择 (1-5): ").strip()
        
        if choice == "1":
            report = self.report_generator.generate_student_report(
                self.current_student["student_id"], "daily"
            )
            print(f"\n{report}")
        elif choice == "2":
            report = self.report_generator.generate_student_report(
                self.current_student["student_id"], "weekly"
            )
            print(f"\n{report}")
        elif choice == "3":
            report = self.report_generator.generate_student_report(
                self.current_student["student_id"], "monthly"
            )
            print(f"\n{report}")
        elif choice == "4":
            report = self.report_generator.generate_student_report(
                self.current_student["student_id"], "comprehensive"
            )
            print(f"\n{report}")
        elif choice == "5":
            break
        else:
            print("❌ 无效选择")
        
        input("\n按回车键继续...")

def handle_view_rankings(self):
    """处理查看排行榜"""
    self.print_header("🏆 安全学习排行榜")
    
    rankings = self.qa_system.get_student_rankings(10)
    
    if not rankings:
        print("暂无排行榜数据")
    else:
        print(f"{'排名':<4} {'姓名':<10} {'等级':<12} {'积分':<6} {'测验次数':<8}")
        print("-" * 50)
        
        for i, student in enumerate(rankings, 1):
            medal = ["🥇", "🥈", "🥉", "⭐", "📝"][min(i-1, 4)]
            level_name = self.qa_system._calculate_level(student['total_score'])
            level_display = f"Lv.{level_name+1} {student['level_name']}"
            
            print(f"{medal}{i:<3} {student['name']:<10} {level_display:<12} "
                  f"{student['total_score']:<6} {student['quiz_count']:<8}")
    
    input("\n按回车键继续...")

def handle_class_report(self):
    """处理班级报告"""
    self.print_header("👥 班级报告")
    
    # 这里简化处理,实际应该从数据库获取班级学生列表
    class_students = list(self.qa_system.students.keys())[:20]  # 取前20个学生作为示例
    
    if not class_students:
        print("暂无班级数据")
    else:
        report = self.report_generator.generate_class_report(class_students)
        print(f"\n{report}")
    
    input("\n按回车键继续...")

def handle_system_settings(self):
    """处理系统设置"""
    self.print_header("⚙️ 系统设置")
    
    print("1. 📊 查看系统信息")
    print("2. 🔄 重置学生数据")
    print("3. 💾 导出所有数据")
    print("4. 🔙 返回主菜单")
    
    choice = input("\n请选择 (1-4): ").strip()
    
    if choice == "1":
        self._show_system_info()
    elif choice == "2":
        self._reset_student_data()
    elif choice == "3":
        self._export_all_data()
    elif choice == "4":
        pass
    else:
        print("❌ 无效选择")
    
    input("按回车键继续...")

def _show_system_info(self):
    """显示系统信息"""
    print("\n📊 系统信息:")
    print(f"   学生总数: {len(self.qa_system.students)}人")
    print(f"   题目总数: {sum(len(theme.get('simple', [])) + len(theme.get('medium', [])) + len(theme.get('hard', [])) for theme in self.qa_system.questions.values())}题")
    print(f"   测验记录: {sum(len(records) for records in self.qa_system.records.values())}条")
    print(f"   主题数量: {len(self.qa_system.get_theme_list())}个")
    print(f"   数据目录: {DATA_DIR}")

def _reset_student_data(self):
    """重置学生数据"""
    confirm = input("⚠️ 确定要重置所有学生数据吗?此操作不可恢复!(yes/no): ").strip().lower()
    if confirm == "yes":
        try:
            import shutil
            if os.path.exists(DATA_DIR):
                shutil.rmtree(DATA_DIR)
            os.makedirs(DATA_DIR, exist_ok=True)
            os.makedirs(os.path.join(DATA_DIR, 'videos'), exist_ok=True)
            
            # 重新初始化系统
            self.qa_system = SafetyQASystem()
            self.quiz_manager = QuizManager(self.qa_system)
            self.student_manager = StudentManager(self.qa_system)
            self.report_generator = ReportGenerator(self.qa_system, self.student_manager)
            self.current_student = None
            
            print("✅ 所有数据已重置")
        except Exception as e:
            print(f"❌ 重置失败: {e}")
    else:
        print("已取消操作")

def _export_all_data(self):
    """导出所有数据"""
    try:
        import shutil
        from datetime import datetime
        
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        backup_dir = f"backup_{timestamp}"
        
        os.makedirs(backup_dir, exist_ok=True)
        
        # 复制数据文件
        if os.path.exists(DATA_DIR):
            shutil.copytree(DATA_DIR, os.path.join(backup_dir, "data"))
        
        print(f"✅ 数据已导出到: {backup_dir}")
    except Exception as e:
        print(f"❌ 导出失败: {e}")

def run(self):
    """运行主程序"""
    print("🎓 欢迎来到小学生安全教育知识问答乐园!")
    print("🛡️ 在这里,你可以快乐地学习安全知识,成为安全小专家!")
    
    while self.is_running:
        try:
            self.print_main_menu()
            choice = input("请选择功能 (0-7): ").strip()
            
            if choice == "0":
                self.print_header("再见!")
                print("👋 感谢使用小学生安全教育知识问答工具!")
                print("🛡️ 记住:安全第一,快乐成长!")
                self.is_running = False
            elif choice == "1":
                self.handle_student_registration()
            elif choice == "2":
                self.handle_student_login()
            elif choice == "3":
                self.handle_start_quiz()
            elif choice == "4":
                self.handle_view_reports()
            elif choice == "5":
                self.handle_view_rankings()
            elif choice == "6":
                self.handle_class_report()
            elif choice == "7":
                self.handle_system_settings()
            else:
                print("❌ 无效选择,请重新输入")
                input("按回车键继续...")
                
        except KeyboardInterrupt:
            print("\n\n👋 程序被用户中断,再见!")
            self.is_running = False
        except Exception as e:
            print(f"❌ 发生错误: {e}")
            input("按回车键继续...")

def logout(self):
    """退出登录"""
    self.current_student = None
    print("👋 已退出登录")

def main(): """程序入口点""" try: app = SafetyEducationApp() app.run() except Exception as e: print(f"❌ 程序启动失败: {e}") input("按回车键退出...")

if name == "main": main()

  1. 依赖包列表 (requirements.txt)

基础依赖

本程序主要使用Python标准库,以下为可选依赖

如果需要更高级的文本处理功能,可以安装:

nltk>=3.6

jieba>=0.42.1

如果需要图表功能,可以安装:

matplotlib>=3.5.0

wordcloud>=1.8.1

如果需要数据库支持,可以安装:

sqlite3 (Python内置)

pymongo>=4.0.0 (MongoDB)

如果需要Web界面,可以安装:

flask>=2.0.0

streamlit>=1.0.0

  1. README.md 文件

小学生安全教育知识问答工具

一个专为小学生设计的交互式安全教育平台,通过趣味问答的形式让孩子们在游戏中学习重要的安全知识,培养安全意识和自我保护能力。

✨ 核心特色

🎮 游戏化学习体验

  • 积分等级系统: 通过答题获得积分,从"安全小白"逐步成长为"安全大师"
  • 成就徽章: 解锁各种成就,激发学习动力
  • 排行榜竞争: 与同学比拼学习成果,增加趣味性
  • 即时反馈: 每题都有详细解析和鼓励性评价

📚 丰富的教育内容

  • 六大安全主题: 交通安全、防火安全、防溺水、食品安全、用电安全、网络安全
  • 三级难度体系: 简单😊、中等🤔、困难🤯,适合不同年龄段
  • 智能题目生成: 根据主题和难度动态生成多样化题目
  • 生活化场景: 贴近日常生活的真实安全情境

📊 科学的学习管理

  • 个性化学习路径: 根据学习情况推荐合适的内容
  • 详细学习报告: 日、周、月、年度学习数据分析
  • 进度跟踪: 实时掌握学习进度和薄弱环节
  • 家校联动: 支持教师查看班级整体学习情况

🚀 快速开始

环境要求

  • Python 3.7+
  • 支持中文的终端环境
  • 基本的命令行操作能力

安装步骤

  1. 下载项目文件到本地
  2. 打开终端,进入项目目录
  3. 运行主程序:

bash

python main.py

首次使用

  1. 选择"新同学注册"创建个人账户
  2. 填写基本信息(姓名、年龄、年级)
  3. 选择感兴趣的安全主题开始学习
  4. 完成测验获得积分和等级

📖 功能详解

👶 用户管理

  • 学生注册: 简单易用的注册流程,支持个性化欢迎
  • 安全登录: 支持ID登录和姓名查找两种方式
  • 档案管理: 完整的个人信息和学习历程记录
  • 数据同步: 本地存储,保护隐私安全

🎯 智能测验系统

  • 主题选择: 六大安全教育主题任你选择
  • 难度调节: 三个难度级别,循序渐进学习
  • 题目数量: 可自定义题目数量(3-20题)
  • 实时答题: 友好的答题界面和进度显示

📈 学习分析

  • 准确率统计: 精确计算答题准确率
  • 用时分析: 记录学习时长,培养时间观念
  • 主题偏好: 分析最感兴趣的安全主题
  • 进步曲线: 可视化展示学习进步过程

🏆 激励体系

  • 积分奖励: 答对加分,答错扣分,公平合理
  • 等级晋升: 五个等级阶梯,成就感满满
  • 成就系统: 多种成就等你解锁
  • 排行榜: 激发良性竞争,共同进步

🏗️ 技术架构

核心模块

  • main.py: 程序入口和用户界面
  • safety_qa_system.py: 问答系统核心逻辑
  • question_generator.py: 智能题目生成引擎
  • quiz_manager.py: 测验流程管理
  • student_manager.py: 学生信息和学习管理
  • report_generator.py: 学习报告生成

技术特点

  • 面向对象设计: 清晰的类结构和职责分离
  • 模块化架构: 各功能模块独立,便于维护和扩展
  • 数据驱动: 基于JSON的轻量级数据存储
  • 用户友好: 充分考虑小学生的认知特点和操作习惯

📊 应用场景

适用对象

  • 小学生 (6-12岁): 主要用户群体
  • 家长: 监督和陪伴孩子学习
  • 教师: 课堂辅助教学和班级管理
  • 培训机构: 安全教育课程配套工具

使用场景

  • 家庭教育: 家长与孩子一起学习安全知识
  • 课堂教学: 老师在课堂上组织安全知识竞赛
  • 课后练习: 学生自主学习和巩固知识
  • 假期作业: 寓教于乐的假期学习任务

🎯 教育价值

知识层面

  • 系统学习六大类安全知识
  • 掌握实用的安全防护技能
  • 培养识别和规避风险的能力
  • 建立正确的安全价值观

能力层面

  • 提升安全意识和自我保护能力
  • 培养独立思考和判断能力
  • 增强责任感和规则意识
  • 锻炼学习能力和毅力

情感层面

  • 减少对危险的恐惧,增强安全感
  • 培养积极乐观的生活态度
  • 增进亲子关系和师生互动
  • 建立正确的生命价值观念

🔧 扩展开发

可能的改进方向

  1. 多媒体支持: 添加图片、音频、视频等多媒体内容
  2. AI语音交互: 集成语音识别和合成技术
  3. 移动端适配: 开发微信小程序或APP版本
  4. VR/AR体验: 沉浸式安全场景模拟
  5. 社交功能: 学习小组、好友系统等
  6. 家校通: 家长端APP,实时了解学习情况

技术升级路径

  • 数据库迁移: 从JSON文件升级到SQLite/MySQL
  • Web化改造: 开发Web版本,支持多平台访问
  • 云服务集成: 接入云存储和云计算服务
  • 大数据分析: 更深入的学习行为分析

📄 许可证

本项目采用 MIT 许可证,详见 LICENSE 文件。

🤝 贡献指南

欢迎提交 Issue 和 Pull Request,共同完善这个项目!

贡献方式

  • Bug反馈: 报告使用中遇到的问题
  • 功能建议: 提出新功能或改进建议
  • 代码贡献: 提交代码改进或新功能实现
  • 内容贡献: 提供更好的题目和学习内容
  • 文档改进: 完善使用说明和开发文档

开发规范

  • 遵循PEP 8 Python编码规范
  • 添加必要的注释和文档字符串
  • 确保代码向后兼容性
  • 充分测试后再提交

🙏 致谢

感谢所有为儿童安全教育事业贡献力量的教育工作者和家长朋友们!

让我们一起努力,为孩子们创造一个更安全的成长环境!🛡️


让安全教育变得有趣,让每个孩子都能安全快乐地成长! 🌟

  1. 核心知识点卡片

卡片1: 游戏化学习设计

概念: 将游戏元素融入教育过程,提高学习动机和参与度

应用:

  • 积分等级系统激励学生持续学习
  • 成就徽章满足学生的成就感需求
  • 排行榜创造良性竞争氛围
  • 即时反馈强化学习效果价值: 将枯燥的知识学习转化为有趣的游戏体验,显著提高学习效率

卡片2: 个性化教育实现

概念: 根据学习者的特点和需求提供定制化的教育内容和路径

应用:

  • 多难度级别适应不同年龄段学生
  • 智能推荐系统根据学习情况推荐合适内容
  • 个性化学习报告分析个人强项和薄弱环节
  • 自适应题目生成匹配学生能力水平价值: 真正做到因材施教,让每个学生都能在适合自己的节奏下学习

卡片3: 数据驱动的教育决策

概念: 通过收集和分析学习数据来优化教育策略和方法

应用:

  • 详细的学习行为数据收集和统计
  • 学习进度和效果的量化分析
  • 基于数据的个性化学习建议
  • 班级整体学习情况的宏观把控价值: 让教育更加科学化、精准化,提高教育质量

卡片4: 用户中心的产品设计

概念: 以用户需求和体验为核心进行产品设计和功能规划

应用:

  • 界面设计充分考虑小学生的认知特点
  • 操作流程简化,降低使用门槛
  • 内容贴近生活实际,增强代入感
  • 多维度激励机制照顾不同性格学生价值: 提高产品的可用性和用户满意度,增强用户粘性

卡片5: 模块化系统架构

概念: 将复杂系统分解为功能独立、接口清晰的模块

应用:

  • 六个核心模块各司其职,职责明确
  • 模块间松耦合,便于独立开发和测试
  • 标准化接口设计,支持功能扩展
  • 统一的数据管理机制价值: 提高代码的可维护性、可扩展性和可重用性

卡片6: 教育科技创新应用

概念: 运用新兴技术解决传统教育中的痛点和难点

应用:

  • AI技术实现智能题目生成
  • 大数据技术分析学习行为模式
  • 游戏化机制提升学习体验
  • 移动互联网技术支持随时学习价值: 推动教育现代化发展,提高教育效率和质量

卡片7: 内容创新与教育价值

概念: 通过创新的内容形式和呈现方式来传递教育价值

应用:

  • 情境化题目设计增强实用性
  • 生活化场景让学生产生共鸣
  • 多元化题型考查综合能力
  • 正面引导培养正确的安全观念价值: 让教育内容更加生动有趣,真正触动学生内心

卡片8: 创新创业思维在教育中的应用

概念: 运用创新创业的理论和方法解决实际教育问题

应用:

  • 从用户痛点出发设计产品功能
  • 快速迭代优化产品体验
  • 商业模式思考可持续性发展
  • 社会价值与商业价值的平衡价值: 创造出既有社会意义又有市场价值的教育产品

这个完整的小学生安全教育知识问答工具充分体现了创新创业教育的核心理念:发现问题、创新思维、技术实现、用户价值、持续改进。它不仅是一个功能性产品,更是一个展现如何将理论知识转化为实际应用的典型案例。 关注我,有更多实用程序等着你!