This repository has been archived by the owner on Apr 7, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
server_badtrips.py
245 lines (209 loc) · 7.03 KB
/
server_badtrips.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
from flask import Flask, session, request, jsonify, send_from_directory, escape
import os
import json
import redis
import wrapper_yelp
import google_photo
r = redis.Redis(host='localhost', port=6379, password='')
app = Flask("badtrips", static_url_path='')
app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RZ'
static_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'static')
@app.route('/static/<path:path>')
def send_js(path):
return send_from_directory(static_dir, path)
@app.route('/')
def index():
'''
Starting page
user chooses the location of the game
:return:
'''
return send_from_directory(static_dir, 'index.html')
@app.route('/play', methods=['POST'])
def play():
'''
Must recieve a location in the request
if we dont have a location generate a random one?
:return:
'''
id = newGame(request.form['location'], request.form['username'])
session['id'] = id
app.logger.debug('New game created with location: '+ request.form['location'] +' id: ' + str(id))
return send_from_directory(static_dir, 'play.html')
@app.route('/newquestion', methods=['POST'])
def newQuestion():
'''
Create a new question from yelp
returns a json with:
id: this question id, to check the correct responce
A:
B:
:return:
'''
game = getGame(session['id'])
app.logger.debug("New question from "+ str(session['id']) +"\nGame object: "+ str(game) +"\n" )
if game['state'] != "playing":
return jsonify({"state":"no no no no"})
question, answer, worst_rev = wrapper_yelp.createNewQuestion(game['location'])
if question['A']['image_url'] == "":
app.logger.debug("A sem imagem")
try:
question['A']['image_url'] = google_photo.get_photo(question['A']['name'],
(question['A']['coordinates.latitude'], question['A']['coordinates.longitude']))
except:
question['A']['image_url'] = "/static/burger.jpg"
if question['B']['image_url'] == "":
app.logger.debug("B sem imagem")
try:
question['B']['image_url'] = google_photo.get_photo(question['B']['name'],
(question['B']['coordinates.latitude'], question['B']['coordinates.longitude']))
except:
question['B']['image_url'] = "/static/burger.jpg"
store_answer(answer, session['id'], game)
store_review(worst_rev, session['id'], game)
return jsonify(question)
@app.route('/answer', methods=['POST'])
def answer():
'''
will recieve answer:<nome>
:return:
'''
answer = request.form['answer']
game = getGame(session['id'])
if game['state'] != "playing":
return jsonify({"state":"no no no no"})
response, correct_answer, review = check_answer(answer, session['id'], game)
app.logger.debug("New answer from " + str(session['id']) +"\nGame object: " + str(game) + "\nAnswer: " + answer)
if response:
return jsonify({"correct": True, "answer": correct_answer, "review": review})
else:
app.logger.debug("GAME OVER")
register_gameover(session['id'], game)
return jsonify({"correct": False, "answer": correct_answer, "review": review})
@app.route('/leaderboard',methods=['POST'])
def lead():
game = getGame(session['id'])
l = leaderboard(game)
j = []
for i in l:
print(i)
j.append([escape(str(i[0], 'latin-1')),i[1]])
print(j)
return jsonify(j)
@app.route('/answermulti', methods=['POST'])
def answermulti():
answer = request.form['answer']
user = request.form['user']
game = getGame(session['id'])
if game['state'] != "playing":
return jsonify({"state":"no no no no"})
response, correct_answer, review = check_answer_multi(answer, user, session['id'], game)
return jsonify({"correct": response, "answer": correct_answer, "review": review})
@app.route('/playmulti', methods=['POST'])
def multi():
p1_name = "p1"
p2_name = "p2"
id = newMultiGame(request.form['location'], p1_name, p2_name)
session['id'] = id
app.logger.debug('New multiplayer game created with location: ' + request.form['location'] + ' id: ' + str(id))
return send_from_directory(static_dir, 'playmulti.html')
def newGame(location, username):
'''
create a new game that has a location, username, id, score and state
:return: session id
'''
id = os.urandom(32)
game = {
"location": location,
"score": 0,
"username": username,
"state": "playing"
}
r.set(id, json.dumps(game))
return id
def getGame(id):
'''
get a game session from redis
:param id:
:return:
'''
game = r.get(id)
print("game from redis")
print(game)
return json.loads(game)
def store_answer(answer, id, game):
'''
store a answer for a game
:param answer:
:param game:
:param id:
:return:
'''
game["answer"] = answer
r.set(id, json.dumps(game))
def store_review(review, id, game):
'''
store a review for a game
:param review:
:param game:
:param id:
:return:
'''
game["review"] = review
r.set(id, json.dumps(game))
def leaderboard(game):
l = r.zrevrange("scores" + game['location'], 0, 5, withscores=True)
print(l)
return l
def register_gameover(id, game):
'''
Register in the db this user score and set the state to gameover
:param id:
:param game:
:return:
'''
game['state'] = 'gameover'
r.set(id, json.dumps(game))
score = r.zscore("scores" + game['location'], game["username"])
app.logger.debug("SCORE IN BD: " + str(score))
if score is not None:
if score < game['score']:
app.logger.debug("ADDING score to leaderboard")
r.zadd("scores"+ game['location'], game['username'], game['score'])
else:
app.logger.debug("ADDING score to leaderboard")
r.zadd("scores" + game['location'], game['username'], game['score'])
def check_answer_multi(answer, user, id, game):
if game["answer"] == answer:
if user == 1:
game['p1_score'] += 1
elif user == 2:
game['p2_score'] += 1
r.set(id, json.dumps(game))
return True, game['answer'], game['review']
return False, game['answer'], game['review']
def check_answer(answer, id, game):
'''
Check if the user answer is correct and updates the user score in the db
:param answer: the user answer
:param id: this game id
:param game: this game session
:return: True if is correct,false if incorrect and
'''
if game["answer"] == answer:
game["score"] += 1
r.set(id, json.dumps(game))
return True, game["answer"], game['review']
return False, game["answer"], game['review']
def newMultiGame(location, p1, p2):
id = os.urandom(32)
game = {
"location": location,
"score_p1": 0,
"score_p2": 0,
"p1": p1,
"p2": p2,
"state": "playing"
}
r.set(id, json.dumps(game))
return id