diff --git a/src/dinner.py b/src/dinner.py index 1544ab8..0b5a53e 100644 --- a/src/dinner.py +++ b/src/dinner.py @@ -33,7 +33,7 @@ def fetch_user_menu_summary() -> dict[str, float]: all_menu = list(fetch_all_user_today_menu()) if len(all_menu) > 0: menus = list(map(lambda x: json.loads(x[1]), all_menu)) - menu_keys = set(chain.from_iterable(menus)) + menu_keys = set(chain(*menus)) result = {} for k in menu_keys: result[k] = 0 @@ -79,6 +79,7 @@ def vote_reduce(summary: dict[str, float]) -> tuple[dict[str, float], float, str name, _, expression = menu if expression is None or name not in summary.keys(): continue + # 计算预定路由规则 new_name = eval(expression, {'total_vote': total_vote}) if new_name != name: if summary.get(new_name) is None: @@ -86,9 +87,9 @@ def vote_reduce(summary: dict[str, float]) -> tuple[dict[str, float], float, str else: summary[new_name] += summary[name] summary[name] = 0 - for k in summary: - if last_result == k: - summary[k] = summary[k] * 7 / 10 + # 昨日中签项降低权重 + if last_result in summary: + summary[last_result] = summary[last_result] * 7 / 10 total_vote = sum(value for value in summary.values()) return summary, total_vote, last_result @@ -109,10 +110,12 @@ def dinner_update(): set_user_menu('') return make_response(json.dumps(dict(code=0, data="OK"))) user_menu = json.loads(user_menu) + # 计算总投票数值 summary = sum(abs(int(value)) for value in user_menu.values()) if summary <= 0: set_user_menu('') return make_response(json.dumps(dict(code=0, data="OK"))) + # 投票数归一化 for key in user_menu: user_menu[key] = abs(int(user_menu[key])) / summary set_user_menu(json.dumps(user_menu, ensure_ascii=False)) @@ -128,12 +131,9 @@ def dinner_roll(): if check_roll() != 1: return make_response(json.dumps(dict(code=-1, data="目前不能抽签"))) summary, _, _ = vote_reduce(fetch_user_menu_summary()) - for k in summary: - summary[k] = int(round(summary[k] * 100)) - pool = [] - for k in summary: - for i in range(int(summary[k])): - pool.append(k) + # 票数乘以100四舍五入取整,投入抽奖池 + pool = list(chain(*[[name] * int(round(summary[name] * 100)) for name in summary])) + # Knuth-Durstenfeld Shuffle算法洗牌: 从后往前依次随机将未乱序元素交换到当前位置,直到所有元素均被打乱 random.shuffle(pool) result = pool[0] set_roll_result(result) diff --git a/templates/dinner.html b/templates/dinner.html index 1bd9f26..4b3e450 100644 --- a/templates/dinner.html +++ b/templates/dinner.html @@ -35,7 +35,7 @@