1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861
| """ 三国狼人杀 - 基于AgentScope的中文版狼人杀游戏 融合三国演义角色和传统狼人杀玩法
本文件由 chapter6/AgentScopeDemo 下的多个脚本合并而成: - prompt_cn.py -> ChinesePrompts - game_roles.py -> GameRoles - structured_output_cn.py -> 结构化输出模型 - utils_cn.py -> 工具函数与 GameModerator - main_cn.py -> ThreeKingdomsWerewolfGame 与主流程 """
import asyncio import os import random from typing import List, Dict, Optional, Any, Literal from collections import Counter
from dotenv import load_dotenv from pydantic import BaseModel, Field from agentscope.agent import ReActAgent, AgentBase from agentscope.model import OpenAIChatModel from agentscope.pipeline import MsgHub, sequential_pipeline, fanout_pipeline from agentscope.formatter import OpenAIMultiAgentFormatter from agentscope.message import Msg
load_dotenv()
class ChinesePrompts: """中文提示词管理类"""
@staticmethod def get_role_prompt(role: str, character: str) -> str: """获取角色提示词""" base_prompt = f"""你是{character},在这场三国狼人杀游戏中扮演{role}。
请严格按照以下JSON格式回复,不要添加任何其他文字: {{ "reach_agreement": true/false, "confidence_level": 1-10的数字, "key_evidence": "你的证据或观点" }}
角色特点: """
if role == "狼人": return base_prompt + f""" - 你是狼人阵营,目标是消灭所有好人 - 夜晚可以与其他狼人协商击杀目标 - 白天要隐藏身份,误导好人 - 以{character}的性格说话和行动 """ elif role == "预言家": return base_prompt + f""" - 你是好人阵营的预言家,目标是找出所有狼人 - 每晚可以查验一名玩家的真实身份 - 要合理公布查验结果,引导好人投票 - 以{character}的智慧和洞察力分析局势 """ elif role == "女巫": return base_prompt + f""" - 你是好人阵营的女巫,拥有解药和毒药各一瓶 - 解药可以救活被狼人击杀的玩家 - 毒药可以毒杀一名玩家 - 要谨慎使用道具,在关键时刻发挥作用 """ elif role == "猎人": return base_prompt + f""" - 你是好人阵营的猎人 - 被投票出局时可以开枪带走一名玩家 - 要在关键时刻使用技能,带走狼人 - 以{character}的勇猛和决断力行动 """ else: return base_prompt + f""" - 你是好人阵营的村民 - 没有特殊技能,只能通过推理和投票 - 要仔细观察,找出狼人的破绽 - 以{character}的性格参与讨论 """
class GameRoles: """游戏角色管理类"""
ROLES = { "狼人": { "description": "狼人", "ability": "夜晚可以击杀一名玩家", "win_condition": "消灭所有好人或与好人数量相等", "team": "狼人阵营" }, "预言家": { "description": "预言家",a "ability": "每晚可以查验一名玩家的身份", "win_condition": "消灭所有狼人", "team": "好人阵营" }, "女巫": { "description": "女巫", "ability": "拥有解药和毒药各一瓶,可以救人或杀人", "win_condition": "消灭所有狼人", "team": "好人阵营" }, "猎人": { "description": "猎人", "ability": "被投票出局时可以开枪带走一名玩家", "win_condition": "消灭所有狼人", "team": "好人阵营" }, "村民": { "description": "村民", "ability": "无特殊技能,依靠推理和投票", "win_condition": "消灭所有狼人", "team": "好人阵营" }, "守护者": { "description": "守护者", "ability": "每晚可以守护一名玩家免受狼人攻击", "win_condition": "消灭所有狼人", "team": "好人阵营" } }
CHARACTER_TRAITS = { "刘备": "仁德宽厚,善于团结众人,说话温和有礼", "关羽": "忠义刚烈,言辞直接,重情重义", "张飞": "性格豪爽,说话大声直接,容易冲动", "诸葛亮": "智慧超群,分析透彻,言辞谨慎", "赵云": "忠勇双全,话语简洁有力", "曹操": "雄才大略,善于权谋,话语犀利", "司马懿": "深谋远虑,城府极深,言辞含蓄", "周瑜": "才华横溢,略显傲气,分析精准", "孙权": "年轻有为,善于决断,话语果决" }
@classmethod def get_role_desc(cls, role: str) -> str: """获取角色描述""" return cls.ROLES.get(role, {}).get("description", "未知角色")
@classmethod def get_role_ability(cls, role: str) -> str: """获取角色技能""" return cls.ROLES.get(role, {}).get("ability", "无特殊技能")
@classmethod def get_character_trait(cls, character: str) -> str: """获取角色性格特点""" return cls.CHARACTER_TRAITS.get(character, "性格温和,说话得体")
@classmethod def is_werewolf(cls, role: str) -> bool: """判断是否为狼人""" return role == "狼人"
@classmethod def is_villager_team(cls, role: str) -> bool: """判断是否为好人阵营""" return cls.ROLES.get(role, {}).get("team") == "好人阵营"
@classmethod def get_standard_setup(cls, player_count: int) -> List[str]: """获取标准角色配置""" if player_count == 6: return ["狼人", "狼人", "预言家", "女巫", "村民", "村民"] elif player_count == 8: return ["狼人", "狼人", "狼人", "预言家", "女巫", "猎人", "村民", "村民"] elif player_count == 9: return ["狼人", "狼人", "狼人", "预言家", "女巫", "猎人", "守护者", "村民", "村民"] else: werewolf_count = max(1, player_count // 3) roles = ["狼人"] * werewolf_count
remaining = player_count - werewolf_count if remaining >= 1: roles.append("预言家") remaining -= 1 if remaining >= 1: roles.append("女巫") remaining -= 1 if remaining >= 1: roles.append("猎人") remaining -= 1
roles.extend(["村民"] * remaining)
return roles
class DiscussionModelCN(BaseModel): """中文版讨论输出格式"""
reach_agreement: bool = Field( description="是否已达成一致意见", ) confidence_level: int = Field( description="对当前推理的信心程度(1-10)", ge=1, le=10 ) key_evidence: Optional[str] = Field( description="支持你观点的关键证据", default=None )
def get_vote_model_cn(agents: list[AgentBase]) -> type[BaseModel]: """获取中文版投票模型"""
class VoteModelCN(BaseModel): """中文版投票输出格式"""
vote: Literal[tuple(_.name for _ in agents)] = Field( description="你要投票淘汰的玩家姓名", ) reason: str = Field( description="投票理由,简要说明为什么选择此人", ) suspicion_level: int = Field( description="对被投票者的怀疑程度(1-10)", ge=1, le=10 )
return VoteModelCN
class WitchActionModelCN(BaseModel): """中文版女巫行动模型"""
use_antidote: bool = Field( description="是否使用解药救人", default=False ) use_poison: bool = Field( description="是否使用毒药杀人", default=False ) target_name: Optional[str] = Field( description="目标玩家姓名(救人或毒杀的对象)", default=None ) action_reason: Optional[str] = Field( description="行动理由", default=None )
def get_seer_model_cn(agents: list[AgentBase]) -> type[BaseModel]: """获取中文版预言家模型"""
class SeerModelCN(BaseModel): """中文版预言家查验格式"""
target: Literal[tuple(_.name for _ in agents)] = Field( description="要查验的玩家姓名", ) check_reason: str = Field( description="查验此人的原因", ) priority_level: int = Field( description="查验优先级(1-10)", ge=1, le=10 )
return SeerModelCN
def get_hunter_model_cn(agents: list[AgentBase]) -> type[BaseModel]: """获取中文版猎人模型"""
class HunterModelCN(BaseModel): """中文版猎人开枪格式"""
shoot: bool = Field( description="是否使用开枪技能", ) target: Optional[Literal[tuple(_.name for _ in agents)]] = Field( description="开枪目标玩家姓名", default=None ) shoot_reason: Optional[str] = Field( description="开枪理由", default=None )
return HunterModelCN
class WerewolfKillModelCN(BaseModel): """中文版狼人击杀模型"""
target: str = Field( description="要击杀的玩家姓名", ) kill_strategy: str = Field( description="击杀策略说明", ) team_coordination: Optional[str] = Field( description="与狼队友的配合计划", default=None )
class GameAnalysisModelCN(BaseModel): """中文版游戏分析模型"""
suspected_werewolves: List[str] = Field( description="怀疑的狼人名单", default_factory=list ) trusted_players: List[str] = Field( description="信任的玩家名单", default_factory=list ) key_clues: List[str] = Field( description="关键线索列表", default_factory=list ) next_strategy: str = Field( description="下一步策略", )
MAX_GAME_ROUND = 10 MAX_DISCUSSION_ROUND = 3 CHINESE_NAMES = [ "刘备", "关羽", "张飞", "诸葛亮", "赵云", "曹操", "司马懿", "典韦", "许褚", "夏侯惇", "孙权", "周瑜", "陆逊", "甘宁", "太史慈", "吕布", "貂蝉", "董卓", "袁绍", "袁术" ]
def get_chinese_name(character: str = None) -> str: """获取中文角色名""" if character and character in CHINESE_NAMES: return character return random.choice(CHINESE_NAMES)
def format_player_list(players: List[AgentBase], show_roles: bool = False) -> str: """格式化玩家列表为中文显示""" if not players: return "无玩家"
if show_roles: return "、".join([f"{p.name}({getattr(p, 'role', '未知')})" for p in players]) else: return "、".join([p.name for p in players])
def majority_vote_cn(votes: Dict[str, str]) -> tuple[str, int]: """中文版多数投票统计""" if not votes: return "无人", 0
vote_counts = Counter(votes.values()) most_voted = vote_counts.most_common(1)[0]
return most_voted[0], most_voted[1]
def check_winning_cn(alive_players: List[AgentBase], roles: Dict[str, str]) -> Optional[str]: """检查中文版游戏胜利条件""" alive_roles = [roles.get(p.name, "村民") for p in alive_players] werewolf_count = alive_roles.count("狼人") villager_count = len(alive_roles) - werewolf_count
if werewolf_count == 0: return "好人阵营胜利!所有狼人已被淘汰!" elif werewolf_count >= villager_count: return "狼人阵营胜利!狼人数量已达到或超过好人!"
return None
def analyze_speech_pattern(speech: str) -> Dict[str, Any]: """分析发言模式(中文优化)""" analysis = { "word_count": len(speech), "confidence_keywords": 0, "doubt_keywords": 0, "emotion_score": 0 }
confidence_words = ["确定", "肯定", "一定", "绝对", "必须", "显然"] doubt_words = ["可能", "也许", "或许", "怀疑", "不确定", "感觉"]
for word in confidence_words: analysis["confidence_keywords"] += speech.count(word)
for word in doubt_words: analysis["doubt_keywords"] += speech.count(word)
positive_words = ["好", "棒", "赞", "支持", "同意"] negative_words = ["坏", "差", "反对", "不行", "错误"]
for word in positive_words: analysis["emotion_score"] += speech.count(word)
for word in negative_words: analysis["emotion_score"] -= speech.count(word)
return analysis
class GameModerator(AgentBase): """中文版游戏主持人"""
def __init__(self) -> None: super().__init__() self.name = "游戏主持人" self.game_log: List[str] = []
async def announce(self, content: str) -> Msg: """发布游戏公告""" msg = Msg( name=self.name, content=f"📢 {content}", role="system" ) self.game_log.append(content) await self.print(msg) return msg
async def night_announcement(self, round_num: int) -> Msg: """夜晚阶段公告""" content = f"🌙 第{round_num}夜降临,天黑请闭眼..." return await self.announce(content)
async def day_announcement(self, round_num: int) -> Msg: """白天阶段公告""" content = f"☀️ 第{round_num}天天亮了,请大家睁眼..." return await self.announce(content)
async def death_announcement(self, dead_players: List[str]) -> Msg: """死亡公告""" if not dead_players: content = "昨夜平安无事,无人死亡。" else: content = f"昨夜,{format_player_list_str(dead_players)}不幸遇害。" return await self.announce(content)
async def vote_result_announcement(self, voted_out: str, vote_count: int) -> Msg: """投票结果公告""" content = f"投票结果:{voted_out}以{vote_count}票被淘汰出局。" return await self.announce(content)
async def game_over_announcement(self, winner: str) -> Msg: """游戏结束公告""" content = f"🎉 游戏结束!{winner}" return await self.announce(content)
def format_player_list_str(players: List[str]) -> str: """格式化玩家姓名列表""" if not players: return "无人" return "、".join(players)
def calculate_suspicion_score(player_name: str, game_history: List[Dict]) -> float: """计算玩家可疑度分数""" score = 0.0
for event in game_history: if event.get("type") == "vote" and event.get("target") == player_name: score += 0.3 elif event.get("type") == "accusation" and event.get("target") == player_name: score += 0.2 elif event.get("type") == "defense" and event.get("player") == player_name: score -= 0.1
return min(max(score, 0.0), 1.0)
async def handle_interrupt(*args: Any, **kwargs: Any) -> Msg: """处理游戏中断""" return Msg( name="系统", content="游戏被中断", role="system" )
class ThreeKingdomsWerewolfGame: """三国狼人杀游戏主类"""
def __init__(self): self.players: Dict[str, ReActAgent] = {} self.roles: Dict[str, str] = {} self.moderator = GameModerator() self.alive_players: List[ReActAgent] = [] self.werewolves: List[ReActAgent] = [] self.villagers: List[ReActAgent] = [] self.seer: List[ReActAgent] = [] self.witch: List[ReActAgent] = [] self.hunter: List[ReActAgent] = []
self.witch_has_antidote = True self.witch_has_poison = True
async def create_player(self, role: str, character: str) -> ReActAgent: """创建具有三国背景的玩家""" name = get_chinese_name(character) self.roles[name] = role
agent = ReActAgent( name=name, sys_prompt=ChinesePrompts.get_role_prompt(role, character), model=OpenAIChatModel( model_name=os.getenv("LLM_MODEL_ID"), api_key=os.getenv("LLM_API_KEY"), client_args={"base_url": os.getenv("LLM_BASE_URL")}, ), formatter=OpenAIMultiAgentFormatter(), )
await agent.observe( await self.moderator.announce( f"【{name}】你在这场三国狼人杀中扮演{GameRoles.get_role_desc(role)}," f"你的角色是{character}。{GameRoles.get_role_ability(role)}" ) )
self.players[name] = agent return agent
async def setup_game(self, player_count: int = 6): """设置游戏""" print("🎮 开始设置三国狼人杀游戏...")
roles = GameRoles.get_standard_setup(player_count) characters = random.sample([ "刘备", "关羽", "张飞", "诸葛亮", "赵云", "曹操", "司马懿", "周瑜", "孙权" ], player_count)
for i, (role, character) in enumerate(zip(roles, characters)): agent = await self.create_player(role, character) self.alive_players.append(agent)
if role == "狼人": self.werewolves.append(agent) elif role == "预言家": self.seer.append(agent) elif role == "女巫": self.witch.append(agent) elif role == "猎人": self.hunter.append(agent) else: self.villagers.append(agent)
await self.moderator.announce( f"三国狼人杀游戏开始!参与者:{format_player_list(self.alive_players)}" )
print(f"✅ 游戏设置完成,共{len(self.alive_players)}名玩家")
async def werewolf_phase(self, round_num: int): """狼人阶段""" if not self.werewolves: return None
await self.moderator.announce(f"🐺 狼人请睁眼,选择今晚要击杀的目标...")
async with MsgHub( self.werewolves, enable_auto_broadcast=True, announcement=await self.moderator.announce( f"狼人们,请讨论今晚的击杀目标。存活玩家:{format_player_list(self.alive_players)}" ), ) as werewolves_hub: for _ in range(MAX_DISCUSSION_ROUND): for wolf in self.werewolves: await wolf(structured_model=DiscussionModelCN)
werewolves_hub.set_auto_broadcast(False) kill_votes = await fanout_pipeline( self.werewolves, msg=await self.moderator.announce("请选择击杀目标"), structured_model=WerewolfKillModelCN, enable_gather=False, )
votes = {} for i, vote_msg in enumerate(kill_votes): if vote_msg is not None and hasattr(vote_msg, 'metadata') and vote_msg.metadata is not None: votes[self.werewolves[i].name] = vote_msg.metadata.get("target") else: print(f"⚠️ {self.werewolves[i].name} 的击杀投票无效,随机选择目标") valid_targets = [p.name for p in self.alive_players if p.name not in [w.name for w in self.werewolves]] votes[self.werewolves[i].name] = random.choice(valid_targets) if valid_targets else None
killed_player, _ = majority_vote_cn(votes) return killed_player
async def seer_phase(self): """预言家阶段""" if not self.seer: return
seer_agent = self.seer[0] await self.moderator.announce("🔮 预言家请睁眼,选择要查验的玩家...")
check_result = await seer_agent( structured_model=get_seer_model_cn(self.alive_players) )
if check_result is None or not hasattr(check_result, 'metadata') or check_result.metadata is None: print(f"⚠️ 预言家查验失败,跳过此阶段") return
target_name = check_result.metadata.get("target") if not target_name: print(f"⚠️ 预言家未选择查验目标,跳过此阶段") return
target_role = self.roles.get(target_name, "村民")
result_msg = f"查验结果:{target_name}是{'狼人' if target_role == '狼人' else '好人'}" await seer_agent.observe(await self.moderator.announce(result_msg))
async def witch_phase(self, killed_player: str): """女巫阶段""" if not self.witch: return killed_player, None
witch_agent = self.witch[0] await self.moderator.announce("🧙♀️ 女巫请睁眼...")
death_info = f"今晚{killed_player}被狼人击杀" if killed_player else "今晚平安无事" await witch_agent.observe(await self.moderator.announce(death_info))
witch_action = await witch_agent(structured_model=WitchActionModelCN)
saved_player = None poisoned_player = None
if witch_action is None or not hasattr(witch_action, 'metadata') or witch_action.metadata is None: print(f"⚠️ 女巫行动失败,视为不使用技能") else: if witch_action.metadata.get("use_antidote") and self.witch_has_antidote: if killed_player: saved_player = killed_player self.witch_has_antidote = False await witch_agent.observe(await self.moderator.announce(f"你使用解药救了{killed_player}"))
if witch_action.metadata.get("use_poison") and self.witch_has_poison: poisoned_player = witch_action.metadata.get("target_name") if poisoned_player: self.witch_has_poison = False await witch_agent.observe(await self.moderator.announce(f"你使用毒药毒杀了{poisoned_player}"))
final_killed = killed_player if not saved_player else None
return final_killed, poisoned_player
async def hunter_phase(self, shot_by_hunter: str): """猎人阶段""" if not self.hunter: return None
hunter_agent = self.hunter[0] if hunter_agent.name == shot_by_hunter: await self.moderator.announce("🏹 猎人发动技能,可以带走一名玩家...")
hunter_action = await hunter_agent( structured_model=get_hunter_model_cn(self.alive_players) )
if hunter_action is None or not hasattr(hunter_action, 'metadata') or hunter_action.metadata is None: print(f"⚠️ 猎人技能使用失败,视为放弃开枪") return None
if hunter_action.metadata.get("shoot"): target = hunter_action.metadata.get("target") if target: await self.moderator.announce(f"猎人{hunter_agent.name}开枪带走了{target}") return target else: print(f"⚠️ 猎人选择开枪但未指定目标,视为放弃") return None
return None
def update_alive_players(self, dead_players: List[str]): """更新存活玩家列表""" for dead_name in dead_players: if dead_name: self.alive_players = [p for p in self.alive_players if p.name != dead_name] self.werewolves = [p for p in self.werewolves if p.name != dead_name] self.villagers = [p for p in self.villagers if p.name != dead_name] self.seer = [p for p in self.seer if p.name != dead_name] self.witch = [p for p in self.witch if p.name != dead_name] self.hunter = [p for p in self.hunter if p.name != dead_name]
async def day_phase(self, round_num: int): """白天阶段""" await self.moderator.day_announcement(round_num)
async with MsgHub( self.alive_players, enable_auto_broadcast=True, announcement=await self.moderator.announce( f"现在开始自由讨论。存活玩家:{format_player_list(self.alive_players)}" ), ) as all_hub: await sequential_pipeline(self.alive_players)
all_hub.set_auto_broadcast(False) vote_msgs = await fanout_pipeline( self.alive_players, await self.moderator.announce("请投票选择要淘汰的玩家"), structured_model=get_vote_model_cn(self.alive_players), enable_gather=False, )
votes = {} for i, vote_msg in enumerate(vote_msgs): if vote_msg is not None and hasattr(vote_msg, 'metadata') and vote_msg.metadata is not None: votes[self.alive_players[i].name] = vote_msg.metadata.get("vote") else: print(f"⚠️ {self.alive_players[i].name} 的投票无效,视为弃票") votes[self.alive_players[i].name] = None
voted_out, vote_count = majority_vote_cn(votes) await self.moderator.vote_result_announcement(voted_out, vote_count)
return voted_out
async def run_game(self): """运行游戏主循环""" try: await self.setup_game()
for round_num in range(1, MAX_GAME_ROUND + 1): print(f"\n🌙 === 第{round_num}轮游戏开始 ===")
await self.moderator.night_announcement(round_num)
killed_player = await self.werewolf_phase(round_num)
await self.seer_phase()
final_killed, poisoned_player = await self.witch_phase(killed_player)
night_deaths = [p for p in [final_killed, poisoned_player] if p] self.update_alive_players(night_deaths)
await self.moderator.death_announcement(night_deaths)
winner = check_winning_cn(self.alive_players, self.roles) if winner: await self.moderator.game_over_announcement(winner) return
voted_out = await self.day_phase(round_num)
hunter_shot = await self.hunter_phase(voted_out)
day_deaths = [p for p in [voted_out, hunter_shot] if p] self.update_alive_players(day_deaths)
winner = check_winning_cn(self.alive_players, self.roles) if winner: await self.moderator.game_over_announcement(winner) return
print(f"第{round_num}轮结束,存活玩家:{format_player_list(self.alive_players)}")
except Exception as e: print(f"❌ 游戏运行出错:{e}") import traceback traceback.print_exc()
async def main(): """主函数""" if "DASHSCOPE_API_KEY" not in os.environ: print("❌ 请设置环境变量 DASHSCOPE_API_KEY") return
print("🎮 欢迎来到三国狼人杀!")
game = ThreeKingdomsWerewolfGame() await game.run_game()
if __name__ == "__main__": asyncio.run(main())
|