forked from davepeck/game-of-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
go.py
2233 lines (1794 loc) · 81.6 KB
/
go.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
# (c) 2009 Dave Peck, All Rights Reserved. (http://davepeck.org/)
# This file is part of Dave Peck's Go.
# Dave Peck's Go is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# Dave Peck's Go is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU Affero General Public License
# along with Dave Peck's Go. If not, see <http://www.gnu.org/licenses/>.
#------
# This file is the appengine back-end to the Go application.
#------
import cgi
import os
import sys
import logging
import copy
import pickle
import random
import string
import traceback
from datetime import datetime, timedelta, date
import simplejson
import wsgiref.handlers
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext import db
from google.appengine.api import memcache
from google.appengine.api import mail
import urllib
import urllib2
import base64
import secrets
#------------------------------------------------------------------------------
# Constants
#------------------------------------------------------------------------------
class CONST(object):
No_Color = 0
Black_Color = 1
White_Color = 2
Both_Colors = 3
Color_Names = ['none', 'black', 'white', 'both']
Star_Ordinals = [[3, 9, 15], [3, 6, 9], [2, 4, 6]]
Board_Sizes = [(19, 19), (13, 13), (9, 9)]
Board_Classes = ['nineteen_board', 'thirteen_board', 'nine_board']
Board_Size_Names = ['19 x 19', '13 x 13', '9 x 9']
Handicaps = [0, 9, 8, 7, 6, 5, 4, 3, 2]
Handicap_Names = ['plays first', 'has a nine stone handicap', 'has an eight stone handicap', 'has a seven stone handicap', 'has a six stone handicap', 'has a five stone handicap', 'has a four stone handicap', 'has a three stone handicap', 'has a two stone handicap']
Handicap_Positions = [
[(15, 3), (3, 15), (15, 15), (3, 3), (9, 9), (3, 9), (15, 9), (9, 3), (9, 15)],
[(9, 3), (3, 9), (9, 9), (3, 3), (6, 6), (3, 6), (9, 6), (6, 3), (6, 9)],
[(6, 2), (2, 6), (6, 6), (2, 2), (4, 4)]]
Email_Contact = "email"
Twitter_Contact = "twitter"
No_Contact = "none"
Default_Email = "nobody@example.com"
# "I" is purposfully skipped because, historically, people got confused between "I" and "J"
Column_Names = ["A", "B", "C", "D", "E", "F", "G", "H", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T"]
def opposite_color(color):
return 3 - color
def pos_to_coord(pos):
"""Convert a position into letter coordinates, for SGF"""
x, y = pos
return "%s%s" % (string.letters[x], string.letters[y])
#------------------------------------------------------------------------------
# Exception Handling & AppEngine Helpers
#------------------------------------------------------------------------------
class ExceptionHelper:
@staticmethod
def _typename(t):
"""helper function -- isolates the type name from the type string"""
if t:
return str(t).split("'")[1]
else:
return "{type: None}"
@staticmethod
def _typeof(thing):
"""Get the type name, such as str, float, or int"""
return ExceptionHelper._typename(type(thing))
@staticmethod
def exception_string():
"""called to extract useful information from an exception"""
exc = sys.exc_info()
exc_type = ExceptionHelper._typename(exc[0])
exc_message = str(exc[1])
exc_contents = "".join(traceback.format_exception(*sys.exc_info()))
return "[%s]\n %s" % (exc_type, exc_contents)
class AppEngineHelper:
@staticmethod
def is_production():
server_software = os.environ["SERVER_SOFTWARE"]
if not server_software:
return True
return "development" not in server_software.lower()
@staticmethod
def base_url():
if AppEngineHelper.is_production():
return "http://go.davepeck.org/"
else:
return "http://localhost:8080/"
#------------------------------------------------------------------------------
# Game State
#------------------------------------------------------------------------------
class GameBoard(object):
def __init__(self, board_size_index = 0, handicap_index = 0):
super(GameBoard, self).__init__()
self.width = CONST.Board_Sizes[board_size_index][0]
self.height = CONST.Board_Sizes[board_size_index][1]
self.size_index = board_size_index
self.handicap_index = handicap_index
self._make_board()
self._apply_handicap()
def _make_board(self):
self.board = []
for x in range(self.width):
self.board.append( [CONST.No_Color] * self.height )
def _apply_handicap(self):
stones_handicap = CONST.Handicaps[self.handicap_index]
positions_handicap = CONST.Handicap_Positions[self.size_index]
for i in range(stones_handicap):
self.set(positions_handicap[i][0], positions_handicap[i][1], CONST.Black_Color)
def get(self, x, y):
return self.board[x][y]
def set(self, x, y, color):
self.board[x][y] = color
def get_width(self):
return self.width
def get_height(self):
return self.height
def get_size_index(self):
return self.size_index
def get_column_names(self):
return CONST.Column_Names[:self.width]
def get_row_names(self):
row_names = []
for i in range(self.height, 0, -1):
row_names.append(str(i))
return row_names
def get_komi(self):
if self.handicap_index:
return 0.5
else:
return 6.5
def get_handicap(self):
return CONST.Handicaps[self.handicap_index]
def get_state_string(self):
# Used for passing the board state via javascript. Smallish.
bs = ""
for y in range(self.height):
for x in range(self.width):
piece = self.get(x, y)
if piece == CONST.Black_Color:
bs += "b"
elif piece == CONST.White_Color:
bs += "w"
else:
bs += "."
return bs
def is_in_bounds(self, x, y):
return (x >= 0) and (x < self.get_width()) and (y >= 0) and (y < self.get_height())
def is_stone_in_suicide(self, x, y):
liberties = LibertyFinder(self, x, y)
return liberties.get_liberty_count() == 0
def _compute_liberties_at(self, x, y, other):
# returns number of liberties and connected stones
if not self.is_in_bounds(x, y):
return (0, [])
if self.get(x, y) != other:
return (0, [])
finder = LibertyFinder(self, x, y)
return (finder.get_liberty_count(), finder.get_connected_stones())
def compute_atari_and_captures(self, x, y):
color = self.get(x, y)
other = opposite_color(color)
liberties = []
liberties.append(self._compute_liberties_at(x-1, y, other))
liberties.append(self._compute_liberties_at(x, y-1, other))
liberties.append(self._compute_liberties_at(x+1, y, other))
liberties.append(self._compute_liberties_at(x, y+1, other))
ataris = 0
captures = []
# determine ataris and first pass on captured
# (there may be duplicate captured stones at first)
for count, connected in liberties:
if count == 1:
ataris += 1
if count == 0:
captures.append(connected)
# remove duplicate captures
nodup_captures = []
for capture in captures:
if capture not in nodup_captures:
nodup_captures.append(capture)
# flatten all captured stones into one batch
final_captures = []
for capture in nodup_captures:
for x, y in capture:
final_captures.append((x, y))
return (ataris, final_captures)
def get_class(self):
return CONST.Board_Classes[self.size_index]
def clone(self):
return copy.deepcopy(self)
class GameState(object):
def __init__(self):
super(GameState, self).__init__()
self.board = None
self.white_stones_captured = 0
self.black_stones_captured = 0
self.whose_move = CONST.No_Color
self.last_move_message = "It's your turn to move; this is the first move of the game."
self.current_move_number = 0
self.last_move = (-1, -1)
self.last_move_was_pass = False
def get_board(self):
return self.board
def set_board(self, board):
self.board = board
def get_whose_move(self):
return self.whose_move
def set_whose_move(self, whose_move):
self.whose_move = whose_move
def get_white_stones_captured(self):
return self.white_stones_captured
def set_white_stones_captured(self, wsc):
self.white_stones_captured = wsc
def get_black_stones_captured(self):
return self.black_stones_captured
def set_black_stones_captured(self, bsc):
self.black_stones_captured = bsc
def get_last_move_message(self):
return self.last_move_message
def set_last_move_message(self, message):
self.last_move_message = message
def get_current_move_number(self):
return self.current_move_number
def set_current_move_number(self, number):
self.current_move_number = number
def increment_current_move_number(self, by = 1):
self.current_move_number += by
def get_last_move(self):
return self.last_move
def set_last_move(self, x, y):
self.last_move = (x, y)
def get_last_move_was_pass(self):
return self.last_move_was_pass
def set_last_move_was_pass(self, was_pass):
self.last_move_was_pass = was_pass
def clone(self):
clone = GameState()
clone.white_stones_captured = self.white_stones_captured
clone.black_stones_captured = self.black_stones_captured
clone.whose_move = self.whose_move
clone.last_move_message = self.last_move_message
clone.current_move_number = self.current_move_number
clone.board = self.board.clone()
clone.last_move = self.last_move
clone.last_move_was_pass = self.last_move_was_pass
return clone
class ChatEntry(object):
def __init__(self, cookie, message, current_move_number):
super(ChatEntry, self).__init__()
self.cookie = cookie
self.message = message
self.move_number = current_move_number
def get_cookie(self):
return self.cookie
def get_message(self):
return self.message
def get_move_number(self):
return self.move_number
def get_player(self):
return ModelCache.player_by_cookie(self.cookie)
def get_player_friendly_name(self):
return self.get_player().get_friendly_name()
def get_player_email(self):
return self.get_player().email
#------------------------------------------------------------------------------
# LibertyFinder: given a stone, find all connected stones and count liberties
#------------------------------------------------------------------------------
class LibertyFinder(object):
def __init__(self, board, start_x, start_y):
super(LibertyFinder, self).__init__()
self.board = board
self.start_x = start_x
self.start_y = start_y
self.color = self.board.get(self.start_x, self.start_y)
self.connected_stones = []
self.liberty_count = -1
self._make_found()
self._find_connected_stones()
self._count_liberties()
def _make_found(self):
w = self.board.get_width()
h = self.board.get_height()
self.reached = []
for x in range(w):
self.reached.append([False] * h)
def _find_connected_stones(self):
q = [(self.start_x, self.start_y)]
# Flood-fill on the color
while len(q) > 0:
# dequeue
x, y = q[0]
q = q[1:]
self.reached[x][y] = True
self.connected_stones.append((x, y))
# left
if (x-1) >= 0:
left = self.board.get(x-1, y)
if left == self.color and not self.reached[x-1][y]:
q.append((x-1, y))
# top
if (y-1) >= 0:
top = self.board.get(x, y-1)
if top == self.color and not self.reached[x][y-1]:
q.append((x, y-1))
# right
if (x+1) < self.board.get_width():
right = self.board.get(x+1, y)
if right == self.color and not self.reached[x+1][y]:
q.append((x+1, y))
# bottom
if (y+1) < self.board.get_height():
bottom = self.board.get(x, y+1)
if bottom == self.color and not self.reached[x][y+1]:
q.append((x, y+1))
# force a canoncial order for connected stones
# so that we can determine if two sets of
# connected stones are the same
self.connected_stones.sort()
def _get_liberty_count_at(self, x, y, w, h, already_counted):
libs = 0
# left liberty?
if (x-1) >= 0:
left = self.board.get(x-1, y)
if left == CONST.No_Color and not already_counted[x-1][y]:
libs += 1
already_counted[x-1][y] = True
# top liberty?
if (y-1) >= 0:
top = self.board.get(x, y-1)
if top == CONST.No_Color and not already_counted[x][y-1]:
libs += 1
already_counted[x][y-1] = True
# right liberty?
if (x+1) < w:
right = self.board.get(x+1, y)
if right == CONST.No_Color and not already_counted[x+1][y]:
libs += 1
already_counted[x+1][y] = True
# bottom liberty?
if (y+1) < h:
bottom = self.board.get(x, y+1)
if bottom == CONST.No_Color and not already_counted[x][y+1]:
libs += 1
already_counted[x][y+1] = True
return libs
def _count_liberties(self):
w = self.board.get_width()
h = self.board.get_height()
already_counted = []
for x in range(w):
already_counted.append([False] * h)
self.liberty_count = 0
for connected_stone in self.connected_stones:
x, y = connected_stone
self.liberty_count += self._get_liberty_count_at(x, y, w, h, already_counted)
def get_liberty_count(self):
return self.liberty_count
def get_connected_stones(self):
return self.connected_stones
#------------------------------------------------------------------------------
# Game Cookies: How to get back to the game
#------------------------------------------------------------------------------
class GameCookie(object):
@staticmethod
def _base_n(num, base):
# Works for 2 <= n <= 62
return ((num == 0) and "0") or (GameCookie._base_n(num // base, base).lstrip("0") + "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"[num % base])
@staticmethod
def _base_62(num):
# A nice base to use -- over fifty billion values in just six characters. The power!
return GameCookie._base_n(num, 62)
@staticmethod
def random_cookie():
# Random, but not necessarily unique
return GameCookie._base_62(random.randint(1, 50000000000))
@staticmethod
def unique_pair():
# Return two guaranteed-unique (and non-identical) cookies
unique = False
while not unique:
one = GameCookie.random_cookie()
two = GameCookie.random_cookie()
while one == two:
two = GameCookie.random_cookie()
test_one = Player.all().filter('cookie =', one).get()
test_two = Player.all().filter('cookie =', two).get()
unique = (test_one is None) and (test_two is None)
return (one, two)
#------------------------------------------------------------------------------
# Code to help with sending out emails.
#------------------------------------------------------------------------------
class EmailHelper(object):
No_Reply_Address = "Dave Peck's Go <no-reply@davepeck.org>"
@staticmethod
def _rfc_address(name, email):
return "%s <%s>" % (name, email)
@staticmethod
def _game_url(cookie):
return "%splay/%s/" % (AppEngineHelper.base_url(), cookie)
@staticmethod
def notify_you_new_game(your_name, your_email, your_cookie, opponent_name, your_turn):
your_address = EmailHelper._rfc_address(your_name, your_email)
your_message = mail.EmailMessage()
your_message.sender = EmailHelper.No_Reply_Address
your_message.subject = "[GO] You've started a game with %s" % opponent_name
your_message.to = your_address
your_message.body = """
Hi %s,
You've started a game of Go with %s. You can see what's happening by visiting:
%s
""" % (your_name, opponent_name, EmailHelper._game_url(your_cookie))
if your_turn:
your_message.body += "Also, it's your turn to move first!"
else:
your_message.body += "Your opponent plays first; you'll get an email when it's your turn to move."
# SEND your message!
your_message.send()
@staticmethod
def notify_opponent_new_game(your_name, opponent_name, opponent_email, opponent_cookie, your_turn):
opponent_address = EmailHelper._rfc_address(opponent_name, opponent_email)
opponent_message = mail.EmailMessage()
opponent_message.sender = EmailHelper.No_Reply_Address
opponent_message.subject = "[GO] %s has invited you to play!" % your_name
opponent_message.to = opponent_address
opponent_message.body = """
Hi %s,
%s started a game of Go with you. You can see what's happening by visiting:
%s
""" % (opponent_name, your_name, EmailHelper._game_url(opponent_cookie))
if your_turn:
opponent_message.body += "You'll get another email when it's your turn."
else:
opponent_message.body += "It's your turn to move, so get going!"
# SEND opponent message!
opponent_message.send()
@staticmethod
def notify_your_turn(your_name, your_email, your_cookie, opponent_name, opponent_email, move_message, move_number):
your_address = EmailHelper._rfc_address(your_name, your_email)
opponent_address = EmailHelper._rfc_address(opponent_name, opponent_email)
message = mail.EmailMessage()
message.sender = EmailHelper.No_Reply_Address
message.subject = "[GO - Move #%s] It's your turn against %s" % (str(move_number), opponent_name)
message.to = your_address
if move_message == "It's your turn to move.":
# TODO UNHACK -- ugly, but I'm too lazy to do this well at the moment.
email_body = "It's your turn to make a move against %s." % opponent_name
else:
email_body = move_message
email_body += " Just follow this link:\n\n%s\n" % EmailHelper._game_url(your_cookie)
message.body = email_body
message.send()
#------------------------------------------------------------------------------
# Twitter Support
#------------------------------------------------------------------------------
class TwitterHelper(object):
@staticmethod
def _open_basic_auth_url(username, password, url, params):
# The "right" way to do this with urllib2 sucks. Why bother?
data = None
if params is not None:
data = urllib.urlencode(params)
req = urllib2.Request(url, data)
base64string = base64.encodestring('%s:%s' % (username, password))[:-1]
authheader = "Basic %s" % base64string
req.add_header("Authorization", authheader)
try:
handle = urllib2.urlopen(req)
except:
logging.warn("Failed to make twitter request: %s" % ExceptionHelper.exception_string())
return None
return handle
@staticmethod
def _make_twitter_call_as(url, params, user, user_password):
handle = TwitterHelper._open_basic_auth_url(user, user_password, url, params)
if handle is None:
return None
try:
result = simplejson.loads(handle.read())
except:
logging.warn("Couldn't process json result from twitter: %s" % ExceptionHelper.exception_string())
return None
return result
@staticmethod
def _make_twitter_call(url, params):
return TwitterHelper._make_twitter_call_as(url, params, secrets.twitter_user, secrets.twitter_pass)
@staticmethod
def _make_boolean_twitter_call(url, params):
result = TwitterHelper._make_twitter_call(url, params)
if result is None:
return None
if type(result) != type(True):
return None
return result
@staticmethod
def _make_success_twitter_call(url, params):
result = TwitterHelper._make_twitter_call(url, params)
if result is None:
return None
return not ('error' in result)
@staticmethod
def _make_success_twitter_call_as(url, params, user, user_password):
result = TwitterHelper._make_twitter_call_as(url, params, user, user_password)
if result is None:
return None
return not ('error' in result)
@staticmethod
def _game_url(cookie):
return "%splay/%s/" % (AppEngineHelper.base_url(), cookie)
@staticmethod
def _trim_name(name):
return name.strip()[:16]
@staticmethod
def does_follow(a, b):
# Does "a" follow "b"?
return TwitterHelper._make_boolean_twitter_call("http://twitter.com/friendships/exists.json", {"user_a": a, "user_b": b})
@staticmethod
def are_mutual_followers(a, b):
a_b = TwitterHelper.does_follow(a, b)
if a_b is None:
return None
if not a_b:
return False
b_a = TwitterHelper.does_follow(b, a)
if b_a is None:
return None
return b_a
@staticmethod
def create_follow(a, b, a_password):
# {"ignore": "this"} forces a POST
return TwitterHelper._make_success_twitter_call_as("http://twitter.com/friendships/create/%s.json?follow=true" % b, {"ignore": "this"}, a, a_password)
@staticmethod
def does_go_account_follow_user(user):
return TwitterHelper.does_follow(secrets.twitter_user, user)
@staticmethod
def does_user_follow_go_account(user):
return TwitterHelper.does_follow(user, secrets.twitter_user)
@staticmethod
def make_go_account_follow_user(user):
did = TwitterHelper.create_follow(secrets.twitter_user, user, secrets.twitter_pass)
if did is None:
return False
return did
@staticmethod
def make_user_follow_go_account(user, user_password):
did = TwitterHelper.create_follow(user, secrets.twitter_user, user_password)
if did is None:
return False
return did
@staticmethod
def send_direct_message(a, b, a_password, message):
success = TwitterHelper._open_basic_auth_url(a, a_password, "http://twitter.com/direct_messages/new.json", {"user": b, "text": message})
return (success is not None)
@staticmethod
def send_notification_to_user(user, message):
return TwitterHelper.send_direct_message(secrets.twitter_user, user, secrets.twitter_pass, message)
@staticmethod
def notify_you_new_game(your_name, your_twitter, your_cookie, opponent_name, your_turn):
if your_turn:
message = "You've started a game of Go with %s. It is your turn. You can play by visiting %s" % (TwitterHelper._trim_name(opponent_name), TwitterHelper._game_url(your_cookie))
else:
message = "You've started a game of Go with %s. You can see what's happening by visiting %s" % (TwitterHelper._trim_name(opponent_name), TwitterHelper._game_url(your_cookie))
return TwitterHelper.send_notification_to_user(your_twitter, message)
@staticmethod
def notify_opponent_new_game(your_name, opponent_name, opponent_twitter, opponent_cookie, your_turn):
if your_turn:
message = "%s has started a game of Go with you. You can see what's happening by visiting %s" % (TwitterHelper._trim_name(your_name), TwitterHelper._game_url(opponent_cookie))
else:
message = "%s has started a game of Go with you. It's your turn. You can play by visiting %s" % (TwitterHelper._trim_name(your_name), TwitterHelper._game_url(opponent_cookie))
return TwitterHelper.send_notification_to_user(opponent_twitter, message)
@staticmethod
def notify_your_turn(your_name, your_twitter, your_cookie, opponent_name, move_message):
if move_message == "It's your turn to move.":
# TODO UNHACK -- ugly, but I'm too lazy to do this well at the moment.
message = "%s moved; it's now your turn." % TwitterHelper._trim_name(opponent_name)
else:
message = move_message
message += " " + TwitterHelper._game_url(your_cookie)
return TwitterHelper.send_notification_to_user(your_twitter, message)
#------------------------------------------------------------------------------
# Models
#------------------------------------------------------------------------------
class ModelCache(object):
@staticmethod
def player_by_cookie(cookie):
player = memcache.get(cookie)
if player is not None:
return player
else:
player = Player.all().filter("cookie = ", cookie).get()
if player is not None:
memcache.set(cookie, player)
return player
@staticmethod
def clear_cookie(cookie):
memcache.delete(cookie)
class Game(db.Model):
date_created = db.DateTimeProperty(auto_now = True)
date_last_moved = db.DateTimeProperty(auto_now = True)
history = db.ListProperty(db.Blob)
current_state = db.BlobProperty()
# Back reference the players
black_cookie = db.StringProperty()
white_cookie = db.StringProperty()
# Recent chat
chat_history = db.ListProperty(db.Blob)
is_finished = db.BooleanProperty(default=False)
def get_black_player(self):
return ModelCache.player_by_cookie(self.black_cookie)
def get_white_player(self):
return ModelCache.player_by_cookie(self.white_cookie)
def get_black_friendly_name(self):
return self.get_black_player().get_friendly_name()
def get_white_friendly_name(self):
return self.get_white_player().get_friendly_name()
def get_current_move_number(self):
# 1.0 shipped with a bug that caused the zeroth state to
# have current_move_number set to 1. That sorta sucks for history
# and this little code fixes it. I probably would have ignored the issue
# but there are over 100 games running on the production site at the moment.
if self.history is None:
return 0
return len(self.history)
# 1.0 shipped without chat, so some games may not have this.
# hence this helper routine.
def get_chat_history_blobs(self):
# We shipped without chat, so some games may not have this
blob_history = None
try:
blob_history = self.chat_history
except:
blob_history = None
if blob_history is None:
self.chat_history = []
self.put()
blob_history = []
return blob_history
# Because there is no notion of 'account', players are created
# anew each time a game is constructed.
# NOTE:
# All of the contact and "email vs. twitter" stuff is a little
# rough around the edges. That's because go.davepeck.org launched without
# twitter, and I've got to make sure old player objects continue to behave
# well. I decided to use a less-than-ideal representation so that I didn't
# have to go back and fix all the old player objects.
class Player(db.Model):
game = db.ReferenceProperty(Game)
cookie = db.StringProperty()
color = db.IntegerProperty(default=CONST.No_Color)
name = db.StringProperty()
email = db.EmailProperty()
wants_email = db.BooleanProperty(default=True)
twitter = db.StringProperty()
wants_twitter = db.BooleanProperty(default=False)
contact_type = db.StringProperty(default=CONST.Email_Contact)
show_grid = db.BooleanProperty(default=False)
def get_safe_show_grid(self):
try:
safe_show_grid = self.show_grid
except:
safe_show_grid = False
return safe_show_grid
def get_safe_email(self):
try:
safe_email = self.email
except:
safe_email = None
if safe_email is None:
return ""
if safe_email == CONST.Default_Email:
return ""
return safe_email
def get_safe_twitter(self):
try:
safe_twitter = self.twitter
except:
safe_twitter = None
if safe_twitter is None:
return ""
return safe_twitter
def get_opponent(self):
opponent_color = opposite_color(self.color)
if opponent_color == CONST.Black_Color:
return self.game.get_black_player()
else:
return self.game.get_white_player()
def get_friendly_name(self):
friendly_name = self.name
at_loc = friendly_name.find('@')
if at_loc != -1:
friendly_name = friendly_name[:at_loc]
if len(friendly_name) > 18:
friendly_name = friendly_name[:15] + '...'
return friendly_name
def does_want_twitter(self):
# Smooth over the fact that this property wasn't here in the past.
try:
wants = self.wants_twitter
except:
wants = False
if wants is None:
return False
return wants
def get_active_contact_type(self):
if self.wants_email:
return CONST.Email_Contact
elif self.does_want_twitter():
return CONST.Twitter_Contact
else:
return CONST.No_Contact
def get_contact_type(self):
try:
c_t = self.contact_type
except:
c_t = CONST.Email_Contact
if c_t is None:
return CONST.Email_Contact
return c_t
def get_contact(self):
if self.wants_email:
return self.email
elif self.does_want_twitter():
return self.twitter
c_t = self.get_contact_type()
if c_t == CONST.Email_Contact:
return self.email
else:
return self.twitter
#------------------------------------------------------------------------------
# Base Handler
#------------------------------------------------------------------------------
class GoHandler(webapp.RequestHandler):
def __init__(self):
super(GoHandler, self).__init__()
def _template_path(self, filename):
return os.path.join(os.path.dirname(__file__), 'templates', filename)
def render_json(self, obj):
self.response.headers['Content-Type'] = 'application/json'
self.response.out.write(simplejson.dumps(obj))
def render_text(self, text):
self.response.headers['Content-Type'] = 'text/plain'
self.response.out.write(text)
def render_template(self, filename, template_args=None, content_type='text/html', **template_extras):
if not template_args:
final_args = {}
else:
final_args = template_args.copy()
final_args.update(template_extras)
self.response.headers['Content-Type'] = content_type
self.response.out.write(template.render(self._template_path(filename), final_args))
def is_valid_name(self, name):
return (name is not None) and (len(name) > 0) and (len(name) < 200)
def is_valid_email(self, email):
# There is no "correct" way to validate an email.
# This is the best you can really do.
if email is None:
return False
if len(email) <= 4:
return False
if len(email) > 200:
return False
i_at = email.find('@')
i_p = email.find('.')
i_right_p = email.rfind('.')
i_last = len(email) - 1
if i_at == -1 or i_p == -1:
return False
# @ can't come at front
if i_at == 0:
return False
# @ must come before .
# and there must be a character in between
if i_at >= (i_right_p - 1):
return False
# final domain names must be one or more characters
if i_right_p >= len(email) - 1:
return False
return True
def is_valid_twitter(self, twitter):
if twitter is None:
return False
if (len(twitter) < 1) or (len(twitter) > 16):
return False
# a python hax0r told me this would be faster than REs for very short strings