-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.py
More file actions
295 lines (227 loc) · 7.52 KB
/
app.py
File metadata and controls
295 lines (227 loc) · 7.52 KB
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
import os
import time
from functools import wraps
from flask import ( Flask, flash, render_template, redirect,
request, session, url_for, abort)
from flask_pymongo import PyMongo
from bson.objectid import ObjectId
if os.path.exists("env.py"):
import env
app = Flask(__name__)
app.config["MONGO_DBNAME"] = os.environ.get("MONGO_DBNAME")
app.config["MONGO_URI"] = os.environ.get("MONGO_URI")
app.secret_key = os.environ.get("SECRET_KEY")
DEBUGGING = (os.environ.get("DEBUGGING").lower() == "true")
DEVELOPING = (os.environ.get("DEVELOPING").lower() == "true")
mongo = PyMongo(app)
def dev_only(func):
""" Disables a wrapped route if not in development. """
@wraps(func)
def route(*args, **kwargs):
if DEVELOPING:
return func(*args, **kwargs)
else:
abort(404)
return route
def get_question_list():
""" Returns the list of questions already asked. """
if "questions" not in session:
session["questions"] = []
id_list = []
for id in session["questions"]:
id_list.append(ObjectId(id))
return id_list
def add_question_to_list(id):
""" Adds a question to the list of asked questions. Takes ObjectId. """
if "questions" not in session:
session["questions"] = []
tempList = session["questions"]
tempList.append(str(id))
session["questions"] = tempList
def get_question():
#Get the list of questions already asked
question_list = get_question_list()
#Get the first question
question = list(mongo.db.questions.aggregate([
#Excludes questions already asked
{ "$match" : { "_id" : {"$nin" : question_list} }},
#Returns one random record
{ "$sample" : { "size" : 1 } }
]))
#If we run out of questions, end the quiz
if question == []:
return redirect(url_for("gameover"))
#Add the new question to the list
add_question_to_list(question[0]["_id"])
return question
def get_score():
""" Returns the player's current score """
if "player_score" not in session:
session["player_score"] = 0
return session["player_score"]
def inc_score():
""" Adds one to player score """
if "player_score" not in session:
session["player_score"] = 0
session["player_score"] += 1
def clear_game_state():
""" Clears persistent game state variables """
session["player"] = ""
session["player_score"] = 0
session["game_start"] = 0
session["questions"] = []
def game_time():
""" Returns the length of a game in seconds """
#Game length in seconds
return 60;
@app.route("/")
@app.route("/home")
def home():
""" Homepage route. """
clear_game_state()
return render_template("home.html")
@app.route("/startgame", methods=["POST"])
def startgame():
clear_game_state()
if 'player_name' in request.form:
session['player'] = request.form['player_name']
session['player_score'] = 0
session["game_start"] = time.time()
else:
return abort(400)
return redirect(url_for("quiz"))
@app.route("/quiz")
def quiz():
""" Quiz page route. """
#Calculate game time remaining
time_left = game_time() - (time.time() - session["game_start"])
#If game time has expired, force gameover
if time_left <= 0:
redirect(url_for("gameover"))
if 'sound' not in session:
session['sound'] = True
question = get_question()
return render_template("quiz.html", question = question[0], time_left=time_left)
@app.route("/gameover")
@app.route("/leaderboard")
def gameover():
""" Called when the game ends. """
player = {}
if 'player' in session and session['player']:
if session['player_score'] > 0:
#Store the player's score
id = mongo.db.scores.insert_one({
"player" : session["player"],
"score" : session["player_score"],
"time" : game_time()
})
#Where did the player place in the database?
position = mongo.db.scores.count_documents({
"score" : {"$gte":session["player_score"]}
})
player = {
"name" : session['player'],
"score" : session['player_score'],
"place" : position,
"id" : id.inserted_id
}
scores = mongo.db.scores.find().sort([
("score", -1),
("_id", 1)
]).limit(10)
#clear session
clear_game_state()
return render_template("leaderboard.html", scores=scores, player=player)
@app.route("/AJAX_answer", methods=["POST"])
def AJAX_answer():
""" Accepts an answer as an ajax request and returns if it is correct. """
#Check that the game time hasn't elapsed
time_left = game_time() - (time.time() - session["game_start"])
if time_left <= 0:
redirect(url_for("gameover"))
response = {
"correct_answer" : -1,
"player_correct" : False,
"player_score" : -1
}
correct = False
question_list = get_question_list()
if "answer" in request.json:
question = mongo.db.questions.find_one( {"_id" : ObjectId(question_list[-1])} )
#Did the player get the right answer?
if (question['answer'] == int(request.json['answer'])):
correct = True
inc_score()
response['correct_answer'] = question['answer']
response['player_correct'] = correct
response['player_score'] = session['player_score']
#Get the next question
question = get_question()[0]
response["next_question"] = {
"question" : question["question"],
"options" : [
question["options"][0],
question["options"][1],
question["options"][2],
question["options"][3]
]
}
return response
@app.route("/AJAX_sound", methods=["POST"])
def AJAX_sound():
""" Toggles session sound on/off """
if 'sound' not in session:
session['sound'] = True
session['sound'] = ('sound-toggle' in request.json)
return {"sound-state" : session['sound']}
#
# Development only routes
# These routes are to aid development and debugging and
# will be switched off in production
#
@app.route("/add_question", methods=["GET", "POST"])
@dev_only
def add_question():
""" Adds a single question to the database. """
if request.method == "POST":
new_question = {
"question" : request.form["question"],
"options" : [
request.form["option_1"],
request.form["option_2"],
request.form["option_3"],
request.form["option_4"]
],
"answer" : int(request.form["answer"])
}
mongo.db.questions.insert_one(new_question)
return render_template("add_question.html")
@app.route("/upload_questions")
@dev_only
def upload_questions():
""" Bulk uploads questions in JSON format to the database. """
"""
questions = [
{
"question" : "?",
"options" : [
"",
"",
"",
""
],
"answer" :
}]
mongo.db.questions.insert(questions)
"""
return "Uploaded questions"
@app.route("/all_questions")
@dev_only
def all_questions():
""" Lists all the questions in the database. """
questions = mongo.db.questions.find()
return render_template("all_questions.html", questions=questions)
if __name__ == "__main__":
app.run(host=os.environ.get("IP"),
port=int(os.environ.get("PORT")),
debug=DEBUGGING)