-
Notifications
You must be signed in to change notification settings - Fork 0
/
game.py
90 lines (68 loc) · 2.8 KB
/
game.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
from board import Board
from google.appengine.ext import db
import logging
import re, pickle
import errors
import copy
class Game(db.Model):
black_email = db.StringProperty(required=True)
white_email = db.StringProperty(required=True)
whose_go = db.StringProperty(required=True)
pickled_board = db.BlobProperty()
pickled_last_board = db.BlobProperty()
history = db.StringListProperty()
processed = db.StringListProperty()
next_go = {'white' : 'black', 'black': 'white'}
def whose_go_email(self):
return getattr(self, self.whose_go + '_email')
def other_email(self):
return getattr(self, self.__class__.next_go[self.whose_go] + '_email')
def __init__(self, *args, **kwargs):
db.Model.__init__(self, *args, **kwargs)
if self.pickled_board:
self.board = pickle.loads(self.pickled_board)
self.last_board = pickle.loads(self.pickled_last_board)
else:
self.board = Board()
self.board.setup_initial_board()
self.last_board = self.board
def put(self, *args, **kwargs):
self.pickled_board = pickle.dumps(self.board)
self.pickled_last_board = pickle.dumps(self.last_board)
db.Model.put(self, *args, **kwargs)
def do_move(self, move):
move = move.lower()
logging.debug(move)
if 'undo' in move:
self.history.append(move)
self.board = self.last_board
self.whose_go = Game.next_go[self.whose_go]
raise errors.Undo
match = re.search(r'([a-h][1-8]) ?to ?([a-h][1-8])(?: ?and ?([a-h][1-8]) ?to ?([a-h][1-8]))?', move)
if match:
matches = match.groups()
_from = matches[0]
to = matches[1]
piece_moving = self.piece_at(_from)
move = "%s %s" % (unicode(piece_moving), move)
piece_taken = self.piece_at(to)
if piece_taken:
move = move + " (takes %s)" % unicode(piece_taken)
self.history.append(move)
self.last_board = copy.deepcopy(self.board)
self.move_from(_from, to)
if len(matches) >= 4 and matches[2] and matches[3]:
self.move_from(matches[2], matches[3])
self.whose_go = Game.next_go[self.whose_go]
else:
raise errors.InvalidMove
def piece_at(self, at):
x, y = self.coords_from_alphanumeric(at)
return self.board[x][y]
def move_from(self, _from, to):
from_x, from_y = self.coords_from_alphanumeric(_from)
to_x, to_y = self.coords_from_alphanumeric(to)
self.board[to_x][to_y] = self.board[from_x][from_y]
self.board[from_x][from_y] = None
def coords_from_alphanumeric(self, alpha):
return (int(alpha[1]) - 1, ord(alpha[0]) - 97)