refactor(utils): 移除自定义加权随机函数并改用 random.choices

将原先在 `bot.py` 中实现的 `weighted_choice` 函数移除,并在 `src/main.py` 中改用 Python 内置的 `random.choices` 函数来实现启动时彩蛋的加权随机选择。

这一更改简化了代码,提高了可读性,并利用了标准库的优化实现。同时调整了彩蛋文本和对应的权重。
This commit is contained in:
minecraft1024a
2025-08-19 12:15:24 +08:00
parent e633ced332
commit 1b2c5393e5
2 changed files with 20 additions and 53 deletions

43
bot.py
View File

@@ -25,8 +25,6 @@ initialize_logging()
from src.main import MainSystem #noqa
from src.manager.async_task_manager import async_task_manager #noqa
from colorama import init, Fore
import random
from typing import List, Sequence, Optional
@@ -65,49 +63,10 @@ async def request_shutdown() -> bool:
logger.error(f"请求关闭程序时发生错误: {e}")
return False
def weighted_choice(data: Sequence[str],
weights: Optional[List[float]] = None) -> str:
"""
从 data 中按权重随机返回一条。
若 weights 为 None则所有元素权重默认为 1。
"""
if weights is None:
weights = [1.0] * len(data)
if len(data) != len(weights):
raise ValueError("data 和 weights 长度必须相等")
# 计算累计权重区间
total = 0.0
acc = []
for w in weights:
total += w
acc.append(total)
if total <= 0:
raise ValueError("总权重必须大于 0")
# 随机落点
r = random.random() * total
# 二分查找落点所在的区间
left, right = 0, len(acc) - 1
while left < right:
mid = (left + right) // 2
if r < acc[mid]:
right = mid
else:
left = mid + 1
return data[left]
def easter_egg():
# 彩蛋
init()
items = ["多年以后面对AI行刑队张三将会回想起他2023年在会议上讨论人工智能的那个下午",
"你知道吗诺狐的耳朵很软很好rua",
"喵喵~你的麦麦被猫娘入侵了喵~",
"恭喜你触发了稀有彩蛋:诺狐嗷呜~ ~"]
w = [15, 6, 8, 0.0001]
text = weighted_choice(items, w)
text = "多年以后面对AI行刑队张三将会回想起他2023年在会议上讨论人工智能的那个下午"
rainbow_colors = [Fore.RED, Fore.YELLOW, Fore.GREEN, Fore.CYAN, Fore.BLUE, Fore.MAGENTA]
rainbow_text = ""
for i, char in enumerate(text):