-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchatactoe.py
187 lines (149 loc) · 5.17 KB
/
chatactoe.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
#!/usr/bin/python2.4
#
# Copyright 2010 Google Inc. All Rights Reserved.
# pylint: disable-msg=C6310
"""Channel Tic Tac Toe
This module demonstrates the App Engine Channel API by implementing a
simple tic-tac-toe game.
"""
import datetime
import logging
import os
import random
import re
from django.utils import simplejson
from google.appengine.api import channel
from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
class Game(db.Model):
"""All the data we store for a game"""
userX = db.UserProperty()
userO = db.UserProperty()
board = db.StringProperty()
moveX = db.BooleanProperty()
winner = db.StringProperty()
winning_board = db.StringProperty()
class Wins():
x_win_patterns = ['XXX......',
'...XXX...',
'......XXX',
'X..X..X..',
'.X..X..X.',
'..X..X..X',
'X...X...X',
'..X.X.X..']
o_win_patterns = map(lambda s: s.replace('X','O'), x_win_patterns)
x_wins = map(lambda s: re.compile(s), x_win_patterns)
o_wins = map(lambda s: re.compile(s), o_win_patterns)
class GameUpdater():
game = None
def __init__(self, game):
self.game = game
def get_game_message(self):
gameUpdate = {
'board': self.game.board,
'userX': self.game.userX.user_id(),
'userO': '' if not self.game.userO else self.game.userO.user_id(),
'moveX': self.game.moveX,
'winner': self.game.winner,
'winningBoard': self.game.winning_board
}
return simplejson.dumps(gameUpdate)
def send_update(self):
message = self.get_game_message()
channel.send_message(self.game.userX.user_id() + self.game.key().id_or_name(), message)
if self.game.userO:
channel.send_message(self.game.userO.user_id() + self.game.key().id_or_name(), message)
def check_win(self):
if self.game.moveX:
# O just moved, check for O wins
wins = Wins().o_wins
potential_winner = self.game.userO.user_id()
else:
# X just moved, check for X wins
wins = Wins().x_wins
potential_winner = self.game.userX.user_id()
for win in wins:
if win.match(self.game.board):
self.game.winner = potential_winner
self.game.winning_board = win.pattern
return
def make_move(self, position, user):
if position >= 0 and user == self.game.userX or user == self.game.userO:
if self.game.moveX == (user == self.game.userX):
boardList = list(self.game.board)
if (boardList[position] == ' '):
boardList[position] = 'X' if self.game.moveX else 'O'
self.game.board = "".join(boardList)
self.game.moveX = not self.game.moveX
self.check_win()
self.game.put()
self.send_update()
return
class GameFromRequest():
game = None;
def __init__(self, request):
user = users.get_current_user()
game_key = request.get('g')
if user and game_key:
self.game = Game.get_by_key_name(game_key)
def get_game(self):
return self.game
class MovePage(webapp.RequestHandler):
def post(self):
game = GameFromRequest(self.request).get_game()
user = users.get_current_user()
if game and user:
id = int(self.request.get('i'))
GameUpdater(game).make_move(id, user)
class OpenedPage(webapp.RequestHandler):
def post(self):
game = GameFromRequest(self.request).get_game()
GameUpdater(game).send_update()
class MainPage(webapp.RequestHandler):
"""The main UI page, renders the 'index.html' template."""
def get(self):
"""Renders the main page. When this page is shown, we create a new
channel to push asynchronous updates to the client."""
user = users.get_current_user()
game_key = self.request.get('g')
game = None
if user:
if not game_key:
game_key = user.user_id()
game = Game(key_name = game_key,
userX = user,
moveX = True,
board = ' ')
game.put()
else:
game = Game.get_by_key_name(game_key)
if not game.userO:
game.userO = user
game.put()
game_link = 'http://localhost:8080/?g=' + game_key
if game:
token = channel.create_channel(user.user_id() + game_key)
template_values = {'token': token,
'me': user.user_id(),
'game_key': game_key,
'game_link': game_link,
'initial_message': GameUpdater(game).get_game_message()
}
path = os.path.join(os.path.dirname(__file__), 'index.html')
self.response.out.write(template.render(path, template_values))
else:
self.response.out.write('No such game')
else:
self.redirect(users.create_login_url(self.request.uri))
application = webapp.WSGIApplication([
('/', MainPage),
('/opened', OpenedPage),
('/move', MovePage)], debug=True)
def main():
run_wsgi_app(application)
if __name__ == "__main__":
main()