-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
232 lines (212 loc) · 8.27 KB
/
main.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
/**
* Austin Jenchi
* CSE 154 19sp AQ
*
*/
(function() {
"use strict";
const URL_AUTH = "auth.php";
const URL_GAME = "game.php";
const URL_SCORES = "scores.php";
const CLASS_HIDDEN = "hidden";
let uid = undefined;
window.addEventListener("load", init);
/**
* Runs on page load. Registers event listeners with the authentication form, as well
* as sets up the listeners for the elements for the game. These however should not be
* functional on page load since they are hidden by default.
*/
function init() {
id("form-login").addEventListener("submit", handleFormLogin);
id("form-signup").addEventListener("submit", handleFormSignup);
qsa("#view-game > button").forEach(btn => btn.addEventListener("click", makeGuess));
id("btn-again").addEventListener("click", startGame);
id("btn-submit").addEventListener("click", submitScore);
id("btn-view").addEventListener("click", viewHighScores);
}
/**
* @param {HTMLFormEvent} event - The event from submitting the form
*/
function handleFormLogin(event) {
// this is the form element
event.preventDefault();
let body = new FormData(this);
body.append("mode", "login");
fetch(URL_AUTH, { method: "POST", body: body })
.then(checkStatus)
.then(resp => uid = resp)
.then(switchViewGame)
.catch(() => showError(qs("#view-auth .error-text"),
"There was an issue logging in... are you sure you are registered?"));
}
/**
* @param {HTMLFormEvent} event - The event from submitting the form
*/
function handleFormSignup(event) {
// this is the form element
event.preventDefault();
let body = new FormData(this);
body.append("mode", "signup");
fetch(URL_AUTH, { method: "POST", body: body })
.then(checkStatus)
.then(resp => uid = resp)
.then(switchViewGame)
.catch(() => showError(qs("#view-auth .error-text"),
"There was an issue registering... is your username unique?"));
}
/**
* Switches the view from the auth form to the game. This should only be run once. This
* assumes we have an authed user and that uid is no longer undefined.
*/
function switchViewGame() {
id("view-auth").classList.add(CLASS_HIDDEN);
id("view-game").classList.remove(CLASS_HIDDEN);
startGame();
}
/**
* Starts a new round. Resets the number of correct guesses to 0, and enables the game
* buttons. Also hides the game over section.
*/
function startGame() {
qsa("#view-game > button").forEach(btn => btn.disabled = false);
id("guessed").innerText = 0;
id("game-over").classList.add(CLASS_HIDDEN);
qs("#game-over ol").innerHTML = "";
let btnSubmit = id("btn-submit");
btnSubmit.innerText = "Submit Score";
btnSubmit.disabled = false;
}
/**
* Makes a guess. This should be called as an event listener of a guess button. The button
* should have an id matching "btn-{color name}". That color name is sent to the backend, which
* makes a decision on whether it matches its (random) choice and returns "true"/"false" back
* in response. Then the UI is updated with either another correct guess counted or the game
* being over.
*/
function makeGuess() {
// this is a guess button element
let color = this.id.substring(this.id.indexOf("-") + 1);
fetch(URL_GAME + "?guess=" + color)
.then(checkStatus)
.then(resp => resp === "true")
.then(handleGuess)
.then(() => clearError(qs("#view-game .error-text")))
.catch(() => showError(qs("#view-game .error-text"),
"There was an issue making that guess... try again?"));
}
/**
* Handles a response from the game API. Given a boolean whether or not the game API guessed
* the same as the player, update the UI. Either another correct guess is added to the score
* or the game over routine begins.
*
* @param {boolean} guessCorrect - Whether or not the API found the guess to be correct
*/
function handleGuess(guessCorrect) {
if (guessCorrect) {
let ele = id("guessed");
ele.innerText = parseInt(ele.innerText) + 1;
} else {
qsa("#view-game > button").forEach(btn => btn.disabled = true);
id("game-over").classList.remove(CLASS_HIDDEN);
}
}
/**
* Show the given error in the given element.
*
* @param {HTMLElement} ele - The element to show the error in
* @param {strung} msg - The error message to show
*/
function showError(ele, msg) {
ele.innerText = msg;
}
/**
* Clears the error of the given element, effectively hiding it.
*
* @param {HTMLElement} ele - The element to clear the error of
*/
function clearError(ele) {
ele.innerText = "";
}
/**
* Gets the score from the counter on the page and sends it to the API to save in the database.
*/
function submitScore() {
let body = new FormData();
body.append("uid", uid);
body.append("score", parseInt(id("guessed").innerText));
fetch(URL_SCORES, { method: "POST", body: body })
.then(checkStatus)
.then(() => {
let btnSubmit = id("btn-submit");
btnSubmit.innerText = "Submitted!";
btnSubmit.disabled = true;
})
.then(() => clearError(qs("#view-game .error-text")))
.catch(() => showError(qs("#view-game .error-text"),
"There was an issue submitting your score... try again?"));
}
/**
* Fetches the high scores from the API to generate the scoreboard elements.
*/
function viewHighScores() {
fetch(URL_SCORES)
.then(checkStatus)
.then(JSON.parse)
.then(generateScoreboard)
.then(() => clearError(qs("#view-game .error-text")))
.catch(() => showError(qs("#view-game .error-text"),
"There was an issue getting the scoreboard... try again?"));
}
/**
* Generates list elements from the scores from the API. Assumes that the scores are in
* descending order.
*
* @param {object} scores - The parsed scores object from the API
*/
function generateScoreboard(scores) {
let parent = qs("#game-over ol");
parent.innerHTML = "";
for (let score of scores) {
let ele = document.createElement("li");
ele.innerText = score.uname + " - " + score.score;
parent.appendChild(ele);
}
}
/* CSE 154 HELPER FUNCTIONS */
/**
* Returns the DOM element with the given id.
*
* @param {string} id - The id to search for
* @returns {HTMLElement} The element with that id
*/
const id = id => document.getElementById(id);
/**
* Returns the first element in the DOM tree that matches the given selector.
*
* @param {string} selector - The selector to search with
* @returns {HTMLElement} The first element in the DOM that matches that selector
*/
const qs = selector => document.querySelector(selector);
/**
* Returns all the elements in the DOM that match the given selector.
*
* @param {string} selector - The selector to search with
* @returns {HTMLElement[]} All elements in the DOM that match that selector
*/
const qsa = selector => document.querySelectorAll(selector);
/**
* Helper function to return the response's result text if successful, otherwise
* returns the rejected Promise result with an error status and corresponding text
*
* @param {object} response - response to check for success/error
* @returns {object} - valid result text if response was successful, otherwise rejected
* Promise result
*/
function checkStatus(response) {
if (response.status >= 200 && response.status < 300) {
return response.text();
} else {
return Promise.reject(new Error(response.status + ": " + response.statusText));
}
}
})();