ChinaHamRadioQuest/Generator.py

65 lines
2.3 KiB
Python
Raw Normal View History

import json
import os
import random
import Config
class Quest:
def __init__(self, json_obj):
self.index = json_obj['index']
self.question = json_obj['Q']
self.code = json_obj['I']
self.correct = json_obj['A']
self.options = [json_obj['A'], json_obj['B'], json_obj['C'], json_obj['D']]
self.random_options = random.sample(self.options, len(self.options))
weight_path = 'weight.dat'
def enhance_weight(quest: Quest):
with open(weight_path, 'r') as f:
weight = json.load(f)
if quest.code in weight:
weight[quest.code] += 10
else:
weight[quest.code] = 10
with open(weight_path, 'w') as f:
json.dump(weight, f, ensure_ascii=False, indent=4)
pass
def reduce_weight(quest: Quest):
with open(weight_path, 'r') as f:
weight = json.load(f)
if quest.code in weight:
weight[quest.code] -= 1
else:
weight[quest.code] = -1
with open(weight_path, 'w') as f:
json.dump(weight, f, ensure_ascii=False, indent=4)
pass
# 模拟加载题目
def generate_quests(type_str):
# 模拟从JSON文件加载题目
with open(f'quests/quests_{type_str}.json', 'r', encoding='utf-8') as f:
json_content = json.load(f)
list_quest = [Quest(obj) for obj in json_content]
# load weight
weights = {}
if not os.path.exists(weight_path):
with open(weight_path, 'w') as f:
json.dump({}, f)
else:
with open(weight_path, 'r') as f:
weights = json.load(f)
# 将 list_quest 分为有权重和无权重的两部分
list_quest_weighted = [quest for quest in list_quest if quest.code in weights]
list_quest_unweighted = [quest for quest in list_quest if quest.code not in weights]
# 有权中的按权重排序
list_quest_weighted.sort(key=lambda x: weights[x.code], reverse=True)
list_quest = list_quest_unweighted + list_quest_weighted
# 根据权重随机选取题目 80% 的题目来自权重前 40% 的题目 20% 的题目来自权重后 60% 的题目
num = Config.quest_config[type_str]['num'] # 要生成的题目数量
top = int(num * 0.8)
quests = random.sample(list_quest[:top], top) + random.sample(list_quest[top:], num - top)
# 对 quests 中的题目再次随机排序
random.shuffle(quests)
return quests