1
0

utils_cn.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  1. # -*- coding: utf-8 -*-
  2. """三国狼人杀游戏工具函数"""
  3. import asyncio
  4. import random
  5. from typing import List, Dict, Optional, Any
  6. from collections import Counter
  7. from agentscope.agent import AgentBase
  8. from agentscope.message import Msg
  9. # 游戏常量
  10. MAX_GAME_ROUND = 10
  11. MAX_DISCUSSION_ROUND = 3
  12. CHINESE_NAMES = [
  13. "刘备", "关羽", "张飞", "诸葛亮", "赵云",
  14. "曹操", "司马懿", "典韦", "许褚", "夏侯惇",
  15. "孙权", "周瑜", "陆逊", "甘宁", "太史慈",
  16. "吕布", "貂蝉", "董卓", "袁绍", "袁术"
  17. ]
  18. def get_chinese_name(character: str = None) -> str:
  19. """获取中文角色名"""
  20. if character and character in CHINESE_NAMES:
  21. return character
  22. return random.choice(CHINESE_NAMES)
  23. def format_player_list(players: List[AgentBase], show_roles: bool = False) -> str:
  24. """格式化玩家列表为中文显示"""
  25. if not players:
  26. return "无玩家"
  27. if show_roles:
  28. return "、".join([f"{p.name}({getattr(p, 'role', '未知')})" for p in players])
  29. else:
  30. return "、".join([p.name for p in players])
  31. def majority_vote_cn(votes: Dict[str, str]) -> tuple[str, int]:
  32. """中文版多数投票统计"""
  33. if not votes:
  34. return "无人", 0
  35. vote_counts = Counter(votes.values())
  36. most_voted = vote_counts.most_common(1)[0]
  37. return most_voted[0], most_voted[1]
  38. def check_winning_cn(alive_players: List[AgentBase], roles: Dict[str, str]) -> Optional[str]:
  39. """检查中文版游戏胜利条件"""
  40. alive_roles = [roles.get(p.name, "村民") for p in alive_players]
  41. werewolf_count = alive_roles.count("狼人")
  42. villager_count = len(alive_roles) - werewolf_count
  43. if werewolf_count == 0:
  44. return "好人阵营胜利!所有狼人已被淘汰!"
  45. elif werewolf_count >= villager_count:
  46. return "狼人阵营胜利!狼人数量已达到或超过好人!"
  47. return None
  48. def analyze_speech_pattern(speech: str) -> Dict[str, Any]:
  49. """分析发言模式(中文优化)"""
  50. analysis = {
  51. "word_count": len(speech),
  52. "confidence_keywords": 0,
  53. "doubt_keywords": 0,
  54. "emotion_score": 0
  55. }
  56. # 中文关键词分析
  57. confidence_words = ["确定", "肯定", "一定", "绝对", "必须", "显然"]
  58. doubt_words = ["可能", "也许", "或许", "怀疑", "不确定", "感觉"]
  59. for word in confidence_words:
  60. analysis["confidence_keywords"] += speech.count(word)
  61. for word in doubt_words:
  62. analysis["doubt_keywords"] += speech.count(word)
  63. # 简单情感分析
  64. positive_words = ["好", "棒", "赞", "支持", "同意"]
  65. negative_words = ["坏", "差", "反对", "不行", "错误"]
  66. for word in positive_words:
  67. analysis["emotion_score"] += speech.count(word)
  68. for word in negative_words:
  69. analysis["emotion_score"] -= speech.count(word)
  70. return analysis
  71. class GameModerator(AgentBase):
  72. """中文版游戏主持人"""
  73. def __init__(self) -> None:
  74. super().__init__()
  75. self.name = "游戏主持人"
  76. self.game_log: List[str] = []
  77. async def announce(self, content: str) -> Msg:
  78. """发布游戏公告"""
  79. msg = Msg(
  80. name=self.name,
  81. content=f"📢 {content}",
  82. role="system"
  83. )
  84. self.game_log.append(content)
  85. await self.print(msg)
  86. return msg
  87. async def night_announcement(self, round_num: int) -> Msg:
  88. """夜晚阶段公告"""
  89. content = f"🌙 第{round_num}夜降临,天黑请闭眼..."
  90. return await self.announce(content)
  91. async def day_announcement(self, round_num: int) -> Msg:
  92. """白天阶段公告"""
  93. content = f"☀️ 第{round_num}天天亮了,请大家睁眼..."
  94. return await self.announce(content)
  95. async def death_announcement(self, dead_players: List[str]) -> Msg:
  96. """死亡公告"""
  97. if not dead_players:
  98. content = "昨夜平安无事,无人死亡。"
  99. else:
  100. content = f"昨夜,{format_player_list_str(dead_players)}不幸遇害。"
  101. return await self.announce(content)
  102. async def vote_result_announcement(self, voted_out: str, vote_count: int) -> Msg:
  103. """投票结果公告"""
  104. content = f"投票结果:{voted_out}以{vote_count}票被淘汰出局。"
  105. return await self.announce(content)
  106. async def game_over_announcement(self, winner: str) -> Msg:
  107. """游戏结束公告"""
  108. content = f"🎉 游戏结束!{winner}"
  109. return await self.announce(content)
  110. def format_player_list_str(players: List[str]) -> str:
  111. """格式化玩家姓名列表"""
  112. if not players:
  113. return "无人"
  114. return "、".join(players)
  115. def calculate_suspicion_score(player_name: str, game_history: List[Dict]) -> float:
  116. """计算玩家可疑度分数"""
  117. score = 0.0
  118. for event in game_history:
  119. if event.get("type") == "vote" and event.get("target") == player_name:
  120. score += 0.3
  121. elif event.get("type") == "accusation" and event.get("target") == player_name:
  122. score += 0.2
  123. elif event.get("type") == "defense" and event.get("player") == player_name:
  124. score -= 0.1
  125. return min(max(score, 0.0), 1.0)
  126. async def handle_interrupt(*args: Any, **kwargs: Any) -> Msg:
  127. """处理游戏中断"""
  128. return Msg(
  129. name="系统",
  130. content="游戏被中断",
  131. role="system"
  132. )