├── .gitignore ├── audio ├── 刀民成功.wav ├── 刀神成功.wav ├── 天亮了.wav ├── 游戏开始.wav ├── 逐狼成功.wav ├── 天黑请闭眼.wav ├── 女巫请睁眼.wav ├── 女巫请闭眼.wav ├── 守卫请睁眼.wav ├── 守卫请闭眼.wav ├── 有人掉线了.wav ├── 狼人请睁眼.wav ├── 狼人请闭眼.wav ├── 预言家请睁眼.wav ├── 预言家请闭眼.wav ├── 禁言长老请睁眼.wav └── 禁言长老请闭眼.wav ├── config.json ├── config_prompts.json ├── werewolf_server.spec ├── audio.py ├── wechat.py ├── config_editor.py ├── README.md ├── client_control.py ├── charactor.py ├── werewolf_server.py └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | log 3 | 4 | __pycache__/ 5 | 6 | dist/ 7 | 8 | build/ 9 | -------------------------------------------------------------------------------- /audio/刀民成功.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LouYu2015/WerewolvesWechatBot/HEAD/audio/刀民成功.wav -------------------------------------------------------------------------------- /audio/刀神成功.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LouYu2015/WerewolvesWechatBot/HEAD/audio/刀神成功.wav -------------------------------------------------------------------------------- /audio/天亮了.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LouYu2015/WerewolvesWechatBot/HEAD/audio/天亮了.wav -------------------------------------------------------------------------------- /audio/游戏开始.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LouYu2015/WerewolvesWechatBot/HEAD/audio/游戏开始.wav -------------------------------------------------------------------------------- /audio/逐狼成功.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LouYu2015/WerewolvesWechatBot/HEAD/audio/逐狼成功.wav -------------------------------------------------------------------------------- /audio/天黑请闭眼.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LouYu2015/WerewolvesWechatBot/HEAD/audio/天黑请闭眼.wav -------------------------------------------------------------------------------- /audio/女巫请睁眼.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LouYu2015/WerewolvesWechatBot/HEAD/audio/女巫请睁眼.wav -------------------------------------------------------------------------------- /audio/女巫请闭眼.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LouYu2015/WerewolvesWechatBot/HEAD/audio/女巫请闭眼.wav -------------------------------------------------------------------------------- /audio/守卫请睁眼.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LouYu2015/WerewolvesWechatBot/HEAD/audio/守卫请睁眼.wav -------------------------------------------------------------------------------- /audio/守卫请闭眼.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LouYu2015/WerewolvesWechatBot/HEAD/audio/守卫请闭眼.wav -------------------------------------------------------------------------------- /audio/有人掉线了.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LouYu2015/WerewolvesWechatBot/HEAD/audio/有人掉线了.wav -------------------------------------------------------------------------------- /audio/狼人请睁眼.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LouYu2015/WerewolvesWechatBot/HEAD/audio/狼人请睁眼.wav -------------------------------------------------------------------------------- /audio/狼人请闭眼.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LouYu2015/WerewolvesWechatBot/HEAD/audio/狼人请闭眼.wav -------------------------------------------------------------------------------- /audio/预言家请睁眼.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LouYu2015/WerewolvesWechatBot/HEAD/audio/预言家请睁眼.wav -------------------------------------------------------------------------------- /audio/预言家请闭眼.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LouYu2015/WerewolvesWechatBot/HEAD/audio/预言家请闭眼.wav -------------------------------------------------------------------------------- /audio/禁言长老请睁眼.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LouYu2015/WerewolvesWechatBot/HEAD/audio/禁言长老请睁眼.wav -------------------------------------------------------------------------------- /audio/禁言长老请闭眼.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LouYu2015/WerewolvesWechatBot/HEAD/audio/禁言长老请闭眼.wav -------------------------------------------------------------------------------- /config.json: -------------------------------------------------------------------------------- 1 | { 2 | "gods": { 3 | "have_hunter": false, 4 | "have_idiot": false, 5 | "have_savior": true, 6 | "have_seer": true, 7 | "have_silencer": false, 8 | "have_witch": true 9 | }, 10 | "n_villager": 3, 11 | "rules": { 12 | "have_mayor": true, 13 | "savior_same_player_successivly": false, 14 | "werewolf_can_explode": true, 15 | "witch_save_itself_after_first_night": false, 16 | "witch_save_itself_at_first_night": true, 17 | "witch_two_posion_in_one_round": false 18 | }, 19 | "system": { 20 | "vote_waiting_time": 4 21 | }, 22 | "werewolves": { 23 | "have_werewolf_leader": true, 24 | "n_werewolf": 2 25 | } 26 | } -------------------------------------------------------------------------------- /config_prompts.json: -------------------------------------------------------------------------------- 1 | { 2 | "n_villager": "村民数量", 3 | "gods": 4 | { 5 | "menu_title": "神阵营配置", 6 | "have_witch": "存在女巫", 7 | "have_seer": "存在预言家", 8 | "have_savior": "存在守卫", 9 | "have_hunter": "存在猎人", 10 | "have_idiot": "存在白痴", 11 | "have_silencer":"存在禁言长老" 12 | }, 13 | "werewolves": 14 | { 15 | "menu_title": "狼阵营配置", 16 | "have_werewolf_leader": "存在狼王", 17 | "n_werewolf": "狼人数量" 18 | }, 19 | "rules": 20 | { 21 | "menu_title": "规则设置", 22 | "have_mayor": "进行警长竞选", 23 | "witch_two_posion_in_one_round": "女巫可以双开", 24 | "witch_save_itself_at_first_night": "女巫第一晚可以自救", 25 | "witch_save_itself_after_first_night": "女巫第二晚起可以自救", 26 | "savior_same_player_successivly": "守卫可以连续守人", 27 | "werewolf_can_explode": "狼人可以爆炸" 28 | }, 29 | "system": 30 | { 31 | "menu_title": "系统设置", 32 | "vote_waiting_time": "投票等待时间(秒)" 33 | } 34 | } -------------------------------------------------------------------------------- /werewolf_server.spec: -------------------------------------------------------------------------------- 1 | # -*- mode: python -*- 2 | 3 | block_cipher = None 4 | 5 | 6 | a = Analysis(['werewolf_server.py'], 7 | pathex=['werewolf'], 8 | binaries=[], 9 | datas=[('audio','audio'),('*.json','.')], 10 | hiddenimports=[], 11 | hookspath=[], 12 | runtime_hooks=[], 13 | excludes=[], 14 | win_no_prefer_redirects=False, 15 | win_private_assemblies=False, 16 | cipher=block_cipher) 17 | pyz = PYZ(a.pure, a.zipped_data, 18 | cipher=block_cipher) 19 | exe = EXE(pyz, 20 | a.scripts, 21 | exclude_binaries=True, 22 | name='werewolf_server', 23 | debug=False, 24 | strip=False, 25 | upx=True, 26 | console=True ) 27 | coll = COLLECT(exe, 28 | a.binaries, 29 | a.zipfiles, 30 | a.datas, 31 | strip=False, 32 | upx=True, 33 | name='werewolf_server') 34 | -------------------------------------------------------------------------------- /audio.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Copied from http://stackoverflow.com/a/17657304/4398908 3 | 4 | Play a wave sound file. 5 | ''' 6 | import pyaudio 7 | import wave 8 | import os 9 | 10 | audioPath = None # Path to audio files 11 | 12 | def play_sound(name): 13 | #define stream chunk 14 | chunk = 1024 15 | 16 | #open a wav format music 17 | f = wave.open(os.path.join(audioPath, name + '.wav'),"rb") 18 | #instantiate PyAudio 19 | p = pyaudio.PyAudio() 20 | #open stream 21 | stream = p.open(format = p.get_format_from_width(f.getsampwidth()), 22 | channels = f.getnchannels(), 23 | rate = f.getframerate(), 24 | output = True) 25 | #read data 26 | data = f.readframes(chunk) 27 | 28 | #play stream 29 | while data: 30 | stream.write(data) 31 | data = f.readframes(chunk) 32 | 33 | #stop stream 34 | stream.stop_stream() 35 | stream.close() 36 | 37 | #close PyAudio 38 | p.terminate() 39 | -------------------------------------------------------------------------------- /wechat.py: -------------------------------------------------------------------------------- 1 | import threading 2 | import queue 3 | import time 4 | 5 | import itchat 6 | 7 | import client_control 8 | 9 | class WechatController(client_control.ClientController): 10 | def __init__(self, game_controller): 11 | super().__init__(game_controller) 12 | 13 | self.username_to_user = {} # Map Wechat user name to WechatUser object 14 | self.send_msg_queue = queue.Queue() # Avoid sending messages too fast by buffering 15 | 16 | # Start listening Wechat messages 17 | itchat.auto_login() 18 | threading.Thread(target = itchat.run).start() 19 | 20 | # Send messages in another thread 21 | threading.Thread(target = self.send_messages_in_queue).start() 22 | 23 | # Accept new messages from players 24 | @itchat.msg_register(itchat.content.TEXT) 25 | def listen_wechat_message(message_info): 26 | username = message_info['User']['UserName'] # User name of the Wechat user 27 | text = message_info['Text'] # Content of the message 28 | self.got_message(username, text) 29 | 30 | def send_messages_in_queue(self): 31 | while(True): 32 | (username, message) = self.send_msg_queue.get() 33 | itchat.send(message, toUserName = username) 34 | 35 | time.sleep(0.5) 36 | 37 | def register_user(self, username, user): 38 | self.username_to_user[username] = user 39 | 40 | def user_from_username(self, username): 41 | try: 42 | return self.username_to_user[username] 43 | except KeyError: 44 | raise client_control.UserNotRegistered() 45 | 46 | def clear_screen(self, username): 47 | message = '\n'*25 + '清屏' 48 | self.send_message(username, message) 49 | 50 | def send_message(self, username, message): 51 | self.send_msg_queue.put((username, message)) 52 | -------------------------------------------------------------------------------- /config_editor.py: -------------------------------------------------------------------------------- 1 | import json 2 | import wechat 3 | 4 | class Config: 5 | def __init__(self, config_path, prompts_path): 6 | ''' 7 | config_path: file path of configuration file 8 | prompts_path: file path of prompts 9 | ''' 10 | self.config_path = config_path 11 | 12 | # Load files 13 | self.config = json.load(open(config_path, encoding = 'utf-8')) 14 | self.prompts = json.load(open(prompts_path, encoding = 'utf-8')) 15 | 16 | def save(self): 17 | ''' 18 | Save configuration to file 19 | ''' 20 | json.dump(self.config, open(self.config_path, 'w'), indent = 4, sort_keys = True) 21 | 22 | def edit(self, user): 23 | ''' 24 | Let the user to edit configuration. 25 | 26 | user: a 'WechatUser' object 27 | ''' 28 | def visualize_menu(menu, prompts, user): 29 | message = [] 30 | id_to_key = {} # Map from menu item id to key in the dictionary 31 | 32 | # Menu title 33 | try: 34 | message.append('----- %s -----' % prompts['menu_title']) 35 | except KeyError: 36 | pass 37 | 38 | # Prompt 39 | message.append('请输入你要修改的配置的编号:') 40 | message.append('0.(返回)') 41 | 42 | # Add each menu item to the message 43 | for (i, (key, value)) in enumerate(sorted(menu.items())): 44 | # Get prompt for this item 45 | if isinstance(value, dict): 46 | assert 'menu_title' in prompts[key].keys() 47 | prompt = prompts[key]['menu_title'] 48 | else: 49 | prompt = prompts[key] 50 | 51 | # Add item value to the prompt 52 | if isinstance(value, bool): 53 | if value == True: 54 | content = '%s: 是' % prompt 55 | else: 56 | content = '%s: 否' % prompt 57 | elif isinstance(value, int): 58 | content = '%s: %d' % (prompt, value) 59 | elif isinstance(value, dict): 60 | content = prompt 61 | else: 62 | raise Exception() 63 | 64 | # Update result 65 | message.append('%d.%s' % (i+1, content)) 66 | id_to_key[i+1] = key 67 | 68 | user.send_message('\n'.join(message)) 69 | 70 | return id_to_key 71 | 72 | def edit_menu(menu, prompts, user): 73 | while True: 74 | id_to_key = visualize_menu(menu, prompts, user) 75 | 76 | selection = user.get_int('', 0, len(menu.keys()) + 1) 77 | 78 | if selection == 0: 79 | return 80 | 81 | key = id_to_key[selection] 82 | value = menu[key] 83 | prompt = prompts[key] 84 | 85 | if isinstance(value, bool): 86 | menu[key] = not menu[key] 87 | elif isinstance(value, int): 88 | menu[key] = user.get_int('请输入%s' % prompt, 0) 89 | elif isinstance(value, dict): 90 | edit_menu(value, prompts[key], user) 91 | else: 92 | raise Exception() 93 | 94 | edit_menu(self.config, self.prompts, user) 95 | self.save() 96 | user.send_message('已保存配置') 97 | 98 | def __call__(self, path): 99 | cursor = self.config 100 | for key in path.split('/'): 101 | cursor = cursor[key] 102 | return cursor 103 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # 狼人杀法官.BOT 2 | 3 | 这个程序是基于 itchat,用 Python3 写成的狼人杀面杀助手,用于在微信上作为机器人法官。 4 | 5 | 目前此程序在实战中使用了4次,但是不是系统性地测试,可能依然不太稳定。 6 | 7 | ## 系统要求 8 | 9 | 理论上只要成功安装 pyaudio 和 itchat 即可运行,而这两个依赖项均同时支持 Linux, Mac 和 Windows。不过,我只在 Linux 和 Windows 上测试了程序。 10 | 11 | ## 免安装运行 12 | 13 | 我在 Windows 7 和 Ubuntu 16.10 上用 PyInstaller 打包了程序,所以目前 64 位的 Windows 和 Linux 系统可以免安装运行啦。只需在 Release 界面下载对应的压缩包,然后运行 `werewolf_server.exe`(Windows)或者 `werewolf_server`(Linux)即可。 14 | 15 | 有时 PyInstaller 在打包时会漏掉一些依赖项,如果在免安装运行的时候,程序刚启动就出现错误,则很可能是打包的问题,可以尝试直接运行源代码;如果程序在运行过程中才崩溃,则很可能是代码本身的 BUG。 16 | 17 | 对于没有完成打包的系统(比如 32 位系统或者 Mac),也可以通过直接运行源代码的方式执行程序。 18 | 19 | ## 直接运行源代码 20 | 21 | 若要直接运行源代码,请先安装 Python3.5。可以参考[这篇文章](http://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/0014316090478912dab2a3a9e8f4ed49d28854b292f85bb000) 。 22 | 23 | 程序的源代码可以在 Release 界面的 Source Code 链接或者 Clone or Download 的 Download ZIP 链接下载。 24 | 25 | 程序需要以下依赖项: 26 | 27 | * pyaudio 28 | * itchat 29 | 30 | 可以使用 pip 安装依赖项。 31 | 32 | ### Mac/Linux 用户 33 | 34 | 打开“终端”应用,执行以下命令: 35 | 36 | sudo pip3 install pyaudio 37 | sudo pip3 install itchat 38 | 39 | (这些指令需要用系统的登录密码来授权) 40 | 41 | 之后就可以用 python3 运行程序了: 42 | 43 | cd <储存代码的文件夹路径> 44 | python3 werewolf_sever.py 45 | 46 | ### Windows 用户 47 | 48 | 打开命令行(按 `Win + R`,输入 `cmd` 然后确定),执行以下命令: 49 | 50 | py -3 -m pip install pyaudio 51 | py -3 -m pip install itchat 52 | 53 | 之后就可以用 python 运行程序了: 54 | 55 | cd <储存代码的文件夹路径> 56 | py -3 werewolf_server.py 57 | 58 | ## 使用方法 59 | 60 | 运行程序后,itchat 会弹出微信登录二维码,用微信扫描后在手机上确认登录即可成为法官。 61 | 62 | **提示:** 63 | 64 | 1. 如果想一个人试用这个程序(用文件传输助手),可以让`werewolf_server.py` 中的 `GameController.is_game_ended` 方法直接 `return` 以阻止游戏结束(没有返回值)。否则,由于只有一位玩家,程序会在第一晚认为刀边成功。 65 | 2. 如果登录为法官的用户需要使用自己的帐号参加游戏(用文件传输助手),可以在游戏时把微信设置成勿扰模式,以免不小心从消息提示里看到别人的身份。 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 | * audio(文件夹):包含语音提示的声音文件 107 | * werewolf_server.py:主程序,包含游戏控制器的代码,控制游戏的流程 108 | * charactor.py:包含所有游戏角色的代码,控制角色之间的逻辑 109 | * wechat.py:实现 `ClientController` 与 itchat 的通信 110 | * client_controller.py:包含所有客户端的通用代码,实现处理输入和命令的基本工具 111 | * audio.py:包含播放声音的代码 112 | * config_editor.py:包含处理配置文件的代码,实现配置文件的读取、交互式编辑和保存 113 | * config.json:游戏的配置文件 114 | * config_prompts.json:储存配置文件中每个值对应的菜单提示 115 | * werewolf_server.spec:PyInstaller 的打包配置文件 116 | 117 | ## 技术问题笔记 118 | 119 | 此处用于记录开发过程中遇到过的问题: 120 | 121 | 1. 目前 audio.py 只能读取 signed 16-bit PCM 格式的 WAV 文件,读取 32-bit float PCM 格式的 WAV 会崩溃。 122 | 2. 如果程序发送消息的频率过快,则微信帐号会被屏蔽一段时间。之前出现了单人测试没有问题但是多人测试的时候微信帐号被屏蔽的情况,所以我主动限制了发送消息的间隔。 -------------------------------------------------------------------------------- /client_control.py: -------------------------------------------------------------------------------- 1 | import queue 2 | import threading 3 | 4 | class UserNotRegistered(Exception): 5 | """ 6 | Raised when the Client object of an unregistered user is requested. 7 | """ 8 | pass 9 | 10 | class Client: 11 | def __init__(self, controller, username): 12 | ''' 13 | controller: Client controller 14 | username: Username 15 | ''' 16 | self.controller = controller 17 | self.username = username 18 | self.remarkname = None 19 | 20 | self.identity = None # Link to the Charactor object of the user 21 | self.msg_queue = queue.Queue() # Queue for received messages from user 22 | self.ready = False # Is user ready to begin the game 23 | 24 | def clear_queue(self): 25 | ''' 26 | clear message queue. 27 | ''' 28 | try: 29 | while True: 30 | self.msg_queue.get(block = False) 31 | except queue.Empty: 32 | return 33 | 34 | def got_message(self, message): 35 | ''' 36 | Put message into message queue. 37 | Will be called by controller when a new message arrives. 38 | ''' 39 | self.msg_queue.put(message) 40 | 41 | def send_message(self, message): 42 | ''' 43 | Send message to user. 44 | ''' 45 | if message: 46 | self.controller.send_message(self.username, message) 47 | else: 48 | self.controller.clear_screen(self.username) 49 | 50 | def receive_message(self): 51 | ''' 52 | Return the next message from user. 53 | ''' 54 | return self.msg_queue.get() # Will block when there's no new message 55 | 56 | def get_input(self, prompt): 57 | ''' 58 | Send prompt and return the reply. 59 | ''' 60 | if prompt: 61 | self.send_message(prompt) 62 | 63 | self.clear_queue() 64 | 65 | return self.receive_message() 66 | 67 | def get_int(self, prompt, min_value = -float('inf'), max_value = float('inf')): 68 | ''' 69 | Ask the user to enter an integer in range(min_value, max_value). 70 | Return the integer. 71 | ''' 72 | while True: 73 | try: 74 | result = int(self.get_input(prompt)) 75 | except ValueError: 76 | self.send_message('这不是数字') 77 | continue 78 | 79 | if not(min_value <= result < max_value): 80 | self.send_message('超出范围') 81 | continue 82 | 83 | return result 84 | 85 | def decide(self, message = ''): 86 | ''' 87 | Ask the player to select yes/no. 88 | Return a boolean. 89 | ''' 90 | if message: 91 | message += '(y/n)' 92 | 93 | while True: 94 | answer = self.get_input(message) 95 | 96 | if answer == 'Y' or answer == 'y': 97 | return True 98 | elif answer == 'N' or answer == 'n': 99 | return False 100 | else: 101 | self.send_message('请输入Y/y(yes)或者N/n(no)') 102 | 103 | class ClientController: 104 | def __init__(self, game_controller): 105 | """ 106 | game_controller: link to the game controller. 107 | """ 108 | self.game_controller = game_controller 109 | 110 | def new_user(self, username): 111 | """ 112 | Initiate a new user. 113 | 114 | username: username of the user 115 | """ 116 | return Client(self, username) 117 | 118 | def register_user(self, username, user): 119 | """ 120 | Link the user object to the username. 121 | """ 122 | pass 123 | 124 | def user_from_username(self, username): 125 | """ 126 | Return the user object that has the username. 127 | """ 128 | return None 129 | 130 | def clear_screen(self, username): 131 | """ 132 | Clear the screen of the user. 133 | """ 134 | pass 135 | 136 | def send_message(self, username, message): 137 | """ 138 | Send a message to the user. 139 | """ 140 | pass 141 | 142 | def got_message(self, username, message): 143 | """ 144 | Process the message from user. 145 | Will be called by message listener upon message arrival. 146 | """ 147 | if '进入游戏' in message: 148 | threading.Thread(target = self.enter_game, args = (username,)).start() 149 | return 150 | 151 | try: 152 | user = self.user_from_username(username) 153 | except UserNotRegistered: 154 | print('收到未注册用户发送的消息') 155 | return 156 | 157 | is_command = self.process_command(user, message) 158 | 159 | if not is_command: 160 | user.got_message(message) 161 | 162 | def process_command(self, user, message): 163 | """ 164 | If the message is a command, execute the command. 165 | 166 | Return whether the message is a command. 167 | """ 168 | # Edit configuration 169 | if '编辑配置' in message: 170 | command = self.edit_config 171 | 172 | # See identities 173 | elif '查看配置' in message: 174 | command = self.get_identity_list 175 | 176 | # Start game 177 | elif '开始游戏' in message: 178 | command = self.start_game 179 | 180 | # Get game history 181 | elif '接管上帝' in message: 182 | command = self.get_game_history 183 | 184 | else: 185 | command = None 186 | 187 | if command: 188 | threading.Thread(target = command, args = (user,)).start() 189 | return True 190 | else: 191 | return False 192 | 193 | def enter_game(self, username): 194 | # Check whether user have registered 195 | try: 196 | user = self.user_from_username(username) 197 | except UserNotRegistered: 198 | pass 199 | else: 200 | user.send_message('您已经注册过了') 201 | return 202 | 203 | user = self.new_user(username) 204 | self.register_user(username, user) 205 | 206 | players = self.game_controller.players 207 | 208 | # Ask for remarkname 209 | remarkname = user.get_input('请输入你想使用的备注名') 210 | 211 | user.remarkname = remarkname 212 | print('%s 进入游戏' % remarkname) 213 | 214 | # Assign an identity 215 | player = self.game_controller.pop_from_identity_pool() 216 | user.identity = player 217 | 218 | # Assign properties 219 | player.user = user 220 | player.name = remarkname 221 | player.get_id() 222 | 223 | players[player.player_id] = player 224 | 225 | # Tell the identity 226 | player.welcome() 227 | 228 | def edit_config(self, user): 229 | if self.game_controller.game_started: 230 | user.send_message('游戏过程中不能编辑配置') 231 | return 232 | 233 | user.ready = False 234 | 235 | self.game_controller.config.edit(user) 236 | 237 | self.game_controller.status('配置已更新', broadcast = True) 238 | self.game_controller.reassign_identities() 239 | user.ready = True 240 | 241 | def get_identity_list(self, user): 242 | user.identity.welcome() 243 | 244 | def start_game(self, user): 245 | self.game_controller.event_start_game.set() 246 | 247 | def get_game_history(self, user): 248 | if self.game_controller.game_started: 249 | user.send_message(self.game_controller.get_history()) 250 | self.game_controller.broadcast('%s 接管上帝' % user.remarkname) 251 | -------------------------------------------------------------------------------- /charactor.py: -------------------------------------------------------------------------------- 1 | from audio import play_sound 2 | import threading 3 | import time 4 | 5 | class Character: 6 | can_be_voted_out = True 7 | 8 | def __init__(self, controller): 9 | ''' 10 | controller: game controller 11 | ''' 12 | self.player_id = None # ID of the player 13 | self.name = None # Player's name 14 | self.user = None # WechatUser object 15 | 16 | self.died = False # Is player died 17 | self.protected = False # Is player protected by Savior 18 | 19 | self.is_mayor = False # Is the player elected as a mayor 20 | 21 | self.controller = controller # Game controller 22 | self.ready = False # Is player ready to start game 23 | 24 | def get_id(self): 25 | while True: 26 | player_id = self.user.get_int('请输入你的编号', 1, len(self.controller.players)) 27 | 28 | if self.controller.players[player_id]: 29 | self.user.send_message('该编号已被占用') 30 | continue 31 | 32 | break 33 | 34 | self.player_id = player_id 35 | 36 | def welcome(self): 37 | ''' 38 | Tell the player his/her identity. 39 | ''' 40 | def welcome(): 41 | self.message(self.controller.str_identity_list()) 42 | self.message('你是 %s' % self.description()) 43 | self.get_input('记住身份后,请回复任意内容继续') 44 | self.message('') 45 | 46 | self.ready = True 47 | self.message('%s 已上线' % self.desc()) 48 | 49 | threading.Thread(target = welcome).start() 50 | 51 | def message(self, message = ''): 52 | ''' 53 | Send message to player. 54 | ''' 55 | self.user.send_message(message) 56 | 57 | def get_input(self, message = ''): 58 | ''' 59 | Get input from player with message as prompt. 60 | ''' 61 | return self.user.get_input(message).strip() 62 | 63 | def decide(self, message = ''): 64 | ''' 65 | Ask the player to select yes/no. 66 | ''' 67 | return self.user.decide(message) 68 | 69 | def select_player(self, message = '', min_id = 1, candidates = None): 70 | ''' 71 | Let the player select a player. 72 | ''' 73 | # Default candidates 74 | if candidates == None: 75 | candidates = [player for player in self.controller.players[1:] \ 76 | if not player.died or player in self.controller.killed_players] 77 | 78 | while True: 79 | answer = self.user.get_int(message, min_id, len(self.controller.players)) 80 | 81 | if answer != 0 and self.controller.players[answer] not in candidates: 82 | self.message('不是候选人') 83 | continue 84 | 85 | # Return the result 86 | return answer 87 | 88 | def kill(self): 89 | ''' 90 | Try to kill the player. Only werewolf should use this method. 91 | ''' 92 | if not self.protected: 93 | self.die(True) 94 | else: 95 | self.controller.killed_players.append(self) 96 | 97 | def die(self, killed_by_wolf = False): 98 | ''' 99 | Called when the player will be died. Ignore Savior's protection. 100 | 101 | killed_by_wolf: whether killed by a werewolf. 102 | ''' 103 | self.died = True 104 | self.controller.killed_players.append(self) 105 | 106 | if not killed_by_wolf: # If killed by wolf, game won't end until Witch makes a choice. 107 | self.controller.is_game_ended() 108 | 109 | def wake_up(self): 110 | ''' 111 | Called at the start of each day. 112 | ''' 113 | pass 114 | 115 | def after_dying(self): 116 | ''' 117 | Called at the start of daytime if the player died at night. 118 | ''' 119 | if self.is_mayor: 120 | # Resign 121 | self.is_mayor = False 122 | self.controller.have_mayor = False 123 | 124 | # Select next Mayor 125 | self.controller.broadcast('等待移交警徽') 126 | next_mayor_id = self.select_player('输入你要移交警徽的玩家,撕警徽用 0 表示', min_id = 0) 127 | 128 | # Assign next mayor and broadcast the result 129 | if next_mayor_id == 0: 130 | self.controller.status('警长 %s 选择撕警徽' % self.desc(), broadcast = True) 131 | else: 132 | next_mayor = self.controller.players[next_mayor_id] 133 | next_mayor.is_mayor = True 134 | self.controller.have_mayor = True 135 | 136 | self.controller.status('警长 %s 选择把警徽交给 %s' % (self.desc(), next_mayor.desc()), broadcast = True) 137 | 138 | def desc(self): 139 | ''' 140 | Short description of the player. 141 | ''' 142 | return '%d号%s' % (self.player_id, self.name) 143 | 144 | def description(self): 145 | ''' 146 | Description of the player. 147 | ''' 148 | return '%d号%s%s' % (self.player_id, self.__class__.identity, self.name) 149 | 150 | def open_eyes(self): 151 | ''' 152 | Ask the player to open eyes. 153 | ''' 154 | play_sound('%s请睁眼' % self.__class__.identity) 155 | 156 | def close_eyes(self): 157 | ''' 158 | Ask the player to close eyes. 159 | ''' 160 | play_sound('%s请闭眼' % self.__class__.identity) 161 | 162 | # Clear screen 163 | self.message() 164 | 165 | class Witch(Character): 166 | identity = '女巫' 167 | good = True 168 | 169 | def __init__(self, controller): 170 | super().__init__(controller) 171 | self.used_poison = False 172 | self.used_medicine = False 173 | 174 | def move(self): 175 | used_medicine_this_round = self.decide_use_medicine() 176 | 177 | self.controller.is_game_ended() 178 | 179 | if used_medicine_this_round and not self.controller.config('rules/witch_two_posion_in_one_round'): 180 | self.message('不能双开') 181 | else: 182 | self.decide_use_poison() 183 | 184 | def decide_use_medicine(self): 185 | # Check whether medicine is used 186 | if self.used_medicine: 187 | self.message('你用过解药了') 188 | self.controller.wait_random_time() # Won't let the player close eyes immediately 189 | return False 190 | 191 | # Find the died player 192 | try: 193 | died_player = self.controller.killed_players[-1] 194 | except IndexError: 195 | self.message('刚才是空刀') 196 | self.controller.wait_random_time() 197 | return False 198 | 199 | # Tell the Witch 200 | self.message('刚才 %s 被杀了' % died_player.desc()) 201 | 202 | # Witch can't save himself/herself after fist round 203 | if died_player is self: 204 | if self.controller.nRound == 1 and not self.controller.config('rules/witch_save_itself_at_first_night'): 205 | self.message('第一晚不能自救') 206 | return False 207 | if self.controller.nRound >= 2 and not self.controller.config('rules/witch_save_itself_after_first_night'): 208 | self.message('第二回合起你不能自救') 209 | return False 210 | 211 | # Ask whether the Witch want's to use medicine 212 | if not self.decide('是否使用解药'): 213 | self.controller.status('%s 没有救 %s' % (self.description(), died_player.description())) 214 | return False 215 | 216 | else: 217 | self.controller.status('%s 救了 %s' % (self.description(), died_player.description())) 218 | died_player.died = False 219 | 220 | # If Witch saves the protected player, the player will die 221 | if died_player.protected: 222 | self.controller.status('同守同救!') 223 | died_player.died = True 224 | 225 | self.used_medicine = True 226 | return True 227 | 228 | def decide_use_poison(self): 229 | # Check whether poison is used 230 | if self.used_poison: 231 | self.message('你用过毒药了') 232 | self.controller.wait_random_time() # Won't let the player close eyes immediately 233 | return False 234 | 235 | # Ask whether the Witch want's to use poison 236 | if not self.decide('是否使用毒药'): 237 | self.controller.status('%s 没有使用毒药' % self.description()) 238 | return False 239 | 240 | # Ask whoever the Witch wants to kill 241 | target_id = self.select_player('输入要毒死的玩家,0表示取消', min_id = 0) 242 | 243 | if target_id != 0: 244 | target = self.controller.players[target_id] 245 | 246 | target.die() # Can't be saved by Savior 247 | target.can_use_gun = False 248 | 249 | self.controller.status('%s 毒死了 %s' % (self.description(), target.description())) 250 | self.used_poison = True 251 | return True 252 | 253 | class Savior(Character): 254 | identity = '守卫' 255 | good = True 256 | 257 | def __init__(self, controller): 258 | super().__init__(controller) 259 | self.last_protected = None # The player that was protected on last round 260 | 261 | def move(self): 262 | # Choose the target 263 | while True: 264 | target_id = self.select_player('输入要守护的人,0表示空守', min_id = 0) 265 | target = self.controller.players[target_id] 266 | 267 | if target.player_id != 0 and target is self.last_protected \ 268 | and not self.controller.config('rules/savior_same_player_successivly'): 269 | self.message('连续的回合里不能守护同一个人') 270 | continue 271 | else: 272 | break 273 | 274 | # Protect the target 275 | if self.last_protected: 276 | self.last_protected.protected = False 277 | 278 | target.protected = True 279 | self.controller.status('%s 守护了 %s' % (self.description(), target.description())) 280 | 281 | self.last_protected = target 282 | 283 | 284 | class Seer(Character): 285 | identity = '预言家' 286 | good = True 287 | 288 | def move(self): 289 | # Choose the target 290 | target_id = self.select_player('选择你要预言的人') 291 | target = self.controller.players[target_id] 292 | 293 | # Tell the result 294 | if target.__class__.good: 295 | self.message('%s 是好人' % target.desc()) 296 | self.controller.status('%s 发现 %s 是金水' % (self.description(), target.description())) 297 | else: 298 | self.message('%s 是坏人' % target.desc()) 299 | self.controller.status('%s 发现 %s 是查杀' % (self.description(), target.description())) 300 | 301 | class Hunter(Character): 302 | identity = '猎人' 303 | good = True 304 | 305 | def __init__(self, controller): 306 | super().__init__(controller) 307 | self.can_use_gun = True 308 | 309 | def after_dying(self): 310 | super().after_dying() 311 | 312 | # Can't use gun if killed by Witch 313 | if not self.can_use_gun: 314 | self.message('你是被女巫毒死的,不能放枪') 315 | return 316 | 317 | # Choose target 318 | target_id = self.select_player('输入你要枪杀的玩家编号,0表示黑枪', min_id = 0) 319 | target = self.controller.players[target_id] 320 | 321 | if target_id == 0: 322 | self.controller.status('%s 黑枪' % self.description()) 323 | return 324 | 325 | # Broadcast the result 326 | self.controller.broadcast('%s 枪杀了 %s' % (self.description(), target.desc())) 327 | self.controller.status('%s 枪杀了 %s' % (self.description(), target.description())) 328 | target.die() 329 | 330 | class Idiot(Character): 331 | identity = '白痴' 332 | good = True 333 | can_be_voted_out = False 334 | 335 | class Silencer(Character): 336 | identity = '禁言长老' 337 | good = True 338 | 339 | def __init__(self, controller): 340 | super().__init__(controller) 341 | self.silenced = None 342 | 343 | def move(self): 344 | while True: 345 | target_id = self.select_player('选择你要禁言的人', min_id = 0) 346 | 347 | if target_id == 0: 348 | self.silenced = None 349 | self.controller.status('禁言长老选择不禁言') 350 | return 351 | 352 | if self.silenced and target_id == self.silenced.player_id: 353 | self.message('你不能连续禁言同一个人') 354 | continue 355 | else: 356 | break 357 | 358 | self.silenced = self.controller.players[target_id] 359 | 360 | self.controller.status('%s 被禁言' % self.silenced.description()) 361 | 362 | def wake_up(self): 363 | if self.silenced: 364 | self.controller.broadcast('%s 被禁言' % self.silenced.desc()) 365 | 366 | class Werewolf(Character): 367 | identity = '狼人' 368 | good = False 369 | 370 | def move(self): 371 | self.controller.broadcast_to_wolves('由 %s 代表狼人进行操作' % self.description()) 372 | 373 | # Choose target 374 | target_id = self.select_player('输入你要杀的玩家,0表示空刀', min_id = 0) 375 | target = self.controller.players[target_id] 376 | 377 | if target_id == 0: 378 | self.controller.broadcast_to_wolves('狼人选择空刀') 379 | self.controller.status('狼人空刀') 380 | return 381 | 382 | # Kill 383 | target.kill() 384 | 385 | # Send result 386 | self.controller.broadcast_to_wolves('狼人选择刀 %s' % target.desc()) 387 | self.controller.status('狼人选择刀 %s' % target.description()) 388 | time.sleep(3) 389 | self.controller.broadcast_to_wolves('') 390 | 391 | def after_exploded(self): 392 | self.message('你不能带人') 393 | 394 | class WerewolfLeader(Werewolf): 395 | identity = '狼王' 396 | good = False 397 | 398 | def after_exploded(self): 399 | if self.decide('是否要带人'): 400 | target_id = self.select_player('输入你要带走的人') 401 | target = self.controller.players[target_id] 402 | 403 | target.die() 404 | 405 | self.controller.broadcast('%s 带走了 %s' % (self.description(), target.desc())) 406 | self.controller.status('%s 带走了 %s' % (self.description(), target.description())) 407 | 408 | def open_eyes(self): 409 | play_sound('狼人请睁眼') 410 | 411 | def close_eyes(self): 412 | play_sound('狼人请闭眼') 413 | self.message('') 414 | 415 | class Villager(Character): 416 | identity = '村民' 417 | good = True 418 | -------------------------------------------------------------------------------- /werewolf_server.py: -------------------------------------------------------------------------------- 1 | ''' 2 | A Wechat bot for the Werewolf game, running on Python 3. 3 | 4 | Contributor(s): Yu Lou(louyu27@gmail.com) 5 | ''' 6 | 7 | import socket 8 | import time 9 | import random 10 | import struct 11 | import threading 12 | import os 13 | import sys 14 | 15 | import audio 16 | from audio import play_sound 17 | from charactor import * 18 | import wechat 19 | import config_editor 20 | 21 | def get_path(path): 22 | """ 23 | Get absolute path from relative path. 24 | """ 25 | try: 26 | base_path = sys._MEIPASS # If packed by PyInstaller 27 | except AttributeError: 28 | base_path = os.path.abspath(".") # If executed directly 29 | 30 | return os.path.join(base_path, path) 31 | 32 | audio.audioPath = get_path('audio') 33 | 34 | def main(): 35 | controller = GameController() 36 | wechat.game_controller = controller 37 | 38 | controller.get_ready() 39 | play_sound('游戏开始') 40 | controller.main_loop() 41 | 42 | class WerewolfExploded(Exception): 43 | ''' 44 | Raised when a werewolf explodes. 45 | ''' 46 | def __init__(self, player): 47 | ''' 48 | player: the werewolf that explodes 49 | ''' 50 | self.player = player 51 | 52 | class GameController: 53 | def __init__(self): 54 | # Game related variables 55 | self.have_mayor = False # Does mayor currently exist 56 | self.identity_list = [] # List of possible identities 57 | 58 | # Other variables 59 | self.history = [] # History of status messages 60 | self.game_started = False # Is game started? 61 | self.event_start_game = threading.Event() 62 | 63 | # Load configuration file 64 | config_path = get_path('config.json') 65 | prompt_path = get_path('config_prompts.json') 66 | self.config = config_editor.Config(config_path, prompt_path) # Configurations 67 | 68 | self.initialize_identity_pool() 69 | 70 | # Start wechat controller 71 | wechat.WechatController(game_controller = self) 72 | 73 | # Manage identities 74 | def initialize_identity_pool(self): 75 | ''' 76 | Initialize 'identity_list' and 'identity_pool' from \ 77 | the configuration in 'self.config'. 78 | ''' 79 | self.identity_list = [] 80 | path_to_class = [ # Map configuration path to class name 81 | ('gods/have_witch', Witch), 82 | ('gods/have_seer', Seer), 83 | ('gods/have_savior', Savior), 84 | ('gods/have_hunter', Hunter), 85 | ('gods/have_idiot', Idiot), 86 | ('gods/have_silencer', Silencer), 87 | ('n_villager', Villager), 88 | ('werewolves/have_werewolf_leader', WerewolfLeader), 89 | ('werewolves/n_werewolf', Werewolf) 90 | ] 91 | 92 | for (path, identity) in path_to_class: 93 | value = self.config(path) # Number of corresponding identity 94 | 95 | # Add charactors 96 | if isinstance(value, bool): 97 | if value == True: 98 | self.identity_list.append(identity(controller = self)) 99 | else: 100 | for i in range(value): 101 | self.identity_list.append(identity(controller = self)) 102 | 103 | self.identity_pool = self.identity_list.copy() 104 | 105 | def reassign_identities(self): 106 | ''' 107 | Reassign identities for players. 108 | ''' 109 | self.initialize_identity_pool() 110 | 111 | old_player_list = self.players 112 | self.players = [Villager(self)] + [None]*len(self.identity_pool) 113 | 114 | for (i, player) in enumerate(old_player_list): 115 | if player and i != 0: 116 | # Assign a new identity 117 | new_identity = self.pop_from_identity_pool() 118 | 119 | # Copy parameters 120 | new_identity.player_id = player.player_id 121 | new_identity.user = player.user 122 | new_identity.name = player.name 123 | 124 | # Add to player list 125 | try: 126 | self.players[new_identity.player_id] = new_identity 127 | 128 | # If the ID is too large, ask for a new ID 129 | except IndexError: 130 | new_identity.get_id() 131 | self.players[new_identity.player_id] = new_identity 132 | 133 | # Inform the player 134 | new_identity.welcome() 135 | 136 | def pop_from_identity_pool(self): 137 | ''' 138 | Get an identity from identity pool. 139 | ''' 140 | identity = random.choice(self.identity_pool) 141 | self.identity_pool.remove(identity) 142 | return identity 143 | 144 | def str_identity_list(self): 145 | ''' 146 | Get a string representation of identity list. 147 | ''' 148 | str_list = ','.join([player.identity for player in self.identity_list]) 149 | return '当前角色配置为%s' % str_list 150 | 151 | # Main program 152 | def get_ready(self): 153 | # Initialize player list 154 | self.players = [Villager(self)] + [None]*len(self.identity_pool) 155 | self.players[0].died = True # Player 0 is just a placeholder 156 | self.players[0].player_id = 0 157 | 158 | # Wait for players to join the game 159 | while True: 160 | self.event_start_game.clear() 161 | self.event_start_game.wait() 162 | 163 | can_proceed = True 164 | for (i, player) in enumerate(self.players[1:]): 165 | if player == None or not player.ready: 166 | self.broadcast('缺少 %d 号玩家' % (i+1)) 167 | can_proceed = False 168 | 169 | if can_proceed: 170 | break 171 | 172 | def main_loop(self): 173 | self.game_started = True 174 | 175 | # Initialize variables 176 | self.nRound = 0 # Number of days elapsed 177 | seer, savior, witch, silencer, self.werewolves = None, None, None, None, [] 178 | self.killed_players = [] # List of players who are killed last night 179 | 180 | # Find players who have special identities 181 | for player in self.players[1:]: 182 | if isinstance(player, Seer): 183 | seer = player 184 | elif isinstance(player, Witch): 185 | witch = player 186 | elif isinstance(player, Savior): 187 | savior = player 188 | elif isinstance(player, Silencer): 189 | silencer = player 190 | elif isinstance(player, WerewolfLeader): 191 | self.werewolves.insert(0, player) # Insert the leader to the front 192 | elif isinstance(player, Werewolf): 193 | self.werewolves.append(player) 194 | 195 | # Main loop 196 | while True: 197 | self.nRound += 1 198 | 199 | # Night 200 | self.status('-----第%d天晚上-----' % self.nRound, broadcast = True) 201 | 202 | self.broadcast('天黑请闭眼') 203 | play_sound('天黑请闭眼') 204 | 205 | self.broadcast('') 206 | 207 | self.move_for(savior) 208 | 209 | for werewolf in self.werewolves: 210 | if not werewolf.died: 211 | self.move_for(werewolf) 212 | break # Only one werewolf needs to make a choice 213 | 214 | self.move_for(witch) 215 | 216 | if witch == None: 217 | self.is_game_ended() 218 | 219 | self.move_for(seer) 220 | 221 | self.move_for(silencer) 222 | 223 | # Day 224 | self.status('-----第%d天-----' % self.nRound, broadcast = True) 225 | 226 | self.broadcast('天亮啦') 227 | play_sound('天亮了') 228 | 229 | # Vote for Mayor 230 | if self.nRound == 1 and self.config('rules/have_mayor'): 231 | self.vote_for_mayor() 232 | 233 | # Remove players who resurrect 234 | self.killed_players = [player for player in self.killed_players if player.died] 235 | random.shuffle(self.killed_players) 236 | 237 | # Show the result of last night 238 | if self.killed_players: 239 | self.broadcast('昨天晚上,%s 死了' % self.player_list_to_str(self.killed_players)) 240 | else: 241 | self.broadcast('昨天晚上是平安夜~') 242 | 243 | # Trigger after-dying action 244 | for player in self.killed_players: 245 | player.after_dying() 246 | 247 | # Trigger wake-up action 248 | player_list = self.survived_players() 249 | random.shuffle(player_list) 250 | 251 | for player in player_list: 252 | player.wake_up() 253 | 254 | # Vote for suspect 255 | self.vote_for_suspect() 256 | 257 | # Reset killed_players 258 | self.killed_players = [] 259 | 260 | def move_for(self, charactor): 261 | ''' 262 | Called when a charactor needs to take a move. 263 | 264 | charactor: the charactor that needs to take a move 265 | ''' 266 | if charactor == None: 267 | return 268 | 269 | charactor.open_eyes() 270 | 271 | if not charactor.died or charactor in self.killed_players: 272 | charactor.move() 273 | else: 274 | # Won't let the player close eyes immediately even if he/she died. 275 | time.sleep(random.random()*4+4) 276 | 277 | charactor.close_eyes() 278 | 279 | def is_game_ended(self): 280 | ''' 281 | Show game result if game ends. 282 | ''' 283 | # if self.nRound == 1: 284 | # return 285 | 286 | # Count players 287 | villager_count = 0 288 | god_count = 0 289 | werewolf_count = 0 290 | 291 | for player in self.players[1:]: 292 | if not player.died: 293 | if isinstance(player, Villager): 294 | villager_count += 1 295 | elif player.__class__.good: 296 | god_count += 1 297 | else: 298 | werewolf_count += 1 299 | 300 | # Check if the game ends 301 | if villager_count == 0: 302 | self.status('刀民成功,狼人胜利!', broadcast = True) 303 | play_sound('刀民成功') 304 | elif god_count == 0: 305 | self.status('刀神成功,狼人胜利!', broadcast = True) 306 | play_sound('刀神成功') 307 | elif werewolf_count == 0: 308 | self.status('逐狼成功,平民胜利!', broadcast = True) 309 | play_sound('逐狼成功') 310 | else: 311 | return 312 | 313 | # End of game 314 | self.status('游戏结束', broadcast = True) 315 | self.broadcast(self.get_history()) 316 | exit() 317 | 318 | def get_history(self): 319 | ''' 320 | Show player identites status history. 321 | ''' 322 | # Get desciptions of each player 323 | identity_desc = [player.description() for player in self.players[1:]] 324 | 325 | # Show player identites and status history 326 | return '\n'.join(identity_desc + self.history) 327 | 328 | # Voting system 329 | def vote_for_mayor(self): 330 | ''' 331 | Ask players to vote for a Mayor. 332 | ''' 333 | targets = self.players[1:] 334 | 335 | # Ask for candidates 336 | initial_candidates = self.broadcast_choice('是否竞选警长', '%s 完成了是否竞选的选择', targets = targets) 337 | 338 | self.status('%s 竞选警长' % self.player_list_to_str(initial_candidates), broadcast = True) 339 | 340 | # Decide who can vote 341 | can_vote_players = [player for player in targets \ 342 | if player not in initial_candidates] 343 | 344 | # Decide speech order 345 | if initial_candidates: 346 | self.decide_speech_order(initial_candidates) 347 | 348 | # Special case: no candidate 349 | if not initial_candidates: 350 | return 351 | 352 | # Ask candidates whether they want to quite 353 | self.broadcast('正在等待候选人选择是否继续竞选') 354 | candidates = self.broadcast_choice('是否继续竞选', '%s 完成了是否继续竞选的选择', targets = initial_candidates) 355 | 356 | quited_player = [player for player in initial_candidates if player not in candidates] 357 | 358 | # Show remaining candidates 359 | self.status('%s 退水' % self.player_list_to_str(quited_player), broadcast = True) 360 | self.status('%s 继续竞选警长' % self.player_list_to_str(candidates), broadcast = True) 361 | 362 | # Check for special situations 363 | # No candidate 364 | if not candidates: 365 | return 366 | 367 | if not can_vote_players: 368 | self.status('没有人可以投票', broadcast = True) 369 | return 370 | 371 | # Just one candidate 372 | if len(candidates) == 1: 373 | mayor = candidates[0] 374 | 375 | # Vote 376 | else: 377 | self.broadcast('等待玩家投票') 378 | mayor = self.vote(candidates, '请输入你要选为警长的玩家编号', targets = can_vote_players) 379 | 380 | # Assign Mayor 381 | mayor.is_mayor = True 382 | self.have_mayor = True 383 | self.broadcast('%s 当选警长' % mayor.desc()) 384 | self.status('%s 当选警长' % mayor.description()) 385 | 386 | def vote_for_suspect(self): 387 | targets = self.survived_players() 388 | 389 | # Decide speech order 390 | if self.have_mayor: 391 | self.broadcast('请警长选择发言顺序') 392 | else: 393 | self.decide_speech_order(candidates = targets) 394 | 395 | # Vote for suspect 396 | try: 397 | suspect = self.vote(targets, '请输入你要投出的玩家编号,狼人用0号表示爆炸', min_id = 0, targets = targets) 398 | 399 | # If a werewolf explods 400 | except WerewolfExploded as e: 401 | werewolf = e.player 402 | 403 | werewolf.die() 404 | self.broadcast('%s 爆炸' % werewolf.desc()) 405 | self.status('%s 爆炸' % werewolf.description()) 406 | 407 | werewolf.after_dying() 408 | werewolf.after_exploded() 409 | 410 | # Vote out the suspect 411 | else: 412 | if suspect.can_be_voted_out: 413 | self.broadcast('%s 被投出' % suspect.desc()) 414 | self.status('%s 被投出' % suspect.description()) 415 | suspect.die() 416 | suspect.after_dying() 417 | else: 418 | self.broadcast('%s 不能被投出' % suspect.desc()) 419 | self.status('%s 不能被投出' % suspect.description()) 420 | 421 | self.is_game_ended() 422 | 423 | # Give players some time to view the result 424 | self.broadcast_choice('查看结果后,回复y以继续游戏', '%s 已确认今天的结果', targets = targets) 425 | 426 | def decide_speech_order(self, candidates): 427 | ''' 428 | Randomly choose an order for players to give a speech. 429 | 430 | candidate: list of players who can give a speech. 431 | ''' 432 | first_player = random.choice(candidates) 433 | direction = random.choice(['顺时针', '逆时针']) 434 | self.broadcast('从 %s %s发言' % (first_player.desc(), direction)) 435 | 436 | def broadcast_choice(self, message, finish_message, targets = None): 437 | ''' 438 | Ask several players to choose yes/no at the same time. 439 | 440 | message: message that describes choices. 441 | finish_message: status message for players who finished choice 442 | targets: list of players that needs to make the choice. 443 | 444 | Return a list of players who choose yes. 445 | ''' 446 | accepted_players = [] 447 | first_respond_event = threading.Event() # Set when first respond is received 448 | broadcast_event = threading.Event() # Set when it's time to reveal the result 449 | finish_events = [] # Set when the player finishes voting 450 | 451 | def ask_for_choice(player, finish_event): 452 | if player.decide(message): 453 | accepted_players.append(player) 454 | 455 | player.message('收到') 456 | first_respond_event.set() 457 | 458 | broadcast_event.wait() 459 | self.players[1].message(finish_message % player.desc()) 460 | 461 | finish_event.set() 462 | 463 | # Collect reply 464 | for player in targets: 465 | finish_event = threading.Event() 466 | finish_events.append(finish_event) 467 | 468 | threading.Thread(target = ask_for_choice, args = (player,finish_event)).start() 469 | 470 | # Broadcast status after some time 471 | first_respond_event.wait() 472 | time.sleep(self.config('system/vote_waiting_time')) 473 | broadcast_event.set() 474 | 475 | # Wait for all players to finish 476 | for event in finish_events: 477 | event.wait() 478 | 479 | return accepted_players 480 | 481 | def vote(self, candidates, message, min_id = 1, targets = None): 482 | ''' 483 | Ask players to vote. 484 | 485 | candidates: list of players who can be voted. 486 | message: prompt message. 487 | min_id: minimum player id that voters can choose. 488 | targets: list of players who can vote. 489 | 490 | Return the player who has the highest vote. 491 | ''' 492 | while True: 493 | # Get and show result 494 | (vote_statistic, give_up) = self.get_vote_statistic(candidates, message, min_id, targets = targets) 495 | self.show_vote_result(vote_statistic, give_up) 496 | 497 | # Check if two people get equal votes 498 | try: 499 | if vote_statistic[0][2] == vote_statistic[1][2]: 500 | self.broadcast('票数相同,重新投票') 501 | continue 502 | else: 503 | break 504 | except IndexError: 505 | break 506 | 507 | return vote_statistic[0][0] 508 | 509 | def get_vote_statistic(self, candidates, message, min_id = 1, targets = None): 510 | ''' 511 | Ask players to vote. 512 | 513 | candidates: list of players who can be voted. 514 | message: prompt message. 515 | min_id: minimum player id that voters can choose. 516 | targets: list of players who can vote. 517 | 518 | Return a list of tuple and a list of players who give up. 519 | Elements in each tuple: 520 | [0]:candidate 521 | [1]:list of players who voted for this candidate 522 | [2]:vote count for this candidate 523 | ''' 524 | voted_for = [list() for i in range(len(self.players) + 1)] 525 | vote_count = [0]*(len(self.players) + 1) 526 | give_up = [] 527 | 528 | # Ask for vote 529 | vote_result = self.get_vote_result(candidates, message, min_id, targets) 530 | 531 | # Count votes 532 | for (voter, elected_id) in vote_result: 533 | if elected_id == 0: 534 | raise WerewolfExploded(voter) 535 | elif elected_id == -1: 536 | give_up.append(voter) 537 | continue 538 | 539 | # Count votes 540 | voted_for[elected_id].append(voter) 541 | 542 | if voter.is_mayor: 543 | vote_count[elected_id] += 1.5 544 | else: 545 | vote_count[elected_id] += 1 546 | 547 | # Sort votes 548 | vote_statistic = [(candidate, voted_for[candidate.player_id], vote_count[candidate.player_id]) \ 549 | for candidate in candidates] 550 | vote_statistic.sort(key = lambda x: x[2], reverse = True) 551 | 552 | return (vote_statistic, give_up) 553 | 554 | def get_vote_result(self, candidates, message, min_id, targets): 555 | vote_result = [] 556 | first_respond_event = threading.Event() # Set when first respond is received 557 | broadcast_event = threading.Event() # Set when it's time to reveal the result 558 | finish_events = [] # Set when the player finishes voting 559 | 560 | def ask_for_vote(player, finish_event): 561 | if player.decide('是否投票'): 562 | while True: 563 | voted_id = player.select_player(message, min_id = min_id, candidates = candidates) 564 | 565 | # Vote for number 0 means explode 566 | if voted_id == 0: 567 | if player.good or not self.config('rules/werewolf_can_explode'): 568 | player.message('你不能爆炸') 569 | continue 570 | 571 | vote_result.append((player, voted_id)) 572 | break 573 | else: 574 | vote_result.append((player, -1)) 575 | 576 | player.message('收到') 577 | first_respond_event.set() 578 | 579 | broadcast_event.wait() 580 | self.players[1].message('%s 已投票' % player.desc()) 581 | 582 | finish_event.set() 583 | 584 | # Ask for vote 585 | for player in targets: 586 | finish_event = threading.Event() 587 | finish_events.append(finish_event) 588 | 589 | threading.Thread(target = ask_for_vote, args = (player, finish_event)).start() 590 | 591 | # Boradcast status after some time 592 | first_respond_event.wait() 593 | time.sleep(self.config('system/vote_waiting_time')) 594 | broadcast_event.set() 595 | 596 | # Wait for vote 597 | for event in finish_events: 598 | event.wait() 599 | 600 | return vote_result 601 | 602 | def show_vote_result(self, vote_results, give_up): 603 | ''' 604 | Broadcast voting result. 605 | 606 | vote_results: the list returned by 'get_vote_statistic' 607 | give_up: list of players who give up voting 608 | ''' 609 | messages = [] 610 | 611 | for player in give_up: 612 | messages.append('%s 弃票' % player.desc()) 613 | 614 | for vote_statistic in vote_results: 615 | # Unpack data 616 | player = vote_statistic[0] 617 | voted_by = vote_statistic[1] 618 | vote_count = vote_statistic[2] 619 | 620 | # Get string representation of voted_by 621 | str_voted_by = self.player_list_to_str(voted_by) 622 | 623 | # Broadcast the message 624 | messages.append('%s 获得 %.1f 票(%s)' % (player.desc(), float(vote_count), str_voted_by)) 625 | 626 | self.broadcast('\n'.join(messages)) 627 | 628 | # Message system 629 | def broadcast(self, message, targets = None): 630 | ''' 631 | Broadcast a message. If 'targets' is 'None', broadcast to all players. 632 | 633 | message: the message to be broadcasted 634 | targets: list of players to receive this message 635 | ''' 636 | # Default target 637 | if targets == None: 638 | targets = self.players[1:] 639 | 640 | # Broadcast the message 641 | for player in targets: 642 | if player: 643 | player.message(message) 644 | 645 | def broadcast_to_wolves(self, message): 646 | ''' 647 | Broadcast a message to werewolves. 648 | ''' 649 | if message: 650 | message = '狼人:' + message 651 | 652 | self.broadcast(message, targets = self.werewolves) 653 | 654 | def status(self, message, broadcast = False): 655 | ''' 656 | Store a status message. 657 | 658 | message: the status message 659 | broadcast: if 'True', the message will be broadcasted to players. 660 | ''' 661 | message_with_time = '[%s]%s' % (time.strftime('%H:%M:%S'), message) 662 | self.history.append(message_with_time) 663 | print(message_with_time) 664 | 665 | if broadcast: 666 | self.broadcast(message) 667 | 668 | # Other methods 669 | def survived_players(self): 670 | ''' 671 | Get a list of survivied players 672 | ''' 673 | return [player for player in self.players[1:] if not player.died] 674 | 675 | def wait_random_time(self): 676 | ''' 677 | Wait for a random amount of time. 678 | ''' 679 | time.sleep(random.random()*4+4) 680 | 681 | def player_list_to_str(self, players): 682 | ''' 683 | Convert a list of player to a string representation of it. 684 | 685 | players: list of players 686 | 687 | Return the string. 688 | ''' 689 | if not players: 690 | result = '没有人' 691 | else: 692 | result = ','.join([player.desc() for player in players]) 693 | 694 | return result 695 | 696 | if __name__ == '__main__': 697 | main() -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | 676 | --------------------------------------------------------------------------------