-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththcode.js
More file actions
669 lines (509 loc) · 25 KB
/
thcode.js
File metadata and controls
669 lines (509 loc) · 25 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
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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
//calls treasure hunts from API
//creates a list with all treasure hunts
function getTreasureHunts() {
fetch("https://codecyprus.org/th/api/list")
.then(response => response.json()) //Parse JSON text to JavaScript object
.then(jsonObject => {
do{
var playersName=prompt("Enter Your Name:", "");
} while(playersName !== null && playersName === "")
//ul element that shows treasure hunts list
let thList = document.getElementById("thList");
let treasureHunts = jsonObject.treasureHunts;
for(let i=0; i < treasureHunts.length; i++) {
let listItem = document.createElement("li");
let treasureHuntName = treasureHunts[i].name;
let treasureHuntDesc = treasureHunts[i].description;
let treasureHuntID = treasureHunts[i].uuid;
//listItem.innerHTML ="<div class='container2'>" + "<h4>" +treasureHuntName+ "</h4>"+ "<p>" +treasureHuntDesc+ "</p>" + "<a href='https://codecyprus.org/th/api/start?player="+ playersName +"&app=team3TreasureHunt&treasure-hunt-id="+treasureHuntID+"'>Start</a>" + "</div><br>";
listItem.innerHTML ="<div class='containerList'>" + "<h4>" +treasureHuntName+ "</h4>"+ "<p>" +treasureHuntDesc+ "</p>" + "<a href='question.html?player="+ playersName +"&treasure-hunt-id="+treasureHuntID+"'>Start</a>" + "</div><br>";
thList.appendChild(listItem);
}
});
}
//creates cookies
function createCookie(cookieName,cookieValue,hoursToExpire)
{
var date = new Date();
date.setTime(date.getTime()+(hoursToExpire*60*60*1000));
document.cookie = cookieName + "=" + cookieValue + "; expires=" + date.toGMTString();
}
//accessing the cookies with cookieName
function accessCookie(cookieName)
{
var name = cookieName + "=";
var allCookieArray = document.cookie.split(';');
for(var i=0; i<allCookieArray.length; i++)
{
var temp = allCookieArray[i].trim();
if (temp.indexOf(name)===0)
return temp.substring(name.length,temp.length);
}
return "";
}
function checkForCookie() {
console.log("document");
if (accessCookie("sessionID") !== "") {
var cookieCheck = confirm("A running session found. Do you want to resume it? (Press cancel to start New Session).");
if (cookieCheck === true) {
var nameInTh = accessCookie("username");
let link = accessCookie("sessionID");
window.location.href="returningQuestion.html?player="+ nameInTh +"&treasure-hunt-id="+link;
//getQuestion(link);
} else {
window.location.href = 'app.html';
}
} else {
location.href='app.html';
}
}
//function that starts the th game
function getStartData() {
const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
const playersName = urlParams.get('player');
let treasureHuntID = urlParams.get('treasure-hunt-id');
//console.log(playersName);
//console.log(treasureHuntID);
//example link
//https://codecyprus.org/th/api/start?player=Homer&app=simpsons-app&treasure-hunt-id=ag9nfmNvZGVjeXBydXNvcmdyGQsSDFRyZWFzdXJlSHVudBiAgICAvKGCCgw
fetch("https://codecyprus.org/th/api/start?player=" + playersName + "&app=team3TreasureHunt&treasure-hunt-id=" + treasureHuntID + "")
.then(response => response.json()) //Parse JSON text to JavaScript object
.then(jsonObject => {
let thstatus = jsonObject.status;
let thsession = jsonObject.session;
let totalQuestions = jsonObject.numOfQuestions;
if (thstatus === "OK") {
createCookie("sessionID", thsession, 1);
createCookie("username", playersName, 1);
createCookie("saveGame", "true", 1);
//gets questions from server and shows them to the user
getQuestion(thsession);
} else {
alert(jsonObject.errorMessages);
window.location.replace("app.html");
}
//console.log(thsession);
//console.log(totalQuestions);
});
}
//function that calls the questions from server
function getQuestion(thsession) {
thsession = accessCookie("sessionID");
//example link
//https://codecyprus.org/th/api/question?session=ag9nfmNvZGVjeXBydXNvcmdyFAsSB1Nlc3Npb24YgICAoMa0gQoM
fetch("https://codecyprus.org/th/api/question?session=" +thsession)
.then(response => response.json()) //Parse JSON text to JavaScript object
.then(jsonObject => {
//hides all answer elements
questionButton = document.getElementsByClassName("questionButton");
answerButton = document.getElementsByClassName("answerButton");
for (i = 0; i < questionButton.length; i++) {
questionButton[i].style.display = "none";
}
for (i = 0; i < answerButton.length; i++) {
answerButton[i].style.display = "none";
}
//initializing properties from server
let qStatus = jsonObject.status;
//gets the number of total questions
let totalQuestions = jsonObject.numOfQuestions;
//calculates the final question
let finalQuestion = totalQuestions - 1;
//gets the number of current question
let questionNo = jsonObject.currentQuestionIndex;
questionNo = questionNo + 1; //increase current question number so count starts from 1 rather than 0
//gets question from server
let questionText = jsonObject.questionText;
//gets what type is the question
let questionType = jsonObject.questionType;
//console.log(questionType)
//specifies if question can be skipped
let isSkip = jsonObject.canBeSkipped;
//specifies if the user has completed this treasure hunt
let isComplete = jsonObject.completed;
//testing when treasure hunt ends
//console.log("th is: " + isComplete);
//specifies if question requires location
let isLocation = jsonObject.requiresLocation;
//get element in html to print question
let question = document.getElementById("question");
//get element in html to print question number
let questionNoHTML = document.getElementById("questionNo");
//functionality of HTML elements
//text elements
let submitString = document.getElementById("submitString");
let answerString = document.getElementById("answerString");
//number elements
let submitNo = document.getElementById("submitNo");
let answerNo = document.getElementById("answerNo");
//boolean elements
let boolF = document.getElementById("boolF");
let boolT = document.getElementById("boolT");
//MCQ buttons
let buttonA = document.getElementById("buttonA");
let buttonB = document.getElementById("buttonB");
let buttonC = document.getElementById("buttonC");
let buttonD = document.getElementById("buttonD");
//qr show/hide button
let qrDropdown = document.getElementsByClassName("qrDropdown");
//get element in html to show camera button
let qrBtn = document.getElementById("qrBtn");
//get element in html to show camera switch button
let switchButton = document.getElementById("switch");
//div that shows progress and score (hide when on leaderboard)
let progressInfo = document.getElementById("progressInfo");
//div for answer elements (hide when on leaderboard)
let questionsDiv = document.getElementById("questionsDiv");
//exports question to player
question.innerHTML = questionText;
//exports question number to player
questionNoHTML.innerHTML = "Question: " + questionNo + "/" + totalQuestions;
//initialising the variable which sends the answer to server
let answer;
//checks if treasure hunt is not completed
if (isComplete === false) {
//gets current score
getScore();
//show question text
question.style.display = "block";
//show question number
questionNoHTML.style.display = "inline-block";
//show camera button
qrBtn.style.display = "inline-block";
//show camera switch button
switchButton.style.display = "inline-block";
//checks if question can be skipped
if (isSkip === true) {
skipQuestion(thsession);
}
//checks what type each question is and acts accordingly
if (questionType === "BOOLEAN") {
//shows boolean submit buttons (changing css display to inline)
boolT.style.display = "inline";
boolF.style.display = "inline";
//get answer (using onclick in js)
boolT.onclick = function () {
answer = true;
sendAnswertoServer(thsession, answer, isLocation);
};
//get answer (using onclick in js)
boolF.onclick = function () {
answer = false;
sendAnswertoServer(thsession, answer, isLocation);
};
} else if (questionType === "INTEGER") {
//shows number input and submit button (changing css display to inline)
answerNo.style.display = "inline";
submitNo.style.display = "inline";
//get answer (using onclick in js)
submitNo.onclick = function () {
answer = answerNo.value;
sendAnswertoServer(thsession, answer, isLocation);
answerNo.value = '';
};
} else if (questionType === "NUMERIC") {
//shows number input and submit button (changing css display to inline)
answerNo.style.display = "inline";
submitNo.style.display = "inline";
answer = answerNo.value;
//get answer (using onclick in js)
submitNo.onclick = function () {
answer = answerNo.value;
sendAnswertoServer(thsession, answer, isLocation);
answerNo.value = '';
};
} else if (questionType === "MCQ") {
//shows 4 boolean submit buttons (changing css display to inline)
buttonA.style.display = "inline";
buttonB.style.display = "inline";
buttonC.style.display = "inline";
buttonD.style.display = "inline";
//get answer (using onclick in js)
buttonA.onclick = function () {
answer = 'A';
sendAnswertoServer(thsession, answer, isLocation);
};
//get answer (using onclick in js)
buttonB.onclick = function () {
answer = 'B';
sendAnswertoServer(thsession, answer, isLocation);
};
//get answer (using onclick in js)
buttonC.onclick = function () {
answer = 'C';
sendAnswertoServer(thsession, answer, isLocation);
};
//get answer (using onclick in js)
buttonD.onclick = function () {
answer = 'D';
sendAnswertoServer(thsession, answer, isLocation);
};
} else if (questionType === "TEXT") {
//shows text input and submit button (changing css display to inline)
answerString.style.display = "inline";
submitString.style.display = "inline";
//get answer (using onclick in js)
submitString.onclick = function () {
//if answer requires location then get location before sending answer
answer = answerString.value;
sendAnswertoServer(thsession, answer, isLocation);
answerString.value = '';
};
}
}
//when treasure hunt ends, brings player to leaderboard
else if (isComplete) {
window.location.replace("leaderboard.html");
}
});
}
function sendAnswertoServer(thsession, answer, isLocation) {
if (isLocation === true) {
getLocation(answer);
} else {
fetch("https://codecyprus.org/th/api/answer?session=" + thsession + "&answer=" + answer + "")
.then(response => response.json()) //Parse JSON text to JavaScript object
.then(jsonObject => {
//console.log("answerSubmitted");
//initializing properties from server
let ansStatus = jsonObject.status;
//gets boolean if answer is correct
let isCorrect = jsonObject.correct;
//console.log(isCorrect);
//gets boolean if session has been completed
let isComplete = jsonObject.completed;
//gets message from server
let message = jsonObject.message;
let messageElement = document.getElementById("message");
//shows message according to status (OK/ERROR)
if (ansStatus === "OK") {
messageElement.innerText = message;
messageElement.style.display = "block";
if (isCorrect === true) {
getQuestion(thsession);
}
else if (isCorrect === false) {
getScore();
}
} else if (ansStatus === "ERROR") {
let errorMessages = jsonObject.errorMessages;
for (let i = 0; i < errorMessages.length; i++) {
messageElement.innerText = errorMessages[i];
}
}
});
}
}
function skipQuestion(thsession) {
//initializing button element
let skipButton = document.getElementById("skipButton");
//makes skipButton visible
skipButton.style.display = "inline-block";
let messageElement = document.getElementById("message");
//if skipButton pressed then skips the current question
skipButton.onclick = function () {
var check = confirm("Do you want to skip this question?");
if (check === true) {
//example link
//https://codecyprus.org/th/api/skip?session=ag9nfmNvZGVjeXBydXNvcmdyFAsSB1Nlc3Npb24YgICAoMa0gQoM
fetch("https://codecyprus.org/th/api/skip?session=" + thsession)
.then(response => response.json()) //Parse JSON text to JavaScript object
.then(jsonObject => {
//initializing properties from server
let skipStatus = jsonObject.status;
//specifies if the user has completed this treasure hunt
let isComplete = jsonObject.completed;
//gets message from server
let message = jsonObject.message;
//shows message according to status (OK/ERROR)
if (skipStatus === "OK") {
messageElement.innerText = message;
messageElement.style.display = "block";
getQuestion(thsession);
}
});
}
}
}
//function gets player location (force update)
function getLocation(answer) {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
showPosition(position.coords.latitude, position.coords.longitude, answer);
});
} else {
alert("Geolocation is not supported by your browser.");
}
}
//function sends player's location to server (force update)
function showPosition(lat, long, answer) {
//https://codecyprus.org/th/api/location?session=ag9nfmNvZGVjeXBydXNvcmdyFAsSB1Nlc3Npb24YgICAoMa0gQoM&latitude=34.683646&longitude=33.055391
fetch("https://codecyprus.org/th/api/location?session=" + accessCookie("sessionID") + "&latitude=" + lat + "&longitude=" + long)
.then(response => response.json()) //Parse JSON text to JavaScript object
.then(jsonObject => {
let locStatus = jsonObject.status;
if (locStatus === "OK") {
fetch("https://codecyprus.org/th/api/answer?session=" + accessCookie("sessionID") + "&answer=" + answer + "")
.then(response => response.json()) //Parse JSON text to JavaScript object
.then(jsonObject => {
//console.log("answerSubmitted");
//initializing properties from server
let ansStatus = jsonObject.status;
//gets boolean if answer is correct
let isCorrect = jsonObject.correct;
//console.log(isCorrect);
//gets boolean if session has been completed
let isComplete = jsonObject.completed;
//gets message from server
let message = jsonObject.message;
let messageElement = document.getElementById("message");
//shows message according to status (OK/ERROR)
if (ansStatus === "OK") {
messageElement.innerText = message;
messageElement.style.display = "block";
if (isCorrect === true) {
getQuestion(accessCookie("sessionID"));
}
} else if (ansStatus === "ERROR") {
let errorMessages = jsonObject.errorMessages;
for (let i = 0; i < errorMessages.length; i++) {
messageElement.innerText = errorMessages[i];
}
}
});
}
});
}
//function gets player location (periodic update)
function getPeriodicLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
showPeriodicPosition(position.coords.latitude, position.coords.longitude);
});
} else {
alert("Geolocation is not supported by your browser.");
}
}
//function sends player's location to server (periodic update)
function showPeriodicPosition(lat, long) {
//https://codecyprus.org/th/api/location?session=ag9nfmNvZGVjeXBydXNvcmdyFAsSB1Nlc3Npb24YgICAoMa0gQoM&latitude=34.683646&longitude=33.055391
fetch("https://codecyprus.org/th/api/location?session=" + accessCookie("sessionID") + "&latitude=" + lat + "&longitude=" + long)
.then(response => response.json()) //Parse JSON text to JavaScript object
.then(jsonObject => {
let locStatus = jsonObject.status;
if (locStatus === "OK") {
console.log("here");
}
});
}
//function gets leaderboard
function getLeaderboard() {
let limit = 20;
//example link
//https://codecyprus.org/th/api/leaderboard?session=ag9nfmNvZGVjeXBydXNvcmdyFAsSB1Nlc3Npb24YgICAoMa0gQoM&sorted&limit=10
fetch("https://codecyprus.org/th/api/leaderboard?session=" + accessCookie("sessionID") + "&sorted&limit=" + limit + "")
.then(response => response.json()) //Parse JSON text to JavaScript object
.then(jsonObject => {
//table element that shows teams score
let lbScores = document.getElementById("lbScores");
//gets leaderboard buttons
let toHome = document.getElementById("toHome");
let toPlayAgain = document.getElementById("toPlayAgain");
let toRefresh = document.getElementById("toRefresh");
//gets scoreboard Title
let scoreboardTitle = document.getElementById("scoreboardTitle");
let filler = document.getElementById("filler");
let tableContent = "";
//shows leaderboard elements
scoreboardTitle.style.display = "block";
lbScores.style.display = "block";
toHome.style.display = "block";
toPlayAgain.style.display = "inline-block";
toRefresh.style.display = "inline-block";
filler.style.display="block";
let temp = accessCookie("username");
//gets scores
let leaderboard = jsonObject.leaderboard;
//creating list items and adds scores to ul
for (let i = 0; i < leaderboard.length; i++) {
let teamName = leaderboard[i].player;
let teamScore = leaderboard[i].score;
let teamTime = leaderboard[i].completionTime;
let options = { day: 'numeric', month: 'short', hour: '2-digit', minute: '2-digit',
second: '2-digit' };
let date = new Date(teamTime);
let formattedDate = date.toLocaleDateString("en-UK", options);
let num = i +1;
if (temp === teamName) {
tableContent += "<tr>" + "<b>" + "<td>" + num + "</td>" +
"<td>" + teamName + "</td>" +
"<td>" + teamScore + "</td>" +
"<td>" + formattedDate + "</td>" + "</b>" +
"</tr>";
} else {
tableContent += "<tr>" + "<td>" + num + "</td>" +
"<td>" + teamName + "</td>" +
"<td>" + teamScore + "</td>" +
"<td>" + formattedDate + "</td>" +
"</tr>";
}
}
lbScores.innerHTML += tableContent;
});
}
//function gets leaderboard
function getRank() {
fetch("https://codecyprus.org/th/api/leaderboard?session=" + accessCookie("sessionID") + "&sorted")
.then(response => response.json()) //Parse JSON text to JavaScript object
.then(jsonObject => {
//table element that shows teams score
let userScores = document.getElementById("userScores");
let temp = accessCookie("username");
//rank and final score visible to player
userScores.style.display = "block";
let tableContent = "";
//gets scores
let leaderboard = jsonObject.leaderboard;
//console.log(leaderboard.length)
//creating list items and adds scores to ul
for (let i = 0; i < leaderboard.length; i++) {
let userName = leaderboard[i].player;
let teamScore = leaderboard[i].score;
let teamTime = leaderboard[i].completionTime;
let options = { day: 'numeric', month: 'short', hour: '2-digit', minute: '2-digit',
second: '2-digit' };
let date = new Date(teamTime);
let formattedDate = date.toLocaleDateString("en-UK", options);
let num = i +1;
if (temp === userName) {
tableContent += "<tr>" + "<td>" + num + "</td>" +
"<td>" + userName + "</td>" +
"<td>" + teamScore + "</td>" +
"<td>" + formattedDate + "</td>" +
"</tr>";
}
}
userScores.innerHTML += tableContent;
});
}
//function gets score of current player
function getScore() {
//example link
//https://codecyprus.org/th/api/score?session=ag9nfmNvZGVjeXBydXNvcmdyFAsSB1Nlc3Npb24YgICAoMa0gQoM
fetch("https://codecyprus.org/th/api/score?session=" + accessCookie("sessionID"))
.then(response => response.json()) //Parse JSON text to JavaScript object
.then(jsonObject => {
//gets scores
let scoreStatus = jsonObject.status;
//gets scores
let scoreAPI = jsonObject.score;
//gets a element
let score = document.getElementById("score");
if(scoreStatus ==="OK") {
score.innerHTML = "Score: " + scoreAPI;
//shows score to player
score.style.display = "inline-block";
}
});
}