-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.py
executable file
·389 lines (308 loc) · 14 KB
/
api.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
# -*- coding: utf-8 -*-`
"""api.py - Create and configure the Game API exposing the resources.
Concerned primarily with communication to/from the API's users."""
import logging
import endpoints
import json, random
from protorpc import remote, messages
from google.appengine.api import memcache
from google.appengine.api import taskqueue
from models import User, Game, Score, Language
from models import StringMessage, GameForm,\
ScoreForms, LanguageForm, LanguageForms, GameForms, UserForm,\
UserForms, StringMessage, RequestByGoogleID, UserRequest, NewGameRequest,\
RequestByGameKey, MakeMoveRequest, RequestByUserKey,\
GamesByUserIDRequest, ScoreRequest
from utils import get_by_urlsafe
NEW_GAME_REQUEST = endpoints.ResourceContainer(NewGameRequest)
REQUEST_BY_GAME_KEY = endpoints.ResourceContainer(RequestByGameKey)
MAKE_MOVE_REQUEST = endpoints.ResourceContainer(MakeMoveRequest)
USER_REQUEST = endpoints.ResourceContainer(UserRequest)
REQUEST_BY_GOOGLE_ID = endpoints.ResourceContainer(RequestByGoogleID)
REQUEST_BY_USER_KEY = endpoints.ResourceContainer(RequestByUserKey)
GAMES_BY_USER_ID_REQUEST = endpoints.ResourceContainer(GamesByUserIDRequest)
SCORE_REQUEST = endpoints.ResourceContainer(ScoreRequest)
MEMCACHE_MATCH_ATTEMPTS = 'MATCH_ATTEMPTS'
@endpoints.api(name='word_match', version='v1',
allowed_client_ids=['510381281726-4dbug0nd52nj5eq6q1mopccr6ggs542u.apps.googleusercontent.com'],
auth_level=endpoints.AUTH_LEVEL.OPTIONAL_CONTINUE)
class WordMatchApi(remote.Service):
"""Game API
"""
@endpoints.method(request_message=USER_REQUEST,
response_message=UserForm,
path='user',
name='create_user_from_google',
http_method='POST')
def create_user_from_google(self, request):
"""Create a User from Google account info.
Requires a unique Google account id.
"""
if User.query(User.google_id == request.user_google_id).get():
raise endpoints.ConflictException(
'A User with that google id already exists!')
user = User(name=request.user_name, email=request.email,
google_id=request.user_google_id)
user.put()
return user.to_form()
@endpoints.method(request_message=REQUEST_BY_GOOGLE_ID,
response_message=UserForm,
path='getuser',
name='get_user_from_google_id',
http_method='POST')
def get_user_from_google_id(self, request):
"""Get a user by the user's google account ID
"""
logging.info(request)
logging.info(request.user_google_id)
user = User.query(User.google_id == request.user_google_id).get()
logging.info(user)
if not user:
message = 'No user with the id "%s" exists.' % request.user_google_id
raise endpoints.NotFoundException(message)
to_form = user.to_form()
logging.info(to_form)
return to_form
@endpoints.method(request_message=GAMES_BY_USER_ID_REQUEST,
response_message=GameForms,
path='getusergames',
name='get_user_games',
http_method='POST')
def get_user_games(self, request):
"""Get a user's scores by user key
"""
user = get_by_urlsafe(request.urlsafe_user_key, User)
if not user:
message = 'No user with the id "%s" exists.' % request.user_google_id
raise endpoints.NotFoundException(message)
if request.active:
games = Game.query(Game.user == user.key, Game.game_over == False)
else:
games = Game.query(Game.user == user.key)
return GameForms(items=[game.to_form() for game in games])
@endpoints.method(request_message=NEW_GAME_REQUEST,
response_message=GameForm,
path='game',
name='create_game',
http_method='POST')
def create_game(self, request):
"""Creates new game
"""
user = get_by_urlsafe(request.urlsafe_user_key, User)
if not user:
raise endpoints.ForbiddenException(
'No (or invalid) user selected!')
language = Language.query(Language.name == request.language).get()
if not language:
raise endpoints.NotFoundException(
'The requested language does not exist in the server.')
logging.info(request.possible_matches)
if request.possible_matches > 20 or request.possible_matches < 1:
raise endpoints.ForbiddenException('Possible matches must be at least '\
'1 and at most 20')
logging.info(request.max_attempts)
if not request.max_attempts >= request.possible_matches:
raise endpoints.ForbiddenException('Max attempts must be greater '\
'than or equal to possible matches')
cards = language.cards
card_ids = {}
# generate random card ids to pick for the game
for x in range(0, request.possible_matches):
idToUse = random.randint(0, len(cards)/2)
while idToUse in card_ids:
idToUse = random.randint(0, len(cards)/2)
card_ids[str(idToUse)] = True
logging.info(card_ids)
game_cards = []
# get the cards
logging.info(cards)
for x in range(0, len(cards)):
if str(cards[x]["id"]) in card_ids:
logging.info(cards[x])
game_cards.append(cards[x])
random.shuffle(game_cards)
logging.info(game_cards)
# assign the position for board layout
for x in range(0, len(game_cards)):
game_cards[x]["position"] = x
game_cards[x]["isFlipped"] = False
game = Game(user=user.key,
possible_matches=request.possible_matches,
language=language.key,
cards=game_cards,
successful_matches=0,
selected_card={},
num_match_attempts=0,
match_attempts=[],
match_in_progress=False,
max_attempts=request.max_attempts,
game_over=False)
game.put()
# Use a task queue to update the average words typed.
# This operation is not needed to complete the creation of a new game
# so it is performed out of sequence.
taskqueue.add(url='/tasks/cache_average_attempts')
return game.to_form()
@endpoints.method(request_message=REQUEST_BY_GAME_KEY,
response_message=GameForm,
path='getgame',
name='get_game',
http_method='POST')
def get_game(self, request):
"""Return the current game state.
"""
game = get_by_urlsafe(request.urlsafe_game_key, Game)
if game:
return game.to_form()
else:
raise endpoints.NotFoundException('Game not found!')
@endpoints.method(request_message=REQUEST_BY_GAME_KEY,
response_message=GameForm,
path='getgamehistory',
name='get_game_history',
http_method='POST')
def get_game_history(self, request):
"""Return the current game state.
NOTE: Just calls 'get_game'. This is because a game object
already contains all moves in order, so there is currently no reason
to use this method and it is only here because Udacity required it by name.
"""
return get_game(self, request)
@endpoints.method(request_message=REQUEST_BY_GAME_KEY,
response_message=StringMessage,
path='cancelgame',
name='cancel_game',
http_method='POST')
def cancel_game(self, request):
"""Cancel (delete) the given game.
"""
game = get_by_urlsafe(request.urlsafe_game_key, Game)
if not game:
raise endpoints.NotFoundException('Game not found!')
if game.game_over:
raise endpoints.ForbiddenException(
'Cannot cancel a completed game.')
game.key.delete()
return StringMessage(message="Game cancelled.")
@endpoints.method(request_message=MAKE_MOVE_REQUEST,
response_message=GameForm,
path='makemove',
name='make_move',
http_method='PUT')
def make_move(self, request):
"""Handler for attempted match. Returns updated game state.
"""
game = get_by_urlsafe(request.urlsafe_game_key, Game)
if not game:
raise endpoints.NotFoundException("Game not found!")
if game.game_over:
return endpoints.ForbiddenException(
'Game already over!')
if game.cards[request.flipped_card_position]["isFlipped"]:
return endpoints.ForbiddenException(
'That card is already face up!')
# get the selected and previously selected card positions
# [whole method ripe for refactoring]
# remember, x = a card's position, just renaming some variables
thisSelectedCardIndex = request.flipped_card_position
if "position" in game.selected_card:
previouslySelectedCardIndex = game.selected_card["position"]
# flip the selected card
game.cards[thisSelectedCardIndex]["isFlipped"] = True
# evaluate a match attempt if appropriate
if game.match_in_progress:
# record the match attempt
game.num_match_attempts += 1
game.match_attempts.append([previouslySelectedCardIndex,
thisSelectedCardIndex])
# determine if match
if game.selected_card["id"] == game.cards[thisSelectedCardIndex]["id"]:
# keep them flipped
game.successful_matches += 1
else:
# flip them back over
game.cards[thisSelectedCardIndex]["isFlipped"] = False
game.cards[previouslySelectedCardIndex]["isFlipped"] = False
game.match_in_progress = False
game.selected_card = {}
else:
game.match_in_progress = True
game.selected_card = game.cards[thisSelectedCardIndex]
if game.successful_matches >= game.possible_matches:
game.end_game(True)
elif game.num_match_attempts >= game.max_attempts:
game.end_game(False)
game.put()
return game.to_form()
@endpoints.method(request_message=SCORE_REQUEST,
response_message=ScoreForms,
path='highscores',
name='get_high_scores',
http_method='POST')
def get_high_scores(self, request):
"""Return high scores
"""
scores = Score.query().order(-Score.percentage_matched, -Score.difficulty)
if not scores:
raise endpoints.NotFoundException("No scores yet!")
if request.limit:
scores = scores.fetch(request.limit)
return ScoreForms(items=[score.to_form() for score in scores])
@endpoints.method(request_message=REQUEST_BY_USER_KEY,
response_message=ScoreForms,
path='getuserscores',
name='get_user_scores',
http_method='POST')
def get_user_scores(self, request):
"""Returns all of an individual User's scores
"""
user = get_by_urlsafe(request.urlsafe_user_key, User)
if not user:
raise endpoints.NotFoundException(
'A User with that name does not exist!')
scores = Score.query(Score.user == user.key)
if not scores:
raise endpoints.NotFoundException("No scores for this user yet!")
return ScoreForms(items=[score.to_form() for score in scores])
@endpoints.method(response_message=UserForms,
path='getrankings',
name='get_user_rankings',
http_method='GET')
def get_user_rankings(self, request):
"""Returns users ordered by ranking
"""
users = User.query().order(-User.win_percentage, -User.average_difficulty)
if not users:
raise endpoints.NotFoundException("No users yet!")
return UserForms(items=[user.to_form() for user in users])
@endpoints.method(response_message=LanguageForms,
path='languages',
name='get_languages',
http_method='GET')
def get_languages(self, request):
"""Returns all available languages
"""
return LanguageForms(items=[language.to_form() for language in Language.query()])
# average attempts is probably a not-great metric to cache but at least the code is here
@endpoints.method(response_message=StringMessage,
path='games/average_attempts',
name='get_average_attempts_remaining',
http_method='GET')
def get_average_attempts(self, request):
"""Get the cached average attempts for every game
"""
return StringMessage(message=memcache.\
get(MEMCACHE_MATCH_ATTEMPTS) or '')
@staticmethod
def _cache_average_attempts():
"""Populates memcache with the average match attempts of each completed Game
"""
games = Game.query(Game.game_over == True).fetch()
if games:
count = len(games)
total_match_attempts = sum([game.num_match_attempts
for game in games])
average = float(total_match_attempts)/count
memcache.set(MEMCACHE_MATCH_ATTEMPTS,
'The average match attempts is {:.2f}'.format(average))
api = endpoints.api_server([WordMatchApi])