-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
328 lines (294 loc) · 14.3 KB
/
main.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
import os
import jinja2
import webapp2
from google.appengine.api import users
from google.appengine.ext import ndb
from data_classes import *
#import json
from google.appengine.api import urlfetch
import json
import api_key
JINJA_ENVIRONMENT = jinja2.Environment(
loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),
extensions=['jinja2.ext.autoescape'],
autoescape=True)
def add_to_Database(current_user):
user = User_data.query(User_data.user == current_user, ancestor=root_parent()).fetch()
if not user:
new_user_data = User_data(parent=root_parent())
new_user_data.user = users.get_current_user()
new_user_data.name = users.get_current_user().email()
new_user_data.wins = 0
new_user_data.put()
def getRandomWords():
headers = {"X-Mashape-Key": api_key.rapidapi_key,
"Accept": "application/json"}
result = urlfetch.fetch(
url = "https://wordsapiv1.p.rapidapi.com/words/?random=true" ,
# url='https://wordsapiv1.p.rapidapi.com/words/?random=true',
headers=headers).content
randomwords_json = json.loads(result)
return randomwords_json
class LoginPage(webapp2.RequestHandler):
def get(self):
user = users.get_current_user()
randomwords_json = getRandomWords()
#Sometimes doesn't work
while ((("results" not in randomwords_json or "definition" not in randomwords_json["results"][0] and " " in randomwords_json["word"]))or ( " " in randomwords_json["word"])):
randomwords_json= getRandomWords()
data = {
'user': user,
'login_url': users.create_login_url(self.request.uri),
'logout_url': users.create_logout_url(self.request.uri),
'words': randomwords_json,
'error' : ""
}
if user:
add_to_Database(user)
data['user_data'] = User_data.query(User_data.user == user, ancestor=root_parent()).fetch()[0]
data['error'] = self.request.get('error')
template = JINJA_ENVIRONMENT.get_template('templates/homePage/homePage.html')
elif not user:
template = JINJA_ENVIRONMENT.get_template('templates/loginPage/login.html')
self.response.headers['Content-Type'] = 'text/html'
self.response.write(template.render(data))
# API stuff- Fantah put under game page handler
#self.response.write(result.content) when responding to client
def link_player_game(current_user,gameID,isMaster = False):
#We assume that the player is logged in and search for the user in the user_data data table,
#This will allow us to acess that player's name
player = User_data.query(User_data.user == current_user, ancestor=root_parent()).fetch()[0]
new_player = Players(parent=root_parent())
new_player.name = player.name
new_player.email = player.user.email()
# ndb.Key(urlsafe = gameID) Used to create a game key based on the
new_player.gameKey = ndb.Key(urlsafe = gameID)
new_player.isMaster = isMaster
new_player.put()
class AddGameState(webapp2.RequestHandler):
def post(self):
#Randomizing/getting words
randomwords_json = getRandomWords()
while ((("results" not in randomwords_json or "definition" not in randomwords_json["results"][0] and " " in randomwords_json["word"]))or ( " " in randomwords_json["word"])):
randomwords_json= getRandomWords()
generated_word = randomwords_json["word"]
generated_def = randomwords_json["results"][0]["definition"]
#Instantiating state
new_game_state = Game_state(parent=root_parent())
new_game_state.word = generated_word
new_game_state.definition = generated_def
new_game_state.fake_definition = ""
gameKey = new_game_state.put()
link_player_game(users.get_current_user(), gameKey.urlsafe(), isMaster = True)
self.redirect("/player?gameID="+gameKey.urlsafe())
class updateGameState(webapp2.RequestHandler):
def get(self):
url = self.request.get('gameID')
gameKey = ndb.Key(urlsafe = url)
currentGame = gameKey.get()
#UPDATE THE CURRENT Game
randomwords_json = getRandomWords()
while ((("results" not in randomwords_json or "definition" not in randomwords_json["results"][0] and " " in randomwords_json["word"]))or ( " " in randomwords_json["word"])):
randomwords_json= getRandomWords()
generated_word = randomwords_json["word"]
generated_def = randomwords_json["results"][0]["definition"]
currentGame.word = generated_word
currentGame.definition = generated_def
currentGame.fake_definition = ""
currentGame.put()
###
players = Players.query( Players.gameKey == gameKey,ancestor=root_parent()).fetch()
for player in players:
player.isDone = False
player.put()
###players
#We gotta make all the players notDone again!!
# for player in players:
# player.isDone = False
# player.put()
self.redirect('/player?gameID='+url)
def post(self):
pass
# Link Player to the game # ID
# class HostPage(webapp2.RequestHandler):
# def get(self):
# self.request.get("gameID")
# template = JINJA_ENVIRONMENT.get_template('templates/gamePage/hostPage.html')
# self.response.headers['Content-Type'] = 'text/html'
# self.response.write(template.render())
#
# class PlayerPage(webapp2.RequestHandler):
# def get(self):
# template = JINJA_ENVIRONMENT.get_template('templates/gamePage/regularPlayer.html')
# self.response.headers['Content-Type'] = 'text/html'
# self.response.write(template.render())
class ajax_refresh(webapp2.RequestHandler):
def get(self):
print("RRUUUUUUUUUUUUUUUUUUUUUUUUUUUNGKLNDSLFsdfN/n/n/n/n/n\n\n\n\n\n\n\n")
url = self.request.get('gameID')
gameKey = ndb.Key(urlsafe = url)
print("RROOOOOOOOOOOOOOOOOOOOOOOOOOON")
# Now let's Dance!
#get all players from the game by their game key -> LeaderBoard Purposes
players = Players.query( Players.gameKey == gameKey,ancestor=root_parent()).fetch()
currentGame = gameKey.get()
willRedirect = True
for player in players:
if player.isDone:
pass
elif player.isDone == False:
willRedirect = False
retDict = {
"willRedirect" : willRedirect
}
self.response.headers['Content-Type'] = 'application/json'
# Turn data dict into a json string and write it to the response
self.response.write(json.dumps(retDict))
#self.response.write()
# self.redirect('/player?gameID='+url)
class get_current_definiton(webapp2.RequestHandler):
def get(self):
# We try to get the game key by looking at the urlsafe in the search bar
try:
url = self.request.get('gameID')
gameKey = ndb.Key(urlsafe = url)
except:
# The redirect doesn't end the function so return will
self.redirect('/?error="That is not a valid Key!!"')
return
try:
#Then we try to get the current logged in player by their current game and through their email as their identifier
currentPlayer = Players.query(Players.gameKey == gameKey, Players.email == users.get_current_user().email(), ancestor=root_parent()).fetch()[0]
except:
#If it doesn't exist then we assume this is a new player going in the game
#So we will add them to the database isMaster = False by default
link_player_game(users.get_current_user(), url)
#Now we try to get the Player again-- let's assume this works since we just added them above
currentPlayer = Players.query(Players.gameKey == gameKey, Players.email == users.get_current_user().email(), ancestor=root_parent()).fetch()[0]
# Now let's Dance!
#get all players from the game by their game key -> LeaderBoard Purposes
players = Players.query( Players.gameKey == gameKey,ancestor=root_parent()).fetch()
currentGame = gameKey.get()
user = users.get_current_user()
if user is None:
# No user is logged in, so don't return any value.
self.response.status = 401
return
user_definition = currentGame.fake_definition
user_word = currentGame.word
# build a dictionary that contains the data that we want to return.
data = {'fake_definition': user_definition,
'word' : user_word }
# Note the different content type.
self.response.headers['Content-Type'] = 'application/json'
# Turn data dict into a json string and write it to the response
self.response.write(json.dumps(data))
class PlayerPage(webapp2.RequestHandler):
def get(self):
# We try to get the game key by looking at the urlsafe in the search bar
try:
url = self.request.get('gameID')
gameKey = ndb.Key(urlsafe = url)
except:
# The redirect doesn't end the function so return will
self.redirect('/?error="That is not a valid Key!!"')
return
try:
#Then we try to get the current logged in player by their current game and through their email as their identifier
currentPlayer = Players.query(Players.gameKey == gameKey, Players.email == users.get_current_user().email(), ancestor=root_parent()).fetch()[0]
except:
#If it doesn't exist then we assume this is a new player going in the game
#So we will add them to the database isMaster = False by default
link_player_game(users.get_current_user(), url)
#Now we try to get the Player again-- let's assume this works since we just added them above
currentPlayer = Players.query(Players.gameKey == gameKey, Players.email == users.get_current_user().email(), ancestor=root_parent()).fetch()[0]
# Now let's Dance!
#get all players from the game by their game key -> LeaderBoard Purposes
players = Players.query( Players.gameKey == gameKey,ancestor=root_parent()).fetch()
currentGame = gameKey.get()
# We update our data dictionary with these values
#currentGame = Game_state.query( Game_state.id == gameKey,ancestor=root_parent()).fetch()[0]
data = {
"players" : players,
"currentPlayer" : currentPlayer,
"word" : currentGame.word,
"url" : url
}
# Now it's time to determine this player's role to display the correct html page
if currentPlayer.isMaster == True:
data["definition"]= currentGame.definition
data["fake_definition"]= currentGame.fake_definition
template = JINJA_ENVIRONMENT.get_template('templates/gamePage/hostPage.html')
elif currentPlayer.isMaster == False:
data["fake_definition"]= currentGame.fake_definition
template = JINJA_ENVIRONMENT.get_template('templates/gamePage/regularPlayer.html')
# Finally we render the HTML page
self.response.headers['Content-Type'] = 'text/html'
self.response.write(template.render(data))
def post(self):
## Getting key and current player
url = self.request.get('gameID')
gameKey = ndb.Key(urlsafe = url)
players = Players.query( Players.gameKey == gameKey,ancestor=root_parent()).fetch()
currentPlayer = Players.query(Players.gameKey == gameKey, Players.email == users.get_current_user().email(), ancestor=root_parent()).fetch()[0]
currentGame = gameKey.get()
if currentPlayer.isMaster == True:
currentGame.fake_definition = self.request.get("fakeDefinition")
currentGame.put()
currentPlayer.isDone = True
currentPlayer.put()
#self.redirect('/standBy?gameID='+url)
self.redirect('/standBy?gameID='+url)
elif currentPlayer.isMaster == False:
#We try to get the answer to the # QUESTION:
answer = self.request.get("check")
if currentPlayer.isDone == False:
if answer == "real":
if currentGame.definition == currentGame.fake_definition:
currentPlayer.score = currentPlayer.score+1
else:
for player in players:
if player.isMaster:
player.score = player.score+1
player.put()
elif answer == "fake":
if currentGame.definition == currentGame.fake_definition:
for player in players:
if player.isMaster:
player.score = player.score+1
player.put()
else:
currentPlayer.score = currentPlayer.score+1
currentPlayer.isDone = True
currentPlayer.put()
self.redirect('/player?gameID='+url)
class standByPage(webapp2.RequestHandler):
def get(self):
url = self.request.get('gameID')
gameKey = ndb.Key(urlsafe = url)
currentPlayer = Players.query(Players.gameKey == gameKey, Players.email == users.get_current_user().email(), ancestor=root_parent()).fetch()[0]
print self.request.get("fakeDefinition")
template = JINJA_ENVIRONMENT.get_template('templates/gamePage/standBy.html')
data = {
"currentPlayer" : currentPlayer
}
self.response.headers['Content-Type'] = 'text/html'
self.response.write(template.render(data))
#self.redirect('/player?gameID='+url)
def post(self):
pass
class LearnMore(webapp2.RequestHandler):
def get(self):
template = JINJA_ENVIRONMENT.get_template('templates/loginPage/learnMore.html')
self.response.headers['Content-Type'] = 'text/html'
self.response.write(template.render())
app = webapp2.WSGIApplication([
('/', LoginPage),
('/player', PlayerPage),
('/newgamestate', AddGameState),
('/standBy', standByPage),
('/ajax/get_def', get_current_definiton),
('/ajax/refresh', ajax_refresh),
('/learnmore', LearnMore),
('/updateGame',updateGameState),
], debug=True)