/
api.py
299 lines (253 loc) · 12.8 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
# -*- coding: utf-8 -*-`
"""api.py - Create and configure the Game API exposing the resources.
This can also contain game logic. For more complex games it would be wise to
move game logic to another file. Ideally the API will be simple, concerned
primarily with communication to/from the API's users."""
import logging
import endpoints
from protorpc import remote, messages
from google.appengine.api import memcache
from google.appengine.api import taskqueue
from google.appengine.ext import ndb
from models import User, Game, Score
from models import StringMessage, NewGameForm, GameForm, GameForms, MakeMoveForm, \
ScoreForms, LimitResults
from utils import get_by_urlsafe
NEW_GAME_REQUEST = endpoints.ResourceContainer(NewGameForm)
GET_GAME_REQUEST = endpoints.ResourceContainer(
urlsafe_game_key=messages.StringField(1), )
MAKE_MOVE_REQUEST = endpoints.ResourceContainer(
MakeMoveForm,
urlsafe_game_key=messages.StringField(1), )
USER_REQUEST = endpoints.ResourceContainer(user_name=messages.StringField(1, required=True),
email=messages.StringField(2))
MEMCACHE_MOVES_REMAINING = 'MOVES_REMAINING'
# - - - - GetYourBonusDayApi Endpoints - - - - - - - - - - - - - - - - - - - - - - - - -
@endpoints.api(name='get_your_bonus_day', version='v1')
class GetYourBonusDayApi(remote.Service):
"""Game API"""
# - - - - Create user endpoint - - - - - - - - - - - - - - -
@endpoints.method(request_message=USER_REQUEST,
response_message=StringMessage,
path='user',
name='create_user',
http_method='POST')
def create_user(self, request):
"""Create a User. Requires a unique username"""
if User.query(User.name == request.user_name).get():
raise endpoints.ConflictException(
'A User with that name already exists!')
user = User(name=request.user_name, email=request.email)
user.put()
return StringMessage(message='User {} created!'.format(
request.user_name))
# - - - - New game endpoint - - - - - - - - - - - - - - -
@endpoints.method(request_message=NEW_GAME_REQUEST,
response_message=GameForm,
path='game',
name='new_game',
http_method='POST')
def new_game(self, request):
"""Creates new game"""
user = User.query(User.name == request.user_name).get()
# Validate user
if not user:
raise endpoints.NotFoundException(
'A User with that name does not exist!')
# Check to see if game already exist.
if user.key and request.attempts:
games = Game.query(Game.user == user.key)
for game in games:
if game and game.attempts_allowed == request.attempts:
game.key.delete()
game = Game.new_game(user.key, request.attempts)
user.attempts_allowed = request.attempts
user.put()
# Use a task queue to update the average attempts remaining.
# 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('Good luck playing Get Your Bonus Day!')
# - - - - Get game endpoint - - - - - - - - - - - - - - -
@endpoints.method(request_message=GET_GAME_REQUEST,
response_message=GameForm,
path='game/{urlsafe_game_key}',
name='get_game',
http_method='GET')
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('Time to make a move!')
else:
raise endpoints.NotFoundException('Game not found!')
# - - - - Get user game endpoint - - - - - - - - - - - - - - -
@endpoints.method(request_message=USER_REQUEST,
response_message=GameForms,
path='games/user/{user_name}',
name='get_user_games',
http_method='GET')
def get_user_games(self, request):
"""Returns all of an individual User's games"""
user = User.query(User.name == request.user_name).get()
if not user:
raise endpoints.NotFoundException(
'A User with that name does not exist!')
games = Game.query(Game.user == user.key). \
filter(Game.game_over == False)
return GameForms(items=[game.to_form('Time to make a move!') for game in games])
# - - - - Make move endpoint - - - - - - - - - - - - - - -
@endpoints.method(request_message=MAKE_MOVE_REQUEST,
response_message=GameForm,
path='game/{urlsafe_game_key}',
name='make_move',
http_method='PUT' or 'DELETE')
def make_move(self, request):
"""Makes a move. Returns a game state with message"""
game = get_by_urlsafe(request.urlsafe_game_key, Game)
user = User.query(User.name == request.user_name).get()
# Validate user
if not user:
raise endpoints.NotFoundException(
'A User with that name does not exist!')
# Validate game and player
if game and user.key == game.user:
user.attempts_allowed = game.attempts_allowed
user.put()
# Check to see if game is already finished
if game.game_over:
game.add_game_history('Game already over!', game.attempts_allowed - game.attempts_remaining)
user.game_over = True
user.put()
return game.to_form('Game already over!')
# Check to see if valid guess
if request.pick_a_date > 31 or request.pick_a_date < 1:
game.add_game_history('Invalid guess! No such date!', game.attempts_allowed - game.attempts_remaining)
return game.to_form('Invalid guess! No such date!')
else:
game.attempts_remaining -= 1
# If the dates match, user win.
if request.pick_a_date == game.target:
user.num_of_wons += 1
user.game_over = True
user.put()
game.num_of_wons = user.num_of_wons
game.won = True
game.add_game_history('Congratulations! You picked the correct date.',
game.attempts_allowed - game.attempts_remaining)
game.end_game(game.won, game.num_of_wons)
game.put()
return game.to_form('You win!')
# If guess is incorrect, warn user and try again
if request.pick_a_date < game.target:
msg = 'Maybe too early for a bonus!'
game.add_game_history('You guessed higher.', game.attempts_allowed - game.attempts_remaining)
else:
msg = 'A little too late, a bonus comes sooner than that!'
game.add_game_history('You guessed lower.', game.attempts_allowed - game.attempts_remaining)
# User guesses incorrectly and exceeded limited attempts, so game over
if game.attempts_remaining < 1:
user.num_of_wons == user.num_of_wons
user.game_over = True
user.put()
game.won = False
game.num_of_wons = user.num_of_wons
game.add_game_history('Incorrect. Game over!', game.attempts_allowed - game.attempts_remaining)
game.end_game(game.won, game.num_of_wons)
game.put()
return game.to_form(msg + ' Game over!')
raise endpoints.BadRequestException('User_name not found! Or game already over! Or something else...')
# - - - - Cancel game endpoint - - - - - - - - - - - - - - -
@endpoints.method(request_message=GET_GAME_REQUEST, response_message=StringMessage,
path='game/{urlsafe_game_key}/cancel',
http_method='DELETE', name='cancel_game')
def cancel_game(self, request):
"""Cancel an active game."""
game = get_by_urlsafe(request.urlsafe_game_key, Game)
if game and not game.game_over:
game.canceled_game()
game.key.delete()
return StringMessage(message='Game with key: {} deleted.'.
format(request.urlsafe_game_key))
elif game and game.game_over:
raise endpoints.BadRequestException(
'Cannot cancel a completed game!')
else:
raise endpoints.NotFoundException('That game does not exist!')
# - - - - Get scores endpoint - - - - - - - - - - - - - - -
@endpoints.method(response_message=ScoreForms,
path='scores',
name='get_scores',
http_method='GET')
def get_scores(self, request):
"""Return all scores"""
scores = Score.query().order(Score.user)
return ScoreForms(items=[score.to_form() for score in scores])
# - - - - Get user scores endpoint - - - - - - - - - - - - - - -
@endpoints.method(request_message=USER_REQUEST,
response_message=ScoreForms,
path='scores/user/{user_name}',
name='get_user_scores',
http_method='GET')
def get_user_scores(self, request):
"""Returns all of an individual User's scores"""
user = User.query(User.name == request.user_name).get()
if not user:
raise endpoints.NotFoundException(
'A User with that name does not exist!')
scores = Score.query(Score.user == user.key)
return ScoreForms(items=[score.to_form() for score in scores])
# - - - - Get high scores endpoint - - - - - - - - - - - - - - -
@endpoints.method(request_message=LimitResults,
response_message=ScoreForms,
path='scores/high_scores',
name='get_high_scores',
http_method='GET')
def get_high_scores(self, request):
"""Return all scores ordered by total points"""
if request.limit:
scores = Score.query().order(-Score.num_of_wons).fetch(request.limit)
else:
scores = Score.query().order(-Score.num_of_wons).fetch()
return ScoreForms(items=[score.to_form() for score in scores])
# - - - - Get user rankings endpoint - - - - - - - - - - - - - - -
@endpoints.method(response_message=ScoreForms,
path='scores/user_rankings',
name='get_user_rankings',
http_method='GET')
def get_user_rankings(self, request):
"""Return all scores ordered by numbers of won"""
scores = Score.query().filter(Score.won == True).order(-Score.num_of_wons)
return ScoreForms(items=[score.to_form() for score in scores])
# - - - - Get game history endpoint - - - - - - - - - - - - - - -
@endpoints.method(request_message=GET_GAME_REQUEST,
response_message=StringMessage,
path='game/{urlsafe_game_key}/history',
name='get_game_history',
http_method='GET')
def get_game_history(self, request):
"""Returns a summary of a game's guesses."""
game = get_by_urlsafe(request.urlsafe_game_key, Game)
if not game:
raise endpoints.NotFoundException('Game not found')
return StringMessage(message=str(game.history))
# - - - - Get average attempts remaining endpoint - - - - - - - - - - - - - - -
@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 moves remaining"""
return StringMessage(message=memcache.get(MEMCACHE_MOVES_REMAINING) or '')
@staticmethod
def _cache_average_attempts():
"""Populates memcache with the average moves remaining of Games"""
games = Game.query(Game.game_over == False).fetch()
if games:
count = len(games)
total_attempts_remaining = sum([game.attempts_remaining
for game in games])
average = float(total_attempts_remaining) / count
memcache.set(MEMCACHE_MOVES_REMAINING,
'The average moves remaining is {:.2f}'.format(average))
api = endpoints.api_server([GetYourBonusDayApi])