-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgame.py
704 lines (583 loc) · 22.6 KB
/
game.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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
import traceback
from difflib import SequenceMatcher
import copy
import time
import timers
import mafl
class Game:
def __init__(self, rng):
self.channel = None
self.queue = mafl.Mqueue()
self.resqueue = mafl.Mqueue()
self.delayqueue = mafl.Mqueue()
self.bus = {}
self.slot = {} # name to slot
self.name = {} # slot to name
self.players = []
self.out = []
self.phase = mafl.phase.Idle
self.newphase = mafl.phase.Idle
self.votes = {}
self.timers = timers.Timers()
self.lastvc = 0
self.fake = {}
self.rng = rng
self.verbose = False
self.setupargs = ['Setup']
def message(self, who, message):
if who in self.fake:
self.out.append((self.fake[who], "(%s) %s"%(who, message)))
else:
self.out.append((who, message))
####
def slotbyname(self, name):
return self.slot.get(name.lower(), None)
def slotbyplayer(self, player):
return self.slotbyname(player.name.lower())
def playerbyslot(self, slot):
return self.players[slot]
def bussedslot(self, slot):
bussed = self.bus.get(slot, [slot])
print("in bussed slot",bussed)
return bussed[0]
def playerbyslotbus(self, slot):
return self.playerbyslot(self.bussedslot(slot))
def playerbyname(self, name):
slot = self.slotbyname(name.lower())
if slot is None:
print("no player",name)
return None
else:
return self.playerbyslot(slot)
def messageslot(self, slot, message):
target = self.playerbyslot(slot)
if target.living:
self.message(target.name, message)
####
def fix(self, targets):
return [self.bussedslot(x) for x in targets]
def nextphase(self, newphase=None):
print("nextphase",newphase)
if newphase:
self.newphase = newphase
else:
self.newphase = self.phase.nextphase
def newplayer(self, name, virtual=False):
if not self.playerbyname(name):
slot = len(self.players)
self.slot[name.lower()] = slot
self.name[slot] = name
newp = mafl.Player(name, virtual)
self.players.append(newp)
return newp
def join(self, channel, name, args):
if name != "nolynch" and self.playerbyname(name) is None:
if self.phase == mafl.phase.Idle:
self.start(channel)
self.newplayer(name)
elif self.phase == mafl.phase.Signups:
self.newplayer(name)
if args:
self.changesetup(args[0:])
def enqueue(self, action):
print("enqueue",action)
self.queue.enqueue(action)
def resolved(self, action):
self.resqueue.enqueue(action)
def delay(self, phases, action):
print("delay",phases,action)
self.delayqueue.enqueue((phases - 1, action))
def resolve(self):
if self.queue:
if self.verbose:
print("resolve",self.queue)
self.useautoabilities()
count = len(self.queue) + 10
if self.verbose:
print("resolve",count)
while self.queue and count > 0:
count -= 1
if self.verbose:
print("resolve q:", self.queue)
act = self.queue.pop()
if self.verbose:
print("resolve act:", act)
self.queue = act.resolve(self)
if self.verbose:
print("resolve done",count)
def resetresolved(self):
self.resqueue = mafl.Mqueue()
def resetqueues(self):
self.resqueue = mafl.Mqueue()
self.queue = mafl.Mqueue()
def resetvotes(self):
self.votes = {}
def resetuses(self):
for player in self.realplayers():
for abi in player.allabilities():
abi.reset()
def resetout(self):
self.out = []
def startphase(self):
print("startphase")
self.resetuses()
self.resetqueues()
self.resetvotes()
# self.useautoabilities()
if self.phase == mafl.phase.Signups:
self.message(None, "New game starting, join now")
def reset(self):
channel = self.channel
self.__init__(self.rng)
self.channel = channel
def playernames(self):
return list(self.name.values())
def names(self, slots):
return [self.name[x] for x in slots]
def livingslots(self):
living = []
for name, slot in self.slot.items():
player = self.playerbyslot(slot)
if player.living and not player.virtual:
living.append(slot)
return living
def realplayers(self):
return list(filter(lambda x: not x.virtual, self.players))
def living(self):
living = []
for name, slot in self.slot.items():
player = self.playerbyslot(slot)
if player.living and not player.virtual:
living.append(player)
return living
def dead(self):
dead = []
for name, slot in self.slot.items():
player = self.playerbyslot(slot)
if not player.living and not player.virtual:
dead.append(player)
return dead
def checkwin(self):
winners = []
losers = []
draw = []
for name, slot in self.slot.items():
player = self.playerbyslot(slot)
if not player.virtual:
if player.faction.win(self, player):
winners.append(slot)
else:
losers.append(slot)
draw.append(slot)
if not self.living():
return ((), (), draw)
if winners:
return (winners, losers, ())
return ((), (), ())
def changesetup(self, args):
if self.phase == mafl.phase.Signups:
print("changesetup",args)
self.setupargs = args
self.message(None, "setup changed to %s"%args[0])
def start(self, channel):
if self.phase == mafl.phase.Idle:
print("start")
self.newplayer('nolynch', True)
self.channel = channel
self.nextphase()
self.timers.settimer('start', 307)
def wait(self):
if self.phase == mafl.phase.Signups:
remaining = self.timers.remaining('start')
if remaining and remaining.v < 61:
self.timers.settimer('start', 61)
self.message(None, "game start delayed %d seconds"%61)
def go(self, now):
if self.phase == mafl.phase.Signups:
if now == "now":
self.nextphase()
else:
remaining = self.timers.remaining('start')
if remaining and remaining.v > 11:
self.timers.settimer('start', 11)
def tick(self):
if self.phase == mafl.phase.Signups:
remaining = self.timers.remaining('start')
if remaining and remaining.v < 0:
self.nextphase()
elif remaining and remaining.v in (307,229,97,31,7):
self.timers.dec('start')
self.message(None, "game starts in %d seconds"%(remaining.v))
if self.phase == mafl.phase.Day:
self.timers.setfirst('vote', 181)
if self.timers.expired('vote'):
self.votecount()
self.timers.settimer('vote', 181)
if self.phase == mafl.phase.Night:
self.timers.setfirst('night', 181)
remaining = self.timers.remaining('night')
if remaining and remaining.v in (173,89,37,11):
self.timers.dec('night')
self.message(None, "night ends in %d seconds"%(remaining.v))
if remaining and remaining.v < 0:
self.message(None, "night timed out")
self.nextphase()
if self.timers.expired('randomize'):
self.nextphase()
if self.phase.started:
# modkill timers
for p in self.living():
self.timers.setfirst('%' + p.name.lower(), 307)
remaining = self.timers.remaining('%' + p.name.lower())
if remaining and remaining.v in (23,5):
self.message(p.name, "modkill in %d seconds"%remaining.v)
self.timers.dec('%' + p.name.lower())
if remaining and remaining.v <= 0:
target = self.slotbyname(p.name)
self.enqueue(mafl.actions.Disable(0, [target]))
self.enqueue(mafl.actions.SuperKill(0, [target], args={'how':'died of boredom'}))
def phasemsg(self, who=None):
self.message(who, self.phase.name)
def deadmsg(self, who=None):
dead = self.dead()
msg = "%d dead players: %s"% (len(dead), ", ".join([x.name for x in dead]))
self.message(who, msg)
def livingmsg(self, who=None):
living = self.living()
msg = "%d living players: %s"% (len(living), ", ".join([x.name for x in living]))
self.message(who, msg)
def fullrolepm(self, name):
player = self.playerbyname(name)
if player and not player.virtual:
self.message(name, player.fullrolepm(self))
def done(self, name):
player = self.playerbyname(name)
if player and not player.virtual:
player.done(self)
self.message(name, 'OK')
def undelay(self):
newqueue = mafl.Mqueue()
while self.delayqueue:
(phases, action) = self.delayqueue.pop()
print("undelay:",phases)
if phases <= 0:
self.queue.enqueue(action)
else:
newqueue.enqueue((phases - 1, action))
self.delayqueue = newqueue
def useautoability(self, player):
slot = self.slotbyplayer(player)
abilities = player.allabilities()
for action in filter(None, map(lambda x: x.useauto(self, self.phase, slot), abilities)):
print("enqueue(auto)",action)
self.enqueue(action)
def useautoabilities(self):
for player in self.players:
self.useautoability(player)
def run(self):
done = 0
# print("state.run")
if self.phase.started:
# if nobody has an unused ability, end the phase
# if no player has an ability (night or day) then
# it'll instantly alternate between day and night forever
# check for unused actions
unused = False
for name, slot in self.slot.items():
player = self.playerbyslot(slot)
if player.unused(self):
unused = True
if not unused:
# anti-meta timer (range is maybe too small)
self.timers.setfirst('randomize', self.rng.randint(3,13))
# tick will cause nextphase
if self.phase.instant:
self.resolve()
win,lose,draw = self.checkwin()
if win or draw:
if draw:
self.message(None, "game over, draw: %s"% ", ".join(self.names(draw)))
else:
self.message(None, "game over, winners: %s"% ", ".join(self.names(win)))
self.message(None, "losers: %s"% ", ".join(self.names(lose)))
self.nextphase(mafl.phase.Done)
self.showsetuppost(None)
# phase changed!
if self.phase != self.newphase:
# reset timers
if self.phase != mafl.phase.Idle:
self.timers = timers.Timers()
if self.phase == mafl.phase.Signups:
pl = self.realplayers()
print("starting setup:",self.setupargs)
setupclass = mafl.setup.setups.get(self.setupargs[0], mafl.setup.Setup)
self.setup = setupclass(self.rng, self.setupargs[1:])
if self.setup.getroles(len(pl)):
self.setup.setroles(pl)
print("sending roles")
# send role pms
for name, slot in self.slot.items():
player = self.playerbyslot(slot)
if not player.virtual:
self.message(name, player.fullrolepm(self))
else:
self.message(None, "Failed to assign roles, canceled game")
self.nextphase(mafl.phase.Done)
self.undelay()
# resolve the previous phase's actions,
# must do this before enqueuing auto abilities
self.resolve()
self.phase = self.newphase
if self.phase.started:
self.phasemsg()
self.livingmsg()
self.startphase()
ret = copy.deepcopy(self.out)
if self.phase is mafl.phase.Done:
self.reset()
self.out = []
return ret
def majority(self):
return int(len(self.living()) / 2)
def vote(self, voter, targets):
print("vote",voter,targets)
# unvote first
for k,v in self.votes.items():
if voter in self.votes[k]:
self.votes[k].remove(voter)
for k in list(self.votes.keys()):
if not self.votes[k]:
del self.votes[k]
lynched = False
for target in targets:
if target in self.votes and self.votes[target]:
self.votes[target].append(voter)
else:
self.votes[target] = [voter]
if len(self.votes[target]) > self.majority():
self.enqueue(mafl.actions.Lynch(voter, [target]))
lynched = True
if lynched:
self.nextphase()
def votecount(self, force=False):
if force or time.time() > self.lastvc + 10:
self.lastvc = time.time()
self.message(None, "Vote count: %d to lynch"%(self.majority()+1))
for k,v in self.votes.items():
print("votecount:",k,v)
voters = [self.playerbyslot(x).name for x in v]
wagon = "%s (%d) - %s" % (self.playerbyslot(k).name, len(voters), ', '.join(voters))
self.message(None, wagon)
def replace(self, p1, p2, quiet=False):
if p1 == p2:
return
slot = self.slotbyname(p1)
slot2 = self.slotbyname(p2)
if slot != None and slot2 == None:
player = self.playerbyslot(slot)
if player.virtual:
return
player.name = p2
self.slot[p2.lower()] = slot
del self.slot[p1.lower()]
self.name[slot] = p2
if p1 in self.fake:
self.fake[p2] = self.fake[p1]
remain = self.timers.remaining('%'+p1.lower())
self.timers.remove('%'+p1.lower())
if remain:
self.timers.settimer('%'+p2.lower(), remain.v)
else:
self.timers.settimer('%'+p2.lower(), 307)
res = "replaced %s with %s"%(p1,p2)
elif slot2:
res = "player %s is already playing"%p2
else:
res = "player %s doesn't exist"%p1
if not quiet:
self.message(None, res)
def setrole(self, who, args):
align = "town"
add = False
if len(args) >= 2:
p1 = args[0]
rolename = args[1]
if len(args) == 3:
align = args[2]
if len(args) == 4:
add = args[3] == '+'
player = self.playerbyname(p1)
newrole = mafl.role.roles.get(rolename, None)
faction = mafl.faction.factions.get(align, None)
facinstance = None
if faction:
for p in self.players:
if isinstance(p.faction, faction):
facinstance = p.faction
break
if not facinstance:
facinstance = faction()
else:
facinstance = player.faction
if newrole and player and facinstance:
if add:
player.addrole(newrole)
else:
player.setrole(newrole, facinstance)
self.useautoability(player)
self.message(None, "%s role set"%p1)
return True
elif not player:
self.message(None, "didn't find player %s"%p1)
return False
elif not newrole:
self.message(None, "didn't find role %s"%rolename)
return False
elif not faction:
self.message(None, "didn't find faction %s"%align)
def showsetup(self, who):
for name, slot in self.slot.items():
player = self.playerbyslot(slot)
if not player.virtual:
self.message(who, name + ": " + player.fullrolepm(self))
def showsetuppost(self, who):
byfac = {}
for p in self.realplayers():
if str(p.faction) in byfac:
byfac[str(p.faction)].append(p.name+" was a "+p.truename)
else:
byfac[str(p.faction)] = [p.name+" was a "+p.truename]
msg = []
for k,v in byfac.items():
msg.append("%s: %s" %(k, ", ".join(v)))
self.message(who, "setup: " + "; ".join(msg))
def fuzzy(self, tryname):
best = 0
match = None
names = self.playernames()
if tryname in names:
return (tryname, 1, tryname)
for name in filter(lambda x:len(x) > 1, names):
ratio = SequenceMatcher(None, tryname.lower(), name.lower()).ratio()
if ratio > best:
best = ratio
match = name
return (tryname, best, match)
def cleanargs(self, args):
return [self.fuzzy(x) for x in args]
def activity(self, who):
player = self.playerbyname(who)
if player:
# reset modkill timer
self.timers.settimer('%'+who.lower(), 307)
def tryability(self, who, public, ability, args):
player = self.playerbyname(who)
if player:
self.activity(who)
print("found player:",who,player)
try:
cleaned = []
mangled = []
for tryname, best, match in self.cleanargs(args):
if best > 0.6:
print("fuzzy match",tryname,best,match)
cleaned.append(match)
else:
mangled.append(tryname)
if mangled:
self.message(who, "%s not found" %mangled)
else:
if player.faction and ability in player.faction.abilities:
(res, msg) = player.faction.abilities[ability].use(self, public, player, cleaned)
# faction ability failed, now try player ability
if not res and ability in player.abilities:
(res, msg) = player.abilities[ability].use(self, public, player, cleaned)
self.message(who, msg)
elif ability in player.abilities:
(res, msg) = player.abilities[ability].use(self, public, player, cleaned)
self.message(who, msg)
except Exception as e:
print("exception trying to handle player ability: %s\n%s\n" %(ability, e))
traceback.print_exc()
def newsetup(self):
self.phase = mafl.phase.Signups
self.nextphase()
def testsetup(self, args):
if len(args) == 0:
args.append('7')
if len(args) == 1:
args.append('Setup')
if len(args) >= 2 and int(args[0]):
n = int(args[0])
if n <= 26:
name = args[1]
setupclass = mafl.setup.setups.get(name, mafl.setup.Setup)
print("testsetup for",setupclass,n)
self.setup = setupclass(self.rng, args[2:])
if self.setup.getroles(n):
byfac = {}
for r,f in self.setup.roles:
if str(f.name) in byfac:
byfac[str(f.name)].append(r.getname())
else:
byfac[str(f.name)] = [r.getname()]
msg = []
for k,v in byfac.items():
roles = []
v.sort()
prev = None
count = 0
for role in v:
if prev:
if role == prev:
count += 1
else:
roles.append((count, prev))
count = 0
prev = role
else:
roles.append((count, role))
strs = []
for count,role in roles:
if count:
strs.append("%s (x%d)" % (role, count+1))
else:
strs.append(role)
msg.append("%s: %s" %(k, ", ".join(strs)))
return "; ".join(msg)
else:
return "setup failed"
else:
return "limit is 26"
def gotest(self, to, who, args):
print("gotest",args)
if len(args) >= 1 and int(args[0]) <= 26 and self.phase == mafl.phase.Idle:
self.start(to)
self.phase = mafl.phase.Signups
if len(args) >= 2:
self.changesetup(args[1:])
self.verbose = True
n = int(args[0])
print("runtest for ",n)
for name in [chr(ord('a') + x) for x in range(n)]:
self.newplayer(name)
self.fake[name] = who
self.nextphase(mafl.phase.Day)
def makefake(self, who, args):
fakecmd = args[1]
if fakecmd[0] == '%':
fakecmd = fakecmd[1:]
if fakecmd == 'join':
self.fake[args[0]] = who
def rolepower(self, who, args):
if len(args) == 3:
rolename = args[0]
n = int(args[1])
align = args[2]
if n > 26:
return
faction = mafl.faction.factions.get(align, None)
r = mafl.role.roles.get(rolename, None)
if r and faction:
power = r.power(n, faction)
self.message(who, "%s %0.2f" %(r.getname(), power))