This repository has been archived by the owner on Dec 26, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
executable file
·419 lines (347 loc) · 13.6 KB
/
app.js
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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
/*
* Midburn 2016 Abracadabra Quiz app - )'( let it burn!
*
* Back-end: Elad
* Front-end: Nate
* Design: Nir
*
* MODULES IN USE: pascalprecht.translate
* ngResource
*
* */
var configFile = getConfigFromConfigFile();
var app = angular.module('quizApp', ['ngResource', 'pascalprecht.translate']);
//
// Constants
app.constant('config', {
API_URL: configFile.api_url,
userId: configFile.user_id
});
//
// Init question-answer vars
Window.currentQuestion = {
id: null,
question: null,
options: null,
userSelectedElement: null,
answer: null,
category: null
}
Window.game = {
token: null,
categories: [],
hintBtn: $("button#btnHint")
}
//
// Set-up new game
app.controller('quizInit', function ($scope, $rootScope, $http, config) {
// Get user id from url param
userId = getUrlParams('userId');
if (userId === undefined) {
$(function () {
$("#game-start-wrapper").hide();
});
alert("User id is missing!")
return;
}
$scope.Init = function (lang = "en") {
var new_gameRequest = {
method: 'POST',
url: config.API_URL + '/games/new/',
contentType: 'application/json',
dataType: 'json',
data: { language: lang, user_id: userId }
}
$http(new_gameRequest).then(function (response) {
// set the game model
Window.game = response.data;
}, function () {
// New game init failure
console.error("Failed to init new game");
});
}
});
//
// Quiz mechanism
//
app.directive('quiz', function (quizFactory, $http, config) {
var qnumber;
var game = Window.game;
var categories = Window.game.categories;
return {
restrict: 'AE',
scope: {},
templateUrl: 'statics/template.html',
link: function (scope, elem, attrs) {
// Quiz start init
scope.start = function () {
// hide intro
$("#intro").fadeOut("fast");
qnumber = 0;
scope.id = 0;
scope.quizOver = false;
scope.inProgress = true;
scope.categories = Window.game.categories;
scope.nextQuestion();
};
// Quiz get question
scope.getQuestion = function(category) {
// Get question request
var getQuestionRequest = {
method: 'POST',
url: config.API_URL + "/games/" + Window.game.token + '/new_question/',
contentType: 'application/json',
dataType: 'json',
data: { category: category.name }
}
$http(getQuestionRequest).then(function (response) {
/* Data returned from API:
* Qustion id, text, answers, category
* */
Window.currentQuestion.id = response.data.id;
Window.currentQuestion.question = response.data.body;
Window.currentQuestion.options = response.data.answers;
Window.currentQuestion.category = response.data.category ? response.data.category.name : "כללי";
Window.currentQuestion.answer = 0;
if (Window.currentQuestion) {
scope.qnumber = qnumber;
scope.question = Window.currentQuestion.question;
scope.options = Window.currentQuestion.options;
scope.answer = Window.currentQuestion.answer;
scope.category = Window.currentQuestion.category;
scope.answerMode = true;
} else {
scope.quizOver = true;
}
}, function () {
// Get questions failure
console.log("Error: can't get questions from api");
});
};
scope.isCategoryCompleted = function(category) {
return category.category_completed;
}
scope.selectCategory = function() {
var categories = Window.game.categories;
for (var i = 0; i < categories.length; i++) {
var category = categories[i];
if (!scope.isCategoryCompleted(category)) {
return category;
}
}
console.log("GAME ENDED");
}
scope.updateProgressBar = function(category) {
var pages = $(".category-pagination");
for (var i = 0; i < pages.length; i++) {
var pageElem = pages[i];
var categoryId = pageElem.getAttribute("data-category-id");
if (category.category_id == parseInt(categoryId)) {
pageElem.classList.remove("disabled");
pageElem.classList.add("active");
} else {
pageElem.classList.add("disabled");
}
}
}
// Quiz next question
scope.nextQuestion = function () {
qnumber++;
scope.id++;
category = scope.selectCategory();
scope.getQuestion(category);
scope.updateProgressBar(category);
};
// Get hint
scope.getHint = function () {
var post_getHint = {
method: 'POST',
url: config.API_URL + "/games/" + Window.game.token + '/hint',
contentType: 'application/json',
dataType: 'json',
data: { question_id: Window.currentQuestion.id }
}
$http(post_getHint).then(function (response) {
var hints = [];
for (var i = 0; i < response.data.hints.length; i++) {
hints.push(response.data.hints[i].id);
}
// Remove two answers
// $("ul#options > li input[type='radio'][value='1385'], ul#options > li input[type='radio'][value='1388']")
for (var i = 0; i < hints.length; i++) {
var answerId = hints[i];
var selector = "ul#options > li input[type='radio'][value='" + answerId + "']";
var elem = $(selector)[0];
elem.parentNode.parentNode.classList.add("disabled-option");
}
});
};
// Quiz reset
scope.reset = function () {
scope.inProgress = false;
scope.score = 0;
}
scope.isGameover = function() {
var gameOverFlag = true;
for (var i = 0; i < Window.game.categories.length; i++) {
var category = Window.game.categories[i];
if (!category.category_completed) {
gameOverFlag = false;
break;
}
}
return gameOverFlag;
}
scope.flashCorrect = function(elem, callback) {
elem.classList.add("correct");
}
// Quiz check answer
scope.checkAnswer = function(event) {
var inputElement = event.target.lastElementChild.lastElementChild
var userAnswerId = inputElement.value;
Window.currentQuestion.userSelectedElement = event.target;
if (userAnswerId === undefined) {
console.log("empty answer?");
return;
}
// POST user answer to API
var postCheckAnswer = {
method: 'POST',
url: config.API_URL + "/games/" + Window.game.token + '/answer',
contentType: 'application/json',
dataType: 'json',
data: { question_id: Window.currentQuestion.id, answer_ids: [userAnswerId] }
}
$http(postCheckAnswer).then(function (response) {
// update categories model
var categoryString = Window.currentQuestion.category;
for (var i = 0; i < Window.game.categories.length; i++) {
var category = Window.game.categories[i];
if (category.name == categoryString) {
category.category_completed = response.data.category_completed;
}
}
// check if game over
var gameOverFlag = scope.isGameover();
// do different things based on API's response on user's answer
if (response.data.response == true) {
Window.currentQuestion.userSelectedElement.classList.add("correct");
} else {
Window.currentQuestion.userSelectedElement.classList.add("wrong");
var answerId = response.data.correct_answers[0].id;
var liElem = $('input[name=answer][value='+answerId+']').parent().parent();
liElem[0].classList.add("correct");
}
// if game is not over
if (!gameOverFlag) {
setTimeout(function(argument) {
scope.nextQuestion();
}, 2000);
} else {
$("#quiz-is-over-alert").toggle();
}
});
scope.answerMode = false;
};
scope.reset();
}
}
});
app.factory('quizFactory', function ($http, config) {
return {
getQuestion: function (category) {
// Get question request
var get_questionsRequest = {
method: 'POST',
url: config.API_URL + "/games/" + Window.game.token + '/new_question/',
contentType: 'application/json',
dataType: 'json',
data: {}
}
$http(get_questionsRequest).then(function (data) {
var quesLevel = data.data.level;
var quesBody = data.data.body;
var quesAnswers = data.data.answers;
Window.currentQuestion.question = quesBody;
Window.currentQuestion.options = quesAnswers;
Window.currentQuestion.answer = 0;
}, function () {
// Get questions failure
//console.log("Error: can't get questions from api");
});
return Window.currentQuestion;
}
};
});
// Get url params method
var getUrlParams = function getUrlParameter(sParam) {
var sPageURL = decodeURIComponent(window.location.search.substring(1)),
sURLVariables = sPageURL.split('&'),
sParameterName,
i;
for (i = 0; i < sURLVariables.length; i++) {
sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] === sParam) {
return sParameterName[1] === undefined ? true : sParameterName[1];
}
}
};
//
// Language translation switch config & controller
//
// Configuration
app.config(function ($translateProvider) {
var dic_EN = {
TITLE: 'Welcome to the Midburn quiz',
DESC: 'In order to be eligible for a ticket for Midburn 2016, you must first show that you care about our culture, by answering 10 questions correctly.',
INFO: 'Wait, what’s Midburn?',
BTN_START_GAME: 'Start Game'
};
var dic_HE = {
TITLE: 'ברוכים הבאות לשאלון מידברן',
DESC: 'על מנת להיות זכאי\\ת לכרטיס למידברן 2016, ראשית את\\ה חייב\\ת להראות שאכפת לך מהתרבות שלנו, על ידי מענה של 10 שאלות בצורה נכונה.',
INFO: 'רגע, מה זה מידברן?',
BTN_START_GAME: 'התחל במשחק'
};
// English conf
$translateProvider.translations('en', dic_EN);
// Hebrew conf
$translateProvider.translations('he', dic_HE);
// Default language
$translateProvider.preferredLanguage('he');
});
// Language Support Controller
app.controller('LangController', function ($scope, $translate) {
// Lang switch method
$scope.changeLanguage = function (key) {
$translate.use(key);
switch (key) {
case 'en':
{
$("body").removeClass("lanHE");
$("body").addClass("lanEN");
break;
}
case 'he':
{
$("body").removeClass("lanEN");
$("body").addClass("lanHE");
break;
}
}
};
});
app.controller('TemplateController', function ($scope) {
// Current Year
$scope.CurrentYear = new Date().getFullYear();
// Theme Name
$scope.ThemeName = "Abracadabra";
// Footer links => {Text: "text", Href: "href", Class: "class"}
$scope.Links = [
{Text: "Help us make it better", Href: "//github.com/Midburn/Midburn-Quiz-Frontend", Class: "link-special"},
{Text: "Midburn Website", Href: "//midburn.org/en/", Class: ""},
{Text: "About The Event", Href: "//midburn.org/en-event/", Class: ""},
{Text: "The Ten Principles", Href: "//midburn.org/en-ten-principles/", Class: ""}
];
});
// )'(