-
Notifications
You must be signed in to change notification settings - Fork 1
/
quantumwerewolf.py
265 lines (221 loc) · 10.3 KB
/
quantumwerewolf.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
from itertools import permutations
from random import shuffle, choice
class Game:
def __init__(self):
self.players = []
self.role_count= {'werewolf':2, 'seer':1}
self.player_count = 10
self.started = False
# Add players to the game
def add_players(self, *names):
# name: the name (or list of names) of the player(s) to add
# The game can't be ongoing
if not self.check_started(False):
return None
# Add names from input and input lists
for name in names:
if isinstance(name, str):
# Check if name is not already taken
if name in self.players:
print("Player {} already exists!".format(name))
else: self.players.append(name)
elif isinstance(name, list):
# unwrap list and pass to add_players again
self.add_players(*name)
else: print("Wrong data type: {}, must be either string or list of strings".format(type(name)))
# Set the contents of the deck
def set_role(self, role, amount):
# roles: [werewolves, seers]
self.role_count[role] = amount
# Identify the player names with their IDs
# def identify_players(self):
# self.player_count = len(self.players)
# idfy = [[i+1, self.players[i]] for i in range(self.player_count)]
# print(tabulate(idfy, headers = ["ID", "Name"]))
# Start the game
def start(self):
if self.check_started(False):
# Determine playercount or generate players if none are given
if self.players != []:
self.player_count = len(self.players)
else:
self.players = ["Player " + str(x+1) for x in range(self.player_count)]
# Generate permutation list for anomymous printing in print_probabilities()
self.print_permutation = list(range(self.player_count))
shuffle(self.print_permutation)
# Determine (valid) amount of villager in the game
villagers = self.player_count - sum(self.role_count.values())
if villagers < 0:
print("Too few players, decrease the amount of roles!")
return False
# Sets the list of roles
roles = self.role_count['werewolf'] * ["w"] + self.role_count['seer'] * ["s"] + villagers * ["v"]
self.werewolf_count = self.role_count['werewolf']
# Generates the list of all role permutations
self.permutations = list(permutations(roles))
# Set all players to be fully alive
self.deaths = []
for i in range(self.player_count):
self.deaths += [[0] * self.player_count]
self.killed = [0] * self.player_count
# start game
self.started = True
print("Game started.")
self.calculate_probabilities()
return True
# Stop the game
def stop(self):
if self.check_started():
self.started = False
print("Game stopped.")
# Reset the game
def reset(self):
self.players = []
self.role_count= {'werewolf':2,'seer':1}
if self.started == True:
self.stop()
print("Game reset.")
# Check if game has(n't) started and throw error otherwise
def check_started(self, boolean = True):
# boolean: set this to false if you want to check if you HAVEN'T started yet
# The point of this function is to throw an error if the game hasn't started yet
if self.started == boolean:
return True
else:
if boolean:
print("Please start the game first with start().")
return False
else:
print("Please stop the game first with stop().")
return False
# Returns the ID corresponding to someone's name
def ID(self, player_name):
#name: the name of the player
return self.players.index(player_name)
# Returns the ID corresponding to someone's name
def name(self, player_id):
#name: the name of the player
return self.players[player_id]
# Return the role corresponding to some letter
def role(self, letter):
# letter: the letter who's corresponding role you want to know
roles = ["villager", "werewolf", "seer"]
letters = ["v", "w", "s"]
return roles[letters.index(letter)]
# Gives the table of probabilities
def print_probabilities(self):
if self.check_started():
self.calculate_probabilities()
print("There are {} possible permutations left.\n".format(self.nperm))
print("{:>12s}{:>12s}{:>12s}{:>12s}{:>12s}".format("Player", "Villagers", "Seer", "Werewolf", "Dead"))
for i, j in enumerate(self.print_permutation):
p = self.probs[j]
if p['dead'] == 1:
i = p['name']
print("{:>12s}{:11.0f}%{:11.0f}%{:11.0f}%{:11.0f}%".format(str(i), 100*p['villager'], 100*p['seer'], 100*p['werewolf'], 100*p['dead']))
# Calculates the probabilities
def calculate_probabilities(self):
if self.check_started():
self.nperm = len(self.permutations)
transpose = list(zip(*self.permutations))
self.probs = []
for i, p in enumerate(self.players):
P_villager = transpose[i].count("v") / self.nperm
P_seer = transpose[i].count("s") / self.nperm
P_werewolf = transpose[i].count("w") / self.nperm
P_dead = self.death_probability(p)
self.probs.append({'name': p, 'werewolf': P_werewolf, 'villager': P_villager, 'seer': P_seer, 'dead': P_dead})
# Let a player take his seer action
def seer(self, seer, target):
# seer: name of the seer
# target: name of the target of the seer
if self.check_started():
seer_id = self.ID(seer)
target_id = self.ID(target)
# Check if player and target are alive and player can be the seer
assert self.killed[seer_id] != 1, "ERROR: in seer() seer {} is dead.".format(seer)
assert self.killed[target_id] != 1, "ERROR: in seer() target {} is dead.".format(target)
assert self.probs[seer_id]['seer'] != 0, "ERROR: in seer() {}'s seer probability is 0.".format(seer)
# Player is allowed to take the action
print("{} is investigating {} ...".format(seer, target))
p_list = [p in self.permutations if p[seer_id] == 's']
# Choose an outcome
assert len(p_list) > 0, "ERROR: seer list is empty"
observation = choice(p_list)[target_id]
# Collapse the wave function
for p in p_list:
if p[target_id] != observation:
self.permutations.remove(p)
# Report on results
print("{} sees that {} is a {}!".format(seer, target, self.role(observation)))
# Force someone's death (e.g., after a vote). Otherwise used only by script
def kill(self, target):
# target: the name of the target
target_id = self.ID(target)
if self.check_started():
assert self.killed[target_id] != 1, "ERROR:in kill() target {} is already dead.".format(target)
print("{} was killed!".format(target))
# Chooses an outcome
res = choice(self.permutations)
prole = res[target_id]
permt = list(self.permutations)
# Collapse the wave function
for p in permt:
if p[target_id] != prole:
self.permutations.remove(p)
# Report on results
print("{} was a {}!".format(target, self.role(prole)))
# Deal with the case that the dead person is a werewolf
if self.role(prole) == "w":
self.werewolf_count -= 1
for i in range(self.player_count):
deaths[i][target_id] = 0
self.killed[target_id] = 1
self.calculate_probabilities()
# Shows the probability of death for a player
def death_probability(self, name):
# name: name of player
name_id = self.ID(name)
if self.check_started():
dead = 0
if self.killed[name_id] == 1:
dead = 1
else:
deathn = 0
for p in self.permutations:
for i in range(self.player_count):
if p[i] == "w" and p[name_id] != "w":
deathn += self.deaths[name_id][i]
dead = deathn / len(self.permutations)
if dead >= 1:
self.kill(name)
return dead
# Lets someone commit their werewolf action
def werewolf(self, werewolf, target):
# werewolf: the name of the werewolf
# target: the name of the werewolf's target
werewolf_id = self.ID(werewolf)
target_id = self.ID(target)
if self.check_started():
assert self.killed[werewolf_id] != 1, "ERROR: in werewolf() werewolf {} is dead".format(werewolf)
assert self.killed[target_id] != 1, "ERROR: in werewolf() target {} is dead".format(target)
assert self.probs[werewolf_id]['werewolf'] != 0, "ERROR: in werewolf() {}'s werewolf probability is 0".format(target)
self.deaths[target_id][werewolf_id] = 1 / self.werewolf_count
print("{} has mauled {}!".format(werewolf, target))
def check_win(self):
villager_win = True
werewolf_win = True
for perm in self.permutations:
for ID, role in enumerate(perm):
if self.killed[ID] == 0:
if role == 'w':
villager_win = False
else:
werewolf_win = False
if villager_win:
print('The villagers win!')
return True
if werewolf_win:
print('The werewolves win!')
return True
return False