-
Notifications
You must be signed in to change notification settings - Fork 22
/
models.py
1579 lines (1447 loc) · 64.5 KB
/
models.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
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from google.appengine.ext import ndb
from google.appengine.ext.ndb.model import ModelKey
from google.appengine.api import users
import logging as log
import random
from json import dumps as jsonify
from datetime import datetime, timedelta
from calendar import timegm
from collections import defaultdict, OrderedDict
from typing import List, Dict, Optional
from seedbuilder.seedparams import Placement, Stuff, SeedGenParams
from enums import MultiplayerGameType, ShareType, Variation
from util import picks_by_coord, get_bit, get_taste, enums_from_strlist, ord_suffix, debug, bfields_to_coords
from pickups import Pickup, Skill, Teleporter, Event
from cache import Cache
trees_by_coords = {
-3160308: Pickup.n("RB", 900),
-560160: Pickup.n("RB", 901),
7839588: Pickup.n("RB", 902),
5320328: Pickup.n("RB", 903),
8599904: Pickup.n("RB", 904),
-4600020: Pickup.n("RB", 905),
-11880100: Pickup.n("RB", 906),
-6959592: Pickup.n("RB", 907),
719620: Pickup.n("RB", 908),
2919744: Pickup.n("RB", 909),
}
zone_translate = {
"Valley": "valleyOfTheWind",
"Sorrow": "sorrowPass",
"Glades": "sunkenGlades",
"Forlorn": "forlornRuins",
"Grove": "hollowGrove",
"Blackroot": "mangrove",
"Grotto": "moonGrotto",
"Horu": "mountHoru",
"Swamp": "thornfeltSwamp",
"Misty": "mistyWoods",
"Ginso": "ginsoTree",
}
map_coords_by_zone = {
"valleyOfTheWind": -4080172,
"sorrowPass": -4519716,
"sunkenGlades": -840248,
"forlornRuins": -8440308,
"hollowGrove": 3479880,
"mangrove": 4159708,
"moonGrotto": 4759608,
"mountHoru": 560340,
"thornfeltSwamp": 6759868
}
relics_by_zone = {
"sunkenGlades": Pickup.n("RB", 911),
"hollowGrove": Pickup.n("RB", 912),
"moonGrotto": Pickup.n("RB", 913),
"mangrove": Pickup.n("RB", 914),
"thornfeltSwamp": Pickup.n("RB", 915),
"ginsoTree": Pickup.n("RB", 916),
"valleyOfTheWind": Pickup.n("RB", 917),
"mistyWoods": Pickup.n("RB", 918),
"forlornRuins": Pickup.n("RB", 919),
"sorrowPass": Pickup.n("RB", 920),
"mountHoru": Pickup.n("RB", 921)
}
def _pid(pkey):
# type: (ModelKey) -> int
try:
return int(pkey.id().partition(".")[2])
except Exception as e:
log.error("invalid pkey %s: %s, returning 1", pkey, e)
return 1
def round_time(t):
parts = str(t).split(":")
parts[-1] = str(round(float(parts[-1]), 2))
if len(parts[-1].partition(".")[0]) < 2:
parts[-1] = "0"+parts[-1]
return ":".join(parts)
# helper function, checks if a pickup stacks
def stacks(pickup):
if pickup.stacks:
return True
if pickup.code != "RB":
return False
return pickup.id in [6, 9, 12, 13, 15, 17, 19, 21, 28, 30, 31, 32, 33, 37, 81]
pbc = picks_by_coord(extras=True)
lines_by_index = {
'Row 1': [0, 1, 2, 3, 4],
'Row 2': [5, 6, 7, 8, 9],
'Row 3': [10, 11, 12, 13, 14],
'Row 4': [15, 16, 17, 18, 19],
'Row 5': [20, 21, 22, 23, 24],
'Col A': [0, 5, 10, 15, 20],
'Col B': [1, 6, 11, 16, 21],
'Col C': [2, 7, 12, 17, 22],
'Col D': [3, 8, 13, 18, 23],
'Col E': [4, 9, 14, 19, 24],
'A1-E5': [0, 6, 12, 18, 24],
'E1-A5': [4, 8, 12, 16, 20]
}
class BingoCardProgress(ndb.Model):
square = ndb.IntegerProperty()
completed = ndb.BooleanProperty(default=False)
count = ndb.IntegerProperty(default=0)
completed_subgoals = ndb.StringProperty(repeated=True)
def to_json(self):
return {
'completed': self.completed,
'count': self.count,
'subgoals': self.completed_subgoals
}
class HistoryLine(ndb.Model):
player = ndb.IntegerProperty()
pickup_code = ndb.StringProperty()
pickup_id = ndb.StringProperty()
timestamp = ndb.DateTimeProperty()
removed = ndb.BooleanProperty()
coords = ndb.IntegerProperty()
map_coords = ndb.IntegerProperty()
def pickup(self):
return Pickup.n(self.pickup_code, self.pickup_id)
def equals(self, other):
return self.player == other.player and self.pickup_code == other.pickup_code and self.pickup_id == other.pickup_id and self.coords == other.coords
def print_line(self, start_time=None):
t = (self.timestamp - start_time) if start_time and self.timestamp else self.timestamp
if not self.removed:
name = "at "
if self.coords in pbc:
name += pbc[self.coords].area
elif self.coords == -1:
name = "via manual activation"
else:
log.warning("Unknown coords: %s", self.coords)
name += str(self.coords)
return "found %s %s. (%s)" % (self.pickup().name, name, t)
else:
return "lost %s! (%s)" % (self.pickup().name, t)
class User(ndb.Model):
# key = user_id
name = ndb.StringProperty()
games = ndb.KeyProperty("Game", repeated=True)
dark_theme = ndb.BooleanProperty(default=False)
email = ndb.StringProperty()
teamname = ndb.StringProperty()
pref_num = ndb.IntegerProperty()
theme = ndb.StringProperty()
verbose = ndb.BooleanProperty(default=False)
@staticmethod
def latest_game(username):
gid = Cache.get_latest_game(username)
if gid:
return gid
user = User.get_by_name(username)
if not user or not user.games:
return False
gid = int(user.games[-1].id())
Cache.set_latest_game(username, gid)
return gid
@staticmethod
def is_admin():
return users.is_current_user_admin()
@staticmethod
def login_url(redirect_after):
return users.create_login_url(redirect_after)
@staticmethod
def logout_url(redirect_after):
return users.create_logout_url(redirect_after)
@staticmethod
def prune_games():
keys = [k for k in Game.query().iter(keys_only=True)]
for user in User.query().fetch():
game_count = len(user.games)
user.games = [g for g in user.games if g in keys]
if len(user.games) < game_count:
print("removed %s games from %s's gamelist" % (game_count - len(user.games), user.name))
user.put()
@staticmethod
def get():
app_user = users.get_current_user()
if not app_user:
return None
user = User.get_by_id(app_user.user_id())
if not user:
return User.create(app_user)
if not user.email:
user.email = app_user.email()
user.put()
user = User.get_by_id(app_user.user_id())
return user
def rename(self, desired_name):
if any([forbidden in desired_name for forbidden in ["@", "/", "\\", "?", "#", "&", "="]]):
return False
if User.get_by_name(desired_name):
return False
self.name = desired_name
if self.put():
return True
return False
@staticmethod
def get_by_name(name):
return User.query().filter(User.name == name).get()
@staticmethod
def create(app_user):
user = User(id=app_user.user_id())
user.email = app_user.email()
user.name = user.email.partition("@")[0]
user.teamname = "%s's team" % user.name
key = user.put()
for old in Seed.query(Seed.author == user.name).fetch():
new = Seed(
id="%s:%s" % (key.id(), old.name),
placements=old.placements,
flags=old.flags,
hidden=old.hidden,
description=old.description,
players=old.players,
author_key=key,
name=old.name
)
new = new.put()
old.key.delete()
log.info("Seed conversion: %s -> %s", old.key, new)
return user
def plando(self, seed_name):
return Seed.get_by_id("%s:%s" % (self.key.id(), seed_name))
class CustomLogic(ndb.Model):
# id = userid
user = ndb.KeyProperty("User")
logic = ndb.PickleProperty()
warnings = ndb.TextProperty()
@staticmethod
def read():
user = User.get()
if not user:
return None, "can't store custom logic while not logged in"
cl = CustomLogic.query().filter(CustomLogic.user == user.key).fetch()
if len(cl) == 0:
return None, "no custom logic for current user"
return cl[0].logic, cl[0].warnings
@staticmethod
def write(logic, warnings):
CustomLogic(
user = User.get().key,
logic = logic,
warnings = warnings
)
class Player(ndb.Model):
# id = gid.pid
skills = ndb.IntegerProperty()
events = ndb.IntegerProperty()
bonuses = ndb.JsonProperty()
hints = ndb.JsonProperty()
teleporters = ndb.IntegerProperty()
seed = ndb.TextProperty()
signals = ndb.StringProperty(repeated=True)
history = ndb.LocalStructuredProperty(HistoryLine, repeated=True)
last_update = ndb.DateTimeProperty(auto_now=True)
teammates = ndb.KeyProperty('Player', repeated=True)
user = ndb.KeyProperty('User')
can_nag = ndb.BooleanProperty(default=True)
seen_bflds = ndb.IntegerProperty(repeated=True)
have_bflds = ndb.IntegerProperty(repeated=True)
bingo_prog = ndb.LocalStructuredProperty(BingoCardProgress, repeated=True)
def bitfield_updates(self, post_data, game_id):
if not self.seen_bflds:
self.seen_bflds=8*[0]
if not self.have_bflds:
self.have_bflds=8*[0]
put = False
seen_diff = 8 * [0]
for i in range(8):
seen = int(post_data["seen_%s" % i])
have = int(post_data["have_%s" % i])
if self.seen_bflds[i] != seen:
put = True
seen_diff[i] = seen - self.seen_bflds[i]
self.seen_bflds[i] = seen
if self.have_bflds[i] != have:
put = True
self.have_bflds[i] = have
if put:
have = Cache.get_have(game_id)
have[self.pid()] = self.have_coords()
Cache.set_have(game_id, have)
# print bfields_to_coords(seen_diff)
self.put()
def seen_coords(self):
return bfields_to_coords(self.seen_bflds) + [2]
def have_coords(self):
return bfields_to_coords(self.have_bflds) + [2]
@ndb.transactional(retries=5)
def reset(self):
self.can_nag = True
self.skills = 0
self.events = 0
self.teleporters = 0
self.bonuses = {}
self.signals = []
self.history = []
self.seen_bflds = 8 * [0]
self.have_bflds = 8 * [0]
self.bingo_prog = [BingoCardProgress(square=i) for i in range(25)]
self.put()
def sharetuple(self):
return (self.skills, self.events, self.teleporters, len(self.bonuses))
def name(self):
if self.user:
u = self.user.get()
if u and u.name:
return u.name
return "Player %s" % self.pid()
def userdata(self):
name = "Player %s" % self.pid()
ppid = self.pid()
if self.user:
u = self.user.get()
if u:
name = u.name
ppid = u.pref_num
return {'name': name, 'ppid': ppid, 'pid': self.pid()}
def teamname(self):
if self.user:
u = self.user.get()
if u:
if u.teamname:
return u.teamname
elif u.name:
return "%s's team" % u.name
return "Player %s's team" % self.pid()
def pid(self):
return _pid(self.key)
# post-refactor version of bitfields
def output(self):
outlines = [str(x) for x in [self.skills, self.events, self.teleporters]]
outlines.append(";".join([ "%sx%s" % (_id, cnt) for (_id, cnt) in self.bonuses.iteritems()]))
outlines.append(";".join(["%s:%s" % (loc, finder) for (loc, finder) in self.hints.iteritems()]))
if self.signals:
outlines.append("|".join(self.signals))
return ",".join(outlines)
def signal_send(self, signal):
if signal not in self.signals:
self.signals.append(signal)
self.put()
def signal_conf(self, signal):
if signal in self.signals:
self.signals.remove(signal)
# basically it is never ok to be spamming ppl, so if we get a message callback
# we remove the first message we find if we don't get an exact match.
elif signal.startswith("msg:"):
for s in self.signals:
self.signals.remove(s)
if s.startswith("msg:"):
log.warning("No exact match for signal %s, removing %s instead (spam protection)" % (signal, s))
break
self.put()
@staticmethod
@ndb.transactional(retries=5, xg=True)
def transaction_pickup(pkey, pickup, remove=False, delay_put=False, coords=None, finder=None):
p = pkey.get()
p.give_pickup(pickup, remove=remove, coords=coords, finder=finder)
def give_pickup(self, pickup, remove=False, delay_put=False, coords=None, finder=None):
if coords and finder:
self.hints[str(coords)] = finder
if pickup.code in ["RB", "TW"]:
# handle upgrade refactor storage
pick_id = str(pickup.id)
if remove:
if pick_id in self.bonuses:
self.bonuses[pick_id] -= 1
if self.bonuses[pick_id] == 0:
del self.bonuses[pick_id]
else:
if pick_id in self.bonuses:
if (not stacks(pickup)) or (pickup.max and self.bonuses[pick_id] >= pickup.max):
log.debug("Will not give %s pickup %s, as they already have %s" % (self.name(), pickup.name, self.bonuses[pick_id]))
self.bonuses[pick_id] = 1
return
self.bonuses[pick_id] += 1
else:
self.bonuses[pick_id] = 1
# bitfields
elif pickup.code == "SK":
self.skills = pickup.add_to_bitfield(self.skills, remove)
elif pickup.code == "TP":
self.teleporters = pickup.add_to_bitfield(self.teleporters, remove)
elif pickup.code == "EV":
self.events = pickup.add_to_bitfield(self.events, remove)
if delay_put:
return
return self.put()
def has_pickup(self, pickup):
if pickup.code in ["RB", "TW"]:
pick_id = str(pickup.id)
return self.bonuses[pick_id] if pick_id in self.bonuses else 0
elif pickup.code == "SK":
return get_bit(self.skills, pickup.bit)
elif pickup.code == "TP":
return get_bit(self.teleporters, pickup.bit)
elif pickup.code == "EV":
return get_bit(self.events, pickup.bit)
else:
return 0
class BingoTeam(ndb.Model):
captain = ndb.KeyProperty(Player)
score = ndb.IntegerProperty(default=0)
place = ndb.IntegerProperty()
blackout_place = ndb.IntegerProperty()
bingos = ndb.StringProperty(repeated=True)
teammates = ndb.KeyProperty(Player, repeated=True)
def name(self, cap=None):
cap = cap or self.captain.get()
teammates = self.teammates
return cap.teamname() if self.teammates else cap.name()
def pids(self):
return [_pid(key) for key in [self.captain] + self.teammates]
def to_json(self, players):
cap = players.get(self.captain)
if not cap:
log.error("Player %s captain of team %s but not in provided players list %s", cap, _pid(self.captain), players)
cap = self.captain.get()
res = {"cap": {'pid': cap.pid(), 'name': cap.name()}, "score": self.score, "teammates": [], "bingos": self.bingos}
if self.place:
res["place"] = self.place
res["name"] = self.name(cap = cap)
for tm in self.teammates:
if tm not in players:
log.error("Player %s part of team %s but not in provided players list %s", tm, res["name"], players)
continue
res["teammates"].append({'pid': _pid(tm), 'name': players[tm].name()})
return res
class BingoCard(ndb.Model):
name = ndb.StringProperty()
disp_name = ndb.TextProperty()
help_lines = ndb.TextProperty(repeated=True)
goal_type = ndb.StringProperty()
goal_method = ndb.StringProperty()
target = ndb.IntegerProperty()
square = ndb.IntegerProperty() # position in the single-dimension array
subgoals = ndb.JsonProperty(repeated=True)
completed_by = ndb.IntegerProperty(repeated=True)
owner = ndb.IntegerProperty(default=0)
early = ndb.BooleanProperty() # i hate this but w/e
def bingothon_json(self, player):
name = self.disp_name
prog = player.bingo_prog[self.square]
if self.goal_method == "count" or self.goal_type == "int":
name += "\n%s/%s" % (prog.count, self.target)
elif self.subgoals:
for subgoal in self.subgoals:
s = "*" if subgoal["name"] in prog.completed_subgoals else ''
n = subgoal["disp_name"] if "disp_name" in subgoal else subgoal["name"]
name += "\n%s%s%s" % (s, n, s)
return {
"name": name,
"completed": prog.completed
}
def to_json(self, players, initial=False):
res = {
"name": self.name,
"progress": {p.pid(): p.bingo_prog[self.square].to_json() for p in players},
"completed_by": self.completed_by,
"owner": self.owner
}
if initial:
res["disp_name"] = self.disp_name
res["help_lines"] = self.help_lines
if self.square or self.square == 0:
res["type"] = self.goal_type
res["square"] = self.square
if self.subgoals:
res["subgoals"] = {subgoal["name"]: subgoal for subgoal in self.subgoals}
if self.target:
res["target"] = self.target
return res
def progress(self, player):
# type: (Player) -> Optional[BingoCardProgress]
if not player or len(player.bingo_prog) < self.square:
return None
return player.bingo_prog[self.square]
def update(self, card_data, player, teammates, capkey):
# type: (dict, Player, List[Player], int) -> Optional['BingoEvent']
p_progress = self.progress(player)
prior_value = _pid(capkey) in self.completed_by
prior_count = p_progress.count
if self.goal_type == "bool":
p_progress.completed = card_data["value"]
elif self.goal_type == "int":
p_progress.count = min(int(card_data["value"]), self.target)
p_progress.completed = p_progress.count >= self.target
elif self.goal_type == "multi":
p_progress.count = min(int(card_data["total"]), self.target)
card_sgs = card_data["value"]
p_progress.completed_subgoals = [subgoal["name"] for subgoal in self.subgoals if subgoal["name"] in card_sgs and card_sgs[subgoal["name"]]["value"]]
if self.goal_method == "count":
p_progress.completed = p_progress.count >= self.target
elif self.goal_method == "and":
p_progress.completed = all([subgoal["name"] in p_progress.completed_subgoals for subgoal in self.subgoals])
elif self.goal_method == "or":
p_progress.completed = any([subgoal["name"] in p_progress.completed_subgoals for subgoal in self.subgoals])
else:
log.error("invalid method %s" % self.goal_method)
else:
log.error("invalid goal type %s" % self.goal_type)
completed = p_progress.completed
if teammates and not completed:
all_progress = [self.progress(p) for p in teammates]
if self.goal_type == "bool":
completed = any([prog.completed for prog in all_progress])
elif self.goal_type == "int":
completed = max([prog.count for prog in all_progress]) >= self.target
elif self.goal_type == "multi":
all_progress.append(p_progress)
count = max([prog.count for prog in all_progress])
team_subgoals = set([subgoal for prog in all_progress for subgoal in prog.completed_subgoals])
if self.goal_method == "count":
completed = count >= self.target
elif self.goal_method == "and":
completed = all([subgoal["name"] in team_subgoals for subgoal in self.subgoals])
elif self.goal_method == "or":
completed = any([subgoal["name"] in team_subgoals for subgoal in self.subgoals])
if prior_value != completed:
event = BingoEvent(event_type="square", loss = not completed, square=self.square, player=capkey, timestamp=datetime.utcnow())
return event
class BingoEvent(ndb.Model):
loss = ndb.BooleanProperty(default=False)
event_type = ndb.StringProperty(default="square")
square = ndb.IntegerProperty() # position in the single-dimension array
bingo = ndb.StringProperty()
timestamp = ndb.DateTimeProperty()
first = ndb.BooleanProperty()
player = ndb.KeyProperty("Player")
def to_json(self, start_time):
timeStr = ""
if start_time:
if self.timestamp < start_time:
timeStr = "-" + round_time(start_time - self.timestamp)
else:
timeStr = round_time(self.timestamp-start_time)
else:
timeStr = str(self.timestamp.time())
if self.event_type.startswith("misc"):
return {'type': self.event_type, 'time': timeStr}
res = {'loss': self.loss, 'type': self.event_type, 'time': timeStr, 'player': _pid(self.player)}
if self.event_type == 'square':
res['square'] = self.square
if self.event_type == 'bingo':
res['bingo'] = self.bingo
if self.first:
res['first'] = True
res['square'] = self.square
if self.event_type == 'owner':
res['square'] = self.square
return res
class BingoGameData(ndb.Model):
players = ndb.KeyProperty("Player", repeated=True)
board = ndb.LocalStructuredProperty(BingoCard, repeated=True)
start_time = ndb.DateTimeProperty()
started = ndb.BooleanProperty(default=True)
creator = ndb.KeyProperty("User")
teams = ndb.LocalStructuredProperty(BingoTeam, repeated=True)
event_log = ndb.LocalStructuredProperty(BingoEvent, repeated=True)
bingo_count = ndb.IntegerProperty(default=3)
current_highest = ndb.IntegerProperty(default=0)
difficulty = ndb.StringProperty()
subtitle = ndb.StringProperty()
seed = ndb.StringProperty()
teams_allowed = ndb.BooleanProperty(default=False)
square_count = ndb.IntegerProperty()
teams_shared = ndb.BooleanProperty(default=False)
game = ndb.KeyProperty("Game")
discovery = ndb.IntegerProperty()
lockout = ndb.BooleanProperty(default=False)
disc_squares = ndb.IntegerProperty(repeated=True)
rand_dat = ndb.TextProperty(compressed=True)
def discovery_squares(self, square_count=2):
if self.discovery != square_count:
self.discovery = square_count
if len(self.disc_squares) > 0:
return self.disc_squares
if square_count > 25:
square_count = 2
rand = random.Random()
rand.seed(self.seed)
noncounts = [card.square for card in self.board if card.early]
i = 0
squares = []
while i < 10:
if len(noncounts) >= square_count:
squares = rand.sample(noncounts, square_count)
else:
squares = noncounts + rand.sample(range(25), square_count - len(noncounts))
for s in squares:
if (s % 5 != 4 and s+1 in squares) or (s % 5 != 0 and s-1 in squares) or (s > 4 and s-5 in squares) or (s < 20 and s+5 in squares):
i += 1
break
else:
break
self.disc_squares = squares
self.put()
return squares
@ndb.transactional(retries=5, xg=True)
def reset(self):
self.event_log = self.event_log[0:1]
self.current_highest = 0
self.started = False
if 'start_time' in self._values:
del self._values['start_time']
for card in self.board:
card.completed_by = []
for team in self.teams:
team.bingos = []
team.score = 0
if 'place' in team._values:
del team._values['place']
if 'blackout_place' in team._values:
del team._values['blackout_place']
self.put()
@staticmethod
def with_id(id):
# type: (int) -> 'BingoGameData'
return BingoGameData.get_by_id(int(id))
def remove_player(self, pid):
player = self.player(pid, False)
if not player:
log.error("Couldn't delete player: player not found")
return False
team = self.team(pid, False)
pkeys_to_delete = [player.key]
if team.captain == player.key:
pkeys_to_delete += team.teammates
self.teams.remove(team)
else:
team.teammates.remove(player.key)
game = self.game.get()
for k in pkeys_to_delete:
game.remove_player(k.id())
self.players.remove(k)
return self.put()
def get_players(self):
# type: () -> List[Player]
return [p.get() for p in self.players]
def player_nums(self): return [_pid(k) for k in self.players]
def player(self, pid, create=False, delay_put=False):
# type: (int, bool, bool) -> Optional[Player]
gid = self.game.id()
full_pid = "%s.%s" % (gid, pid)
player = Player.get_by_id(full_pid, parent=self.game)
if not player:
if create:
player = self.game.get().player(pid)
else:
log.warning("Bingo game %s has no player %s, returning None!", gid, pid)
return None
k = player.key
if k not in self.players:
self.players.append(k)
if not delay_put:
self.put()
return player
def init_player(self, pid):
p = self.player(pid, True, True)
if p.bingo_prog:
log.warning("Player %s already had bingo card progress, won't reinit" % pid)
else:
p.bingo_prog = [BingoCardProgress(square=i) for i in range(25)]
p.put()
return p
def get_json(self, initial=False, players=[]):
players = players or self.get_players()
players_by_pkey = {p.key: p for p in players}
res = {
'cards': [c.to_json(players, initial) for c in self.board],
'events': [e.to_json(self.start_time) for e in self.event_log],
'teams': {_pid(t.captain): t.to_json(players_by_pkey) for t in self.teams},
"gameId": self.game.id()
}
if self.creator:
res["creator"] = self.creator.get().name
user = User.get()
res["is_owner"] = user and self.creator == user.key
if self.start_time:
res['countdown'] = datetime.utcnow() < self.start_time
res['start_time_posix'] = timegm(self.start_time.timetuple())
if initial:
res["difficulty"] = self.difficulty
res["bingo_count"] = self.bingo_count
res["lockout"] = self.lockout
res["subtitle"] = self.subtitle
res["teams_allowed"] = self.teams_allowed
if self.discovery or len(self.disc_squares):
res["discovery"] = self.discovery_squares()
game = self.game.get()
if game.params:
res["paramId"] = game.params.id()
if self.teams_shared:
params = game.params.get()
res["teamMax"] = params.players
return res
def get_seed(self, pid):
sync_flag = ("Sync%s.%s," % (self.key.id(), pid))
game = self.game.get()
goals = OrderedDict()
goals[""] = []
for card in self.board:
if card.subgoals:
goals[card.name] = [subgoal["name"] for subgoal in card.subgoals] + goals.get(card.name, [])
elif card.goal_method == "count":
goals[card.name] = goals.get(card.name, []) + ["COUNT"]
else:
goals[""].append(card.name + ("-%s" % card.target if card.target else ""))
goalstr = "Goals" + "/".join(["%s:%s" % (goal, ",".join(set(subgoals))) for (goal, subgoals) in goals.items()]) + "\n"
if not game.params:
return sync_flag + self.rand_dat + "\n" + goalstr
else:
params = game.params.get()
if Variation.BINGO not in params.variations:
params.variations.append(Variation.BINGO)
params = params.put().get()
if params.players == 1:
return sync_flag + params.get_seed(1, include_sync=False) + goalstr
else:
team = self.team(pid, cap_only=False)
if not team:
log.error("No team found for player %s" % pid)
return None
p_number = team.pids().index(pid) + 1
if params.players < p_number:
log.error("player %s can't get seed as there is no seed available" % pid)
return None
return sync_flag + params.get_seed(p_number, include_sync=False) + goalstr
def team(self, pid, cap_only=True):
# type: (int, bool) -> Optional[BingoTeam]
pid = int(pid)
maybe_team = [team for team in self.teams if _pid(team.captain) == pid]
if not maybe_team and not cap_only:
maybe_team += [team for team in self.teams if pid in team.pids()]
if maybe_team:
if len(maybe_team) > 1 and cap_only:
log.error("Multiple teams found with the same player %s (%s), returning %s", pid, maybe_team, maybe_team[0].captain)
res = maybe_team[0]
return res
return None
@ndb.transactional(retries=0, xg=True)
def update(self, bingo_data, player_id, game_id):
if not bingo_data:
log.error("no bingo data????")
return
player_id = int(player_id)
if not self.start_time:
return
now = datetime.utcnow()
change_squares = set()
loss_squares = set()
win_players = False
round_now = round_time(now - self.start_time)
place = ""
win_sig = "win:$Finished in %s place at %s!"
team = self.team(player_id, cap_only=False)
team.score = 0
players_by_id = {_pid(p.key): p for p in self.get_players()} # type: Dict[int, Player]
player = players_by_id[player_id]
cpid = _pid(team.captain)
teammates = [players_by_id[pid] for pid in team.pids() if pid != player_id]
need_write = False
for card in self.board: # type: BingoCard
if card.name in bingo_data:
ev = card.update(bingo_data[card.name], player, teammates, team.captain)
if ev:
need_write = True
self.event_log.append(ev)
change_squares.add(ev.square)
if ev.loss:
loss_squares.add(ev.square)
if cpid in card.completed_by:
card.completed_by.remove(cpid)
elif cpid not in card.completed_by:
card.completed_by.append(cpid)
if self.lockout:
if not ev.loss and not card.owner:
card.owner = cpid
self.event_log.append(BingoEvent(loss=False, event_type="owner", square=ev.square, player=team.captain, timestamp=datetime.utcnow()))
elif ev.loss and card.owner == cpid:
card.owner = 0
self.event_log.append(BingoEvent(loss=True, event_type="owner", square=ev.square, player=team.captain, timestamp=datetime.utcnow()))
if len(card.completed_by):
new_id = card.completed_by[0]
new_team = self.team(new_id, cap_only=False)
new_owner = new_team.captain if new_team else None # type: Optional[ModelKey]
if new_owner is None:
log.error("Card is completed by player %d without team?!", new_id)
else:
card.owner = _pid(new_owner)
self.event_log.append(BingoEvent(loss=False, event_type="owner", square=ev.square, player=new_owner, timestamp=datetime.utcnow()))
else:
log.warning("card %s was not in bingo data for team/player %s", card.name if card else card, team.captain if team else team)
if not self.lockout and cpid in card.completed_by:
team.score += 1
if self.lockout and cpid == card.owner:
team.score += 1
if self.square_count:
if team.score >= self.square_count and not team.place:
self.event_log.append(BingoEvent(event_type = "win", loss = False, player = team.captain, timestamp = now))
team.place = len([t.place for t in self.teams if t.place]) + 1
place = ord_suffix(team.place)
win_players = True
elif change_squares:
for bingo, line in lines_by_index.items():
if set(line) & change_squares:
squares = len([square for square in line if cpid in self.board[square].completed_by])
lost_squares = len(set(line) & loss_squares)
if lost_squares + squares == 5:
loss = lost_squares > 0
ev = BingoEvent(event_type = "bingo", loss = loss, bingo = bingo, player = team.captain, timestamp = now)
if loss and bingo in team.bingos:
team.bingos.remove(bingo)
elif bingo not in team.bingos:
team.bingos.append(bingo)
if(len(team.bingos) > self.current_highest):
ev.first = True
ev.square = len(team.bingos) # i hate this
self.current_highest += 1
self.event_log.append(ev)
if len(team.bingos) >= self.bingo_count and not team.place:
self.event_log.append(BingoEvent(event_type = "win", loss = False, player = team.captain, timestamp = now))
team.place = len([t.place for t in self.teams if t.place]) + 1
place = ord_suffix(team.place)
win_players = True
if team.score == 25 and not team.blackout_place:
team.blackout_place = len([1 for t in self.teams if t.blackout_place]) + 1
win_players = True
win_sig = "win:$%s to blackout at %s!"
place = ord_suffix(team.blackout_place)
need_write = True
if win_players:
p_list = [player] + teammates
for p in p_list:
p.signal_send(win_sig % (place, round_now))
Cache.set_board(game_id, self.get_json(players=players_by_id.values()))
player.put()
if need_write:
self.put()
class Seed(ndb.Model):
# Seed ids used to be author_name:name but are being migrated to author_id:name
placements = ndb.LocalStructuredProperty(Placement, repeated=True)
flags = ndb.StringProperty(repeated=True)
hidden = ndb.BooleanProperty(default=False)
description = ndb.TextProperty()
players = ndb.IntegerProperty(default=1)
author_key = ndb.KeyProperty(User)
author = ndb.StringProperty() # deprecated: will remove after migration is complete
name = ndb.StringProperty()
@staticmethod
def get(author_name, seed_name):
author = User.get_by_name(author_name)
if author:
return author.plando(seed_name)
log.warning("No user found for %s, looking for old-style seed instead...", author_name)
return Seed.get_by_id("%s:%s" % (author_name, seed_name))
def mode(self):
mode_opt = [MultiplayerGameType.mk(f[5:]) for f in self.flags if f.lower().startswith("mode=")]
return mode_opt[0] if mode_opt else None
def shared(self):
shared_opt = [f[7:].replace("+", " ").split(" ") for f in self.flags if f.lower().startswith("shared=")]
return enums_from_strlist(ShareType, shared_opt[0]) if shared_opt else []
@staticmethod
def new(data):
author = User.get()
if not author:
log.error("Error! No author found when attempting to create seed: %s", data)
return None
placements, players = Seed.get_placements(data['placements'])
s = Seed(
id="%s:%s" % (author.key.id(), data["name"]),
description = data['desc'],
flags = [f.replace(' ', '+') for f in data['flags']],
name = data['name'],
author_key = author.key,
placements = placements,
players = players,
hidden = data.get('hidden', False),
)
return s.put()
@staticmethod
def get_placements(raw_data):
players = 1
placements = []
for placement in raw_data:
plc = Placement(location=placement['loc'], zone=placement['zone'])
for stuff in placement['stuff']:
player = stuff['player']
if int(player) > players:
players = int(player)
plc.stuff.append(Stuff(code=stuff['code'], id=stuff['id'], player=player))
placements.append(plc)
return placements, players
def update(self, data):
author = self.author_key.get()
if not author:
log.error("Error! No author found when attempting to update seed %s with data %s",self, data)
return None
if self.key.id() != "%s:%s" % (author.key.id(), data["name"]):
log.info("Deleting due to rename... goodbye world")
new = Seed.new(data)
self.key.delete()
return new
else:
placements, players = Seed.get_placements(data['placements']) if 'placements' in data else (self.placements, self.players)
self.populate(