forked from mideind/Netskrafl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
skraflgame.py
1184 lines (1013 loc) · 46.3 KB
/
skraflgame.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
# -*- coding: utf-8 -*-
""" Game and User classes for Netskrafl
Author: Vilhjalmur Thorsteinsson, 2014
This module implements the User and Game classes for the
Netskrafl application. These classes form an intermediary
layer between the web server frontend in netskrafl.py and the
actual game logic in skraflplayer.py, skraflmechanics.py et al.
Note: SCRABBLE is a registered trademark. This software or its author
are in no way affiliated with or endorsed by the owners or licensees
of the SCRABBLE trademark.
"""
import collections
import threading
from random import randint
from datetime import datetime, timedelta
from google.appengine.api import users, memcache
from skraflmechanics import State, Board, Rack, Error, \
Move, PassMove, ExchangeMove, ResignMove
from skraflplayer import AutoPlayer
from languages import Alphabet, OldTileSet, NewTileSet
from skrafldb import Unique, UserModel, GameModel, MoveModel, \
FavoriteModel, ChallengeModel, StatsModel, ChatModel
class User:
""" Information about a human user including nickname and preferences """
# Use a lock to avoid potential race conditions between the memcache and the database
_lock = threading.Lock()
# User object expiration in memcache
_CACHE_EXPIRY = 15 * 60 # 15 minutes
# Current namespace (schema) for memcached User objects
_NAMESPACE = "user:2"
# Default Elo points if not explicitly assigned
DEFAULT_ELO = 1200
def __init__(self, uid = None):
""" Initialize a fresh User instance """
self._nickname = u""
self._inactive = False
self._preferences = { }
self._ready = False
self._ready_timed = False
self._elo = 0
self._human_elo = 0
self._highest_score = 0
self._highest_score_game = None
self._best_word = None
self._best_word_score = 0
self._best_word_game = None
# Set of favorite users, only loaded upon demand
self._favorites = None
# NOTE: When new properties are added, the memcache namespace version id
# (User._NAMESPACE, above) should be incremented!
if uid is None:
# Obtain information from the currently logged in user
u = users.get_current_user()
if u is None:
self._user_id = None
else:
self._user_id = u.user_id()
self._nickname = u.nickname() # Default
# Use the user's email address, if available
email = u.email()
if email:
self.set_email(email)
else:
self._user_id = uid
def _fetch(self):
""" Fetch the user's record from the database """
um = UserModel.fetch(self._user_id)
if um is None:
# Use the default properties for a newly created user
self.set_new_bag(True) # Fresh users get the new bag by default
UserModel.create(self._user_id, self.nickname(), self._preferences) # This updates the database
else:
# Obtain the properties from the database entity
self._nickname = um.nickname
self._inactive = um.inactive
self._preferences = um.prefs
self._ready = um.ready
self._ready_timed = um.ready_timed
self._elo = um.elo
self._human_elo = um.human_elo
self._highest_score = um.highest_score
self._highest_score_game = um.highest_score_game
self._best_word = um.best_word
self._best_word_score = um.best_word_score
self._best_word_game = um.best_word_game
def update(self):
""" Update the user's record in the database and in the memcache """
with User._lock:
# Use a lock to avoid the scenaro where a user is fetched by another
# request in the interval between a database update and a memcache update
um = UserModel.fetch(self._user_id)
assert um is not None
um.nickname = self._nickname
um.nick_lc = self._nickname.lower()
um.name_lc = self.full_name().lower()
um.inactive = self._inactive
um.prefs = self._preferences
um.ready = self._ready
um.ready_timed = self._ready_timed
um.elo = self._elo
um.human_elo = self._human_elo
um.highest_score = self._highest_score
um.highest_score_game = self._highest_score_game
um.best_word = self._best_word
um.best_word_score = self._best_word_score
um.best_word_game = self._best_word_game
um.put()
# Note: the namespace version should be incremented each time
# that the class properties change
memcache.set(self._user_id, self, time=User._CACHE_EXPIRY, namespace=User._NAMESPACE)
def id(self):
""" Returns the id (database key) of the user """
return self._user_id
def nickname(self):
""" Returns the human-readable nickname of a user, or userid if a nick is not available """
return self._nickname or self._user_id
def set_nickname(self, nickname):
""" Sets the human-readable nickname of a user """
self._nickname = nickname
@staticmethod
def is_valid_nick(nick):
""" Check whether a nickname is valid and displayable """
if not nick:
return False
return nick[0:8] != u"https://" and nick[0:7] != u"http://"
def human_elo(self):
""" Return the human-only Elo points of the user """
return self._human_elo or User.DEFAULT_ELO
def is_inactive(self):
""" Return True if the user is marked as inactive """
return self._inactive
def is_displayable(self):
""" Returns True if this user should appear in user lists """
if self._inactive:
# Inactive users are hidden
return False
# Nicknames that haven't been properly set aren't displayed
return User.is_valid_nick(self._nickname)
def get_pref(self, pref):
""" Retrieve a preference, or None if not found """
if self._preferences is None:
return None
return self._preferences.get(pref)
def set_pref(self, pref, value):
""" Set a preference to a value """
if self._preferences is None:
self._preferences = { }
self._preferences[pref] = value
@staticmethod
def full_name_from_prefs(prefs):
""" Returns the full name of a user from a dict of preferences """
if prefs is None:
return u""
fn = prefs.get(u"full_name")
return u"" if fn is None else fn
def full_name(self):
""" Returns the full name of a user """
fn = self.get_pref(u"full_name")
return u"" if fn is None else fn
def set_full_name(self, full_name):
""" Sets the full name of a user """
self.set_pref(u"full_name", full_name)
def email(self):
""" Returns the e-mail address of a user """
em = self.get_pref(u"email")
return u"" if em is None else em
def set_email(self, email):
""" Sets the e-mail address of a user """
self.set_pref(u"email", email)
def audio(self):
""" Returns True if the user wants audible signals """
em = self.get_pref(u"audio")
# True by default
return True if em is None else em
def set_audio(self, audio):
""" Sets the audio preference of a user to True or False """
assert isinstance(audio, bool)
self.set_pref(u"audio", audio)
def fanfare(self):
""" Returns True if the user wants a fanfare sound when winning """
em = self.get_pref(u"fanfare")
# True by default
return True if em is None else em
def set_fanfare(self, fanfare):
""" Sets the fanfare preference of a user to True or False """
assert isinstance(fanfare, bool)
self.set_pref(u"fanfare", fanfare)
def beginner(self):
""" Returns True if the user is a beginner so we show help panels, etc. """
em = self.get_pref(u"beginner")
# True by default
return True if em is None else em
def set_beginner(self, beginner):
""" Sets the beginner state of a user to True or False """
assert isinstance(beginner, bool)
self.set_pref(u"beginner", beginner)
@staticmethod
def fairplay_from_prefs(prefs):
""" Returns the fairplay preference of a user """
if prefs is None:
return False
fp = prefs.get(u"fairplay")
return False if fp is None else fp
def fairplay(self):
""" Returns True if the user has committed to a fair play statement """
em = self.get_pref(u"fairplay")
# False by default
return False if em is None else em
def set_fairplay(self, state):
""" Sets the fairplay state of a user to True or False """
assert isinstance(state, bool)
self.set_pref(u"fairplay", state)
@staticmethod
def new_bag_from_prefs(prefs):
""" Returns the new bag preference of a user """
if prefs is None:
return False
newbag = prefs.get(u"newbag")
return False if newbag is None else newbag
def new_bag(self):
""" Returns True if the user would like to play with the new bag """
newbag = self.get_pref(u"newbag")
# False by default
return False if newbag is None else newbag
def set_new_bag(self, state):
""" Sets the new bag preference of a user to True or False """
assert isinstance(state, bool)
self.set_pref(u"newbag", state)
def is_ready(self):
""" Returns True if the user is ready to accept challenges """
return self._ready
def set_ready(self, ready):
""" Sets the ready state of a user to True or False """
assert isinstance(ready, bool)
self._ready = ready
def is_ready_timed(self):
""" Returns True if the user is ready for timed games """
return self._ready_timed
def set_ready_timed(self, ready):
""" Sets the whether a user is ready for timed games """
assert isinstance(ready, bool)
self._ready_timed = ready
def _load_favorites(self):
""" Loads favorites of this user from the database into a set in memory """
if hasattr(self, "_favorites") and self._favorites:
# Already have the favorites in memory
return
self._favorites = set()
i = iter(FavoriteModel.list_favorites(self.id()))
self._favorites.update(i)
def add_favorite(self, destuser_id):
""" Add an A-favors-B relation between this user and the destuser """
self._load_favorites()
self._favorites.add(destuser_id)
FavoriteModel.add_relation(self.id(), destuser_id)
def del_favorite(self, destuser_id):
""" Delete an A-favors-B relation between this user and the destuser """
self._load_favorites()
self._favorites.discard(destuser_id)
FavoriteModel.del_relation(self.id(), destuser_id)
def has_favorite(self, destuser_id):
""" Returns True if there is an A-favors-B relation between this user and the destuser """
self._load_favorites()
return destuser_id in self._favorites
def has_challenge(self, destuser_id):
""" Returns True if this user has challenged destuser """
# !!! TODO: Cache this in the user object to save NDB reads
return ChallengeModel.has_relation(self.id(), destuser_id)
def find_challenge(self, srcuser_id):
""" Returns (found, prefs) """
return ChallengeModel.find_relation(srcuser_id, self.id())
def issue_challenge(self, destuser_id, prefs):
""" Issue a challenge to the destuser """
ChallengeModel.add_relation(self.id(), destuser_id, prefs)
def retract_challenge(self, destuser_id):
""" Retract a challenge previously issued to the destuser """
ChallengeModel.del_relation(self.id(), destuser_id)
def decline_challenge(self, srcuser_id):
""" Decline a challenge previously issued by the srcuser """
ChallengeModel.del_relation(srcuser_id, self.id())
def accept_challenge(self, srcuser_id):
""" Decline a challenge previously issued by the srcuser """
# Delete the accepted challenge and return the associated preferences
return ChallengeModel.del_relation(srcuser_id, self.id())
def adjust_highest_score(self, score, game_uuid):
""" If this is the highest score of the player, modify it """
if self._highest_score and self._highest_score >= score:
# Not a new record
return False
# New record
self._highest_score = score
self._highest_score_game = game_uuid
return True
def adjust_best_word(self, word, score, game_uuid):
""" If this is the highest scoring word of the player, modify it """
if self._best_word_score and self._best_word_score >= score:
# Not a new record
return False
# New record
self._best_word = word
self._best_word_score = score
self._best_word_game = game_uuid
return True
@staticmethod
def logout_url():
return users.create_logout_url("/")
@classmethod
def load(cls, uid):
""" Load a user from persistent storage given his/her user id """
with User._lock:
u = memcache.get(uid, namespace=User._NAMESPACE)
if u is None:
# Not found in the memcache: create a user object and
# populate it from a database entity (or initialize
# a fresh one if no entity exists).
u = cls(uid)
u._fetch()
memcache.add(uid, u, time=User._CACHE_EXPIRY, namespace=User._NAMESPACE)
return u
@classmethod
def current(cls):
""" Return the currently logged in user """
with User._lock:
user = users.get_current_user()
if user is None or user.user_id() is None:
return None
u = memcache.get(user.user_id(), namespace=User._NAMESPACE)
if u is not None:
return u
# This might be a user that is not yet in the database
u = cls()
u._fetch() # Creates a database entity if this is a fresh user
memcache.add(u.id(), u, time=User._CACHE_EXPIRY, namespace=User._NAMESPACE)
return u
@classmethod
def current_id(cls):
""" Return the id of the currently logged in user """
user = users.get_current_user()
return None if user is None else user.user_id()
@classmethod
def current_nickname(cls):
""" Return the nickname of the current user """
u = cls.current()
if u is None:
return None
return u.nickname()
def statistics(self):
""" Return a set of key statistics on the user """
reply = dict()
sm = StatsModel.newest_for_user(self.id())
reply["result"] = Error.LEGAL
reply["nickname"] = self.nickname()
reply["fullname"] = self.full_name()
sm.populate_dict(reply)
# Add statistics from the user entity
reply["highest_score"] = self._highest_score
reply["highest_score_game"] = self._highest_score_game
reply["best_word"] = self._best_word
reply["best_word_score"] = self._best_word_score
reply["best_word_game"] = self._best_word_game
return reply
# Tuple for storing move data within a Game (must be at outermost scope for pickling to work)
MoveTuple = collections.namedtuple("MoveTuple", ["player", "move", "rack", "ts"])
class Game:
""" A wrapper class for a particular game that is in process
or completed. Contains inter alia a State instance.
"""
# The available autoplayers (robots)
AUTOPLAYERS = [
(u"Fullsterkur",
u"Velur stigahæsta leik í hverri stöðu", 0),
(u"Miðlungur",
u"Velur af handahófi einn af 8 stigahæstu leikjum í hverri stöðu", 8),
(u"Amlóði",
u"Forðast sjaldgæf orð og velur úr 20 leikjum sem koma til álita", 15)
]
# The default nickname to display if a player has an unreadable nick
# (for instance a default Google nick with a https:// prefix)
UNDEFINED_NAME = u"[Ónefndur]"
# The maximum overtime in a game, after which a player automatically loses
MAX_OVERTIME = 10 * 60.0 # 10 minutes, in seconds
# After this number of days the game becomes overdue and the
# waiting player can force the tardy opponent to resign
OVERDUE_DAYS = 14
_lock = threading.Lock()
def __init__(self, uuid = None):
# Unique id of the game
self.uuid = uuid
# The start time of the game
self.timestamp = None
# The user ids of the players (None if autoplayer)
# Player 0 is the one that begins the game
self.player_ids = [None, None]
# The current game state
self.state = None
# The ability level of the autoplayer (0 = strongest)
self.robot_level = 0
# The last move made by the remote player
self.last_move = None
# The timestamp of the last move made in the game
self.ts_last_move = None
# History of moves in this game so far, as a list of MoveTuple namedtuples
self.moves = []
# Initial rack contents
self.initial_racks = [None, None]
# Preferences (such as time limit, alternative bag or board, etc.)
self._preferences = None
# Cache of game over state (becomes True when the game is definitely over)
self._game_over = None
def _make_new(self, player0_id, player1_id, robot_level = 0, prefs = None):
""" Initialize a new, fresh game """
self._preferences = prefs
# If either player0_id or player1_id is None, this is a human-vs-autoplayer game
self.player_ids = [player0_id, player1_id]
self.state = State(drawtiles = True, tileset = self.tileset)
self.initial_racks[0] = self.state.rack(0)
self.initial_racks[1] = self.state.rack(1)
self.robot_level = robot_level
self.timestamp = self.ts_last_move = datetime.utcnow()
@classmethod
def new(cls, player0_id, player1_id, robot_level = 0, prefs = None):
""" Start and initialize a new game """
game = cls(Unique.id()) # Assign a new unique id to the game
if randint(0, 1) == 1:
# Randomize which player starts the game
player0_id, player1_id = player1_id, player0_id
game._make_new(player0_id, player1_id, robot_level, prefs)
# If AutoPlayer is first to move, generate the first move
if game.player_id_to_move() is None:
game.autoplayer_move()
# Store the new game in persistent storage
game.store()
return game
@classmethod
def load(cls, uuid, use_cache = True):
""" Load an already existing game from persistent storage """
with Game._lock:
# Ensure that the game load does not introduce race conditions
return cls._load_locked(uuid, use_cache)
def store(self):
""" Store the game state in persistent storage """
# Avoid race conditions by securing the lock before storing
with Game._lock:
self._store_locked()
@classmethod
def _load_locked(cls, uuid, use_cache = True):
""" Load an existing game from cache or persistent storage under lock """
gm = GameModel.fetch(uuid, use_cache)
if gm is None:
# A game with this uuid is not found in the database: give up
return None
# Initialize a new Game instance with a pre-existing uuid
game = cls(uuid)
# Set the timestamps
game.timestamp = gm.timestamp
game.ts_last_move = gm.ts_last_move
if game.ts_last_move is None:
# If no last move timestamp, default to the start of the game
game.ts_last_move = game.timestamp
# Initialize the preferences
game._preferences = gm.prefs
# Initialize a fresh, empty state with no tiles drawn into the racks
game.state = State(drawtiles = False, tileset = game.tileset)
# A player_id of None means that the player is an autoplayer (robot)
game.player_ids[0] = None if gm.player0 is None else gm.player0.id()
game.player_ids[1] = None if gm.player1 is None else gm.player1.id()
game.robot_level = gm.robot_level
# Load the initial racks
game.initial_racks[0] = gm.irack0
game.initial_racks[1] = gm.irack1
# Load the current racks
game.state.set_rack(0, gm.rack0)
game.state.set_rack(1, gm.rack1)
# Process the moves
player = 0
# mx = 0 # Move counter for debugging/logging
for mm in gm.moves:
# mx += 1
# logging.info(u"Game move {0} tiles '{3}' score is {1}:{2}".format(mx, game.state._scores[0], game.state._scores[1], mm.tiles).encode("latin-1"))
m = None
if mm.coord:
# Normal tile move
# Decode the coordinate: A15 = horizontal, 15A = vertical
if mm.coord[0] in Board.ROWIDS:
row = Board.ROWIDS.index(mm.coord[0])
col = int(mm.coord[1:]) - 1
horiz = True
else:
row = Board.ROWIDS.index(mm.coord[-1])
col = int(mm.coord[0:-1]) - 1
horiz = False
# The tiles string may contain wildcards followed by their meaning
# Remove the ? marks to get the "plain" word formed
if mm.tiles is not None:
m = Move(mm.tiles.replace(u'?', u''), row, col, horiz)
m.make_covers(game.state.board(), mm.tiles)
elif mm.tiles[0:4] == u"EXCH":
# Exchange move
m = ExchangeMove(mm.tiles[5:])
elif mm.tiles == u"PASS":
# Pass move
m = PassMove()
elif mm.tiles == u"RSGN":
# Game resigned
m = ResignMove(- mm.score)
assert m is not None
if m:
# Do a "shallow apply" of the move, which updates
# the board and internal state variables but does
# not modify the bag or the racks
game.state.apply_move(m, True)
# Append to the move history
game.moves.append(MoveTuple(player, m, mm.rack, mm.timestamp))
player = 1 - player
# Find out what tiles are now in the bag
game.state.recalc_bag()
# Account for the final tiles in the rack and overtime, if any
if game.is_over():
game.finalize_score()
if not gm.over:
# The game was not marked as over when we loaded it from
# the datastore, but it is over now. One of the players must
# have lost on overtime. We need to update the persistent state.
game._store_locked()
return game
def _store_locked(self):
""" Store the game after having acquired the object lock """
assert self.uuid is not None
gm = GameModel(id = self.uuid)
gm.timestamp = self.timestamp
gm.ts_last_move = self.ts_last_move
gm.set_player(0, self.player_ids[0])
gm.set_player(1, self.player_ids[1])
gm.irack0 = self.initial_racks[0]
gm.irack1 = self.initial_racks[1]
gm.rack0 = self.state.rack(0)
gm.rack1 = self.state.rack(1)
gm.over = self.is_over()
sc = self.final_scores() # Includes adjustments if game is over
gm.score0 = sc[0]
gm.score1 = sc[1]
gm.to_move = len(self.moves) % 2
gm.robot_level = self.robot_level
gm.prefs = self._preferences
tile_count = 0
movelist = []
best_word = [None, None]
best_word_score = [0, 0]
player = 0
for m in self.moves:
mm = MoveModel()
coord, tiles, score = m.move.summary(self.state)
if coord:
# Regular move: count the tiles actually laid down
tile_count += m.move.num_covers()
# Keep track of best words laid down by each player
if score > best_word_score[player]:
best_word_score[player] = score
best_word[player] = tiles
mm.coord = coord
mm.tiles = tiles
mm.score = score
mm.rack = m.rack
mm.timestamp = m.ts
movelist.append(mm)
player = 1 - player
gm.moves = movelist
gm.tile_count = tile_count
# Update the database entity
gm.put()
# Storing a game that is now over: update the player statistics as well
if self.is_over():
pid_0 = self.player_ids[0]
pid_1 = self.player_ids[1]
u0 = User.load(pid_0) if pid_0 else None
u1 = User.load(pid_1) if pid_1 else None
if u0:
mod_0 = u0.adjust_highest_score(sc[0], self.uuid)
mod_0 |= u0.adjust_best_word(best_word[0], best_word_score[0], self.uuid)
if mod_0:
# Modified: store the updated user entity
u0.update()
if u1:
mod_1 = u1.adjust_highest_score(sc[1], self.uuid)
mod_1 |= u1.adjust_best_word(best_word[1], best_word_score[1], self.uuid)
if mod_1:
# Modified: store the updated user entity
u1.update()
def id(self):
""" Returns the unique id of this game """
return self.uuid
@staticmethod
def autoplayer_name(level):
""" Return the autoplayer name for a given level """
i = len(Game.AUTOPLAYERS)
while i > 0:
i -= 1
if level >= Game.AUTOPLAYERS[i][2]:
return Game.AUTOPLAYERS[i][0]
return Game.AUTOPLAYERS[0][0] # Strongest player by default
def player_nickname(self, index):
""" Returns the nickname of a player """
u = None if self.player_ids[index] is None else User.load(self.player_ids[index])
if u is None:
# This is an autoplayer
nick = Game.autoplayer_name(self.robot_level)
else:
# This is a human user
nick = u.nickname()
if nick[0:8] == u"https://":
# Raw name (path) from Google Accounts: use a more readable version
nick = Game.UNDEFINED_NAME
return nick
def get_pref(self, pref):
""" Retrieve a preference, or None if not found """
if self._preferences is None:
return None
return self._preferences.get(pref, None)
def set_pref(self, pref, value):
""" Set a preference to a value """
if self._preferences is None:
self._preferences = { }
self._preferences[pref] = value
@staticmethod
def fairplay_from_prefs(prefs):
""" Returns the fairplay commitment specified by the given game preferences """
return prefs is not None and prefs.get(u"fairplay", False)
def get_fairplay(self):
""" True if this was originated as a fairplay game """
return self.get_pref(u"fairplay") or False
def set_fairplay(self, state):
""" Set the fairplay commitment of this game """
self.set_pref(u"fairplay", state)
def new_bag(self):
""" True if this game uses the new bag """
return self.get_pref(u"newbag") or False
def set_new_bag(self, state):
""" Configures the game as using the new bag """
self.set_pref(u"newbag", state)
@staticmethod
def new_bag_from_prefs(prefs):
""" Returns true if the game preferences specify a new bag """
return prefs is not None and prefs.get(u"newbag", False)
@staticmethod
def tileset_from_prefs(prefs):
""" Returns the tileset specified by the given game preferences """
new_bag = Game.new_bag_from_prefs(prefs)
return NewTileSet if new_bag else OldTileSet
@property
def tileset(self):
""" Return the tile set used in this game """
return NewTileSet if self.new_bag() else OldTileSet
@staticmethod
def get_duration_from_prefs(prefs):
""" Return the duration given a dict of game preferences """
return 0 if prefs is None else prefs.get(u"duration", 0)
def get_duration(self):
""" Return the duration for each player in the game, e.g. 25 if 2x25 minute game """
return self.get_pref(u"duration") or 0
def set_duration(self, duration):
""" Set the duration for each player in the game, e.g. 25 if 2x25 minute game """
self.set_pref(u"duration", duration)
def is_overdue(self):
""" Return True if no move has been made in the game for OVERDUE_DAYS days """
ts_last_move = self.ts_last_move or self.timestamp
delta = datetime.utcnow() - ts_last_move
return delta >= timedelta(days = Game.OVERDUE_DAYS)
def get_elapsed(self):
""" Return the elapsed time for both players, in seconds, as a tuple """
elapsed = [0.0, 0.0]
last_ts = self.timestamp
for m in self.moves:
if m.ts is not None:
delta = m.ts - last_ts
last_ts = m.ts
elapsed[m.player] += delta.total_seconds()
if not self.state.is_game_over():
# Game still going on: Add the time from the last move until now
delta = datetime.utcnow() - last_ts
elapsed[self.player_to_move()] += delta.total_seconds()
return tuple(elapsed)
def time_info(self):
""" Returns a dict with timing information about this game """
return dict(duration = self.get_duration(), elapsed = self.get_elapsed())
def overtime(self):
""" Return overtime for both players, in seconds """
overtime = [0, 0]
duration = self.get_duration() * 60.0 # In seconds
if duration > 0.0:
# Timed game: calculate the overtime
el = self.get_elapsed()
for player in range(2):
overtime[player] = max(0.0, el[player] - duration) # Never negative
return tuple(overtime)
def overtime_adjustment(self):
""" Return score adjustments due to overtime, as a tuple with two deltas """
overtime = self.overtime()
adjustment = [0, 0]
for player in range(2):
if overtime[player] > 0.0:
# 10 point subtraction for every started minute
# The formula means that 0.1 second into a new minute
# a 10-point loss is incurred
# After 10 minutes, the game is lost and the adjustment maxes out at -100
adjustment[player] = max(-100, -10 * ((int(overtime[player] + 0.9) + 59) // 60))
return tuple(adjustment)
def is_over(self):
""" Return True if the game is over """
if self._game_over:
# Use the cached result if available and True
return True
if self.state.is_game_over():
self._game_over = True
return True
if self.get_duration() == 0:
# Not a timed game: it's not over
return False
# Timed game: might now be lost on overtime
overtime = self.overtime()
if any(overtime[ix] >= Game.MAX_OVERTIME for ix in range(2)):
# The game has been lost on overtime
self._game_over = True
return True
return False
def winning_player(self):
""" Returns index of winning player, or -1 if game is tied or not over """
if not self.is_over():
return -1
sc = self.final_scores()
if sc[0] > sc[1]:
return 0
if sc[1] > sc[0]:
return 1
return -1
def finalize_score(self):
""" Adjust the score at the end of the game, accounting for left tiles, overtime, etc. """
assert self.is_over()
# Final adjustments to score, including rack leave and overtime, if any
overtime = self.overtime()
# Check whether a player lost on overtime
lost_on_overtime = None
for player in range(2):
if overtime[player] >= Game.MAX_OVERTIME:
lost_on_overtime = player
break
self.state.finalize_score(lost_on_overtime, self.overtime_adjustment())
def final_scores(self):
""" Return the final score of the game after adjustments, if any """
return self.state.final_scores()
def allows_best_moves(self):
""" Returns True if this game supports full review (has stored racks, etc.) """
if self.initial_racks[0] is None or self.initial_racks[1] is None:
# This is an old game stored without rack information: can't display best moves
return False
# Never show best moves for games that are still being played
return self.is_over()
def register_move(self, move):
""" Register a new move, updating the score and appending to the move list """
player_index = self.player_to_move()
self.state.apply_move(move)
self.ts_last_move = datetime.utcnow()
self.moves.append(MoveTuple(player_index, move,
self.state.rack(player_index), self.ts_last_move))
self.last_move = None # No response move yet
def autoplayer_move(self):
""" Generate an AutoPlayer move and register it """
# Create an appropriate AutoPlayer subclass instance
# depending on the robot level in question
apl = AutoPlayer.create(self.state, self.robot_level)
move = apl.generate_move()
self.register_move(move)
self.last_move = move # Store a response move
def enum_tiles(self, state = None):
""" Enumerate all tiles on the board in a convenient form """
if state is None:
state = self.state
for x, y, tile, letter in state.board().enum_tiles():
yield (Board.ROWIDS[x] + str(y + 1), tile, letter, self.tileset.scores[tile])
def state_after_move(self, move_number):
""" Return a game state after the indicated move, 0=beginning state """
# Initialize a fresh state object
s = State(drawtiles = False, tileset = self.tileset)
# Set up the initial state
for ix in range(2):
s.set_player_name(ix, self.state.player_name(ix))
if self.initial_racks[ix] is None:
# Load the current rack rather than nothing
s.set_rack(ix, self.state.rack(ix))
else:
# Load the initial rack
s.set_rack(ix, self.initial_racks[ix])
# Apply the moves up to the state point
for m in self.moves[0 : move_number]:
s.apply_move(m.move, shallow = True) # Shallow apply
if m.rack is not None:
s.set_rack(m.player, m.rack)
s.recalc_bag()
return s
def display_bag(self, player_index):
""" Returns the bag as it should be displayed to the indicated player,
including the opponent's rack and sorted """
return self.state.display_bag(player_index)
def num_moves(self):
""" Returns the number of moves in the game so far """
return len(self.moves)
def player_to_move(self):
""" Returns the index (0 or 1) of the player whose move it is """
return self.state.player_to_move()
def player_id_to_move(self):
""" Return the userid of the player whose turn it is, or None if autoplayer """
return self.player_ids[self.player_to_move()]
def player_id(self, player_index):
""" Return the userid of the indicated player """
return self.player_ids[player_index]
def my_turn(self, user_id):
""" Return True if it is the indicated player's turn to move """
if self.is_over():
return False
return self.player_id_to_move() == user_id
def is_autoplayer(self, player_index):
""" Return True if the player in question is an autoplayer """
return self.player_ids[player_index] is None
def is_robot_game(self):
""" Return True if one of the players is an autoplayer """
return self.is_autoplayer(0) or self.is_autoplayer(1)
def player_index(self, user_id):
""" Return the player index (0 or 1) of the given user, or None if not a player """
if self.player_ids[0] == user_id:
return 0
if self.player_ids[1] == user_id:
return 1
return None
def has_player(self, user_id):
""" Return True if the indicated user is a player of this game """
return self.player_index(user_id) is not None
def start_time(self):
""" Returns the timestamp of the game in a readable format """
return u"" if self.timestamp is None else Alphabet.format_timestamp(self.timestamp)
def end_time(self):
""" Returns the time of the last move in a readable format """
return u"" if self.ts_last_move is None else Alphabet.format_timestamp(self.ts_last_move)
def has_new_chat_msg(self, user_id):
""" Return True if there is a new chat message that the given user hasn't seen """
p = self.player_index(user_id)