-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
377 lines (303 loc) · 12.5 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
// Ensures the browser executes the following code in strict mode
"use strict";
/**
* The Hexxed jQuery plugin generates a fully-functioning, self-contained color
* guessing game.
* @return {jQuery} The jQuery object for chained calls
* @author Anjin Lima <[email protected]>
* @author Tristan Villamil <[email protected]>
* @autor Justin Etzine <[email protected]>
*/
$.fn.hexxed = function(settings) {
/**
* Input parameter validation:
* Configures settings object. If the user excluded one, it gets defined
* with default values. Otherwise, it ensures the values are legal.
*/
if(!settings) {
// Settings object not passed as argument, generate one.
settings = {
difficulty: 5,
turns: 10
};
} else {
// Settings object passed, must verify settings as valid
// Check difficulty setting (0-10)
if(!settings.difficulty) {
settings.difficulty = 5;
} else if(settings.difficulty > 10) {
settings.difficulty = 10;
} else if(settings.difficulty < 0) {
settings.difficulty = 0;
}
// Check difficulty setting (1+)
if(!settings.turns) {
settins.turns = 10;
} else if(settings.turns < 1) {
settings.turns = 1;
}
}
/**
* Contains the color that user is trying to guess
* @type {Object}
*/
var color = { red: 0, green: 0, blue: 0 };
/**
* Contains the user's guess
* @type {Object}
*/
var guess = { red: 127, green: 127, blue: 127 };
/**
* Logs the time (in milliseconds) when a color is loaded, so we can
* determine the time elapsed when calculating score.
*/
var time_at_load = Date.now();
/**
* Keeps track of of how many points are earned across all turns played
*/
var total_score = 0;
/**
* Tracks how many turns remain before end of game is invoked.
*/
var turns_remaining = settings.turns;
/**
* Creates a new jQuery reference to the game element for DOM manipulation
*/
var gameElement = this;
/**
* Serves as the reusable object that's passed as an argument when creating
* the sliders.
* @type {Object}
*/
var sliderObject = {
min:0,
max:255,
value: 127,
slide: updateGuess,
stop: updateGuess
};
/**
* This function is applied to the slide and stop arguments of the slider
* jquery objects for the Hexxed game, and keeps the variables up to date
* @param {Object} event
* @param {Object} ui
*/
function updateGuess(event, ui) {
// determine which slider called the function
var sliderColor = event.target.id;
// get the value from that slider
var value = $('#' + sliderColor).slider('option', 'value');
// Update the respective numerical indicator with the value
$('#' + sliderColor + 'Val').html(value);
// Update the guess object with the value
guess[sliderColor] = parseInt(value);
// Prepare the guess colors in CSS RGB format for applying to the div
var color_string = 'rgb(' + guess.red + ',' +
guess.green + ',' +
guess.blue + ')';
// Apply the new guess to the #guess div.
$('#guess').css('background', color_string);
}
/**
* Generates a new color, adds it to the designated html element, and
* updates the color object.
*/
function newColor() {
//get random color RGB components
color.red = Math.floor(Math.random()*255);
color.blue = Math.floor(Math.random()*255);
color.green = Math.floor(Math.random()*255);
// Prepare the guess colors in CSS RGB format for applying to the div
var color_string = 'rgb(' + color.red + ',' +
color.green + ',' +
color.blue + ')';
// Apply the new color to the #color div.
$('#color').css('background', color_string);
// Log the current time in milliseconds, used in score calculations
time_at_load = Date.now();
}
/**
* Called by the start over button after ending the game.
*/
function reset() {
// remove the elements available to the user at game over
$('#gameOver').remove();
// show the game board
gameElement.children().show();
// generate a new color
// done after showing game board because newColor resets the timer
newColor();
// reset the score counter
total_score = 0;
// restore turns as defined in settings
turns_remaining = settings.turns;
// clear results, as there wouldn't be any
$('#result').text("");
}
/**
* Checks the user's guess against the designated color and generates a
* score based on a number of factors
*/
function check() {
// Determine milliseconds elapsed since the color was loaded
var milliseconds_taken = Date.now() - time_at_load;
// Calculate the percents that the user was off
var percents = {
red: (Math.abs(color.red - guess.red)/255)*100,
green: (Math.abs(color.green - guess.green)/255)*100,
blue: (Math.abs(color.blue - guess.blue)/255)*100
};
// Calculate the average (overall) percent off
var percent_off = (percents.red + percents.green + percents.blue)/3;
// Calculate the turn's score
var turn_score = ((15 - settings.difficulty - percent_off) /
(15 - settings.difficulty)) *
(15000 - milliseconds_taken);
// If positive, round to 2 decimals. If negative, set to 0.
turn_score = (turn_score > 0) ? (Math.round(turn_score*100)/100) : 0;
// Add the score for the turn to the running total
total_score += turn_score;
total_score = (Math.round(total_score*100)/100)
// decrease the turn count
turns_remaining--;
// check if no turns remain
if(turns_remaining > 0) {
newColor();
// Display the current statistics
$('#result').html("Last Score: " + turn_score +
"; Total Score: " + total_score +
"; Turns Left: " + turns_remaining);
} else {
// create a new div element to display game over info for the user
// wrapped in a div for easy removing on game reset
var gameOver = $('<div>').attr('id', 'gameOver');
// Add a header to denote game over
gameOver.append($("<h2>").text("Game Over!"));
// Show the final score from the game
gameOver.append($("<p>").text("Final Score: " + total_score));
// Create the input for players to input a name for their high score
var playerNameInput = $('<input>').attr('placeholder', 'Your name');
// Add the input to the page with an ID for easy value access
gameOver.append(playerNameInput.attr('id', 'hsName'));
// Create a submit button to send the score to the high scores array
var submit = $('<button>').text("Submit High Score!");
submit = submit.attr("type", "button").attr("id","hsSubmit");
// Show the button
gameOver.append(submit.click(submitHighscore));
// Create a try again buton to allow users to restart the game over
var againButton = $("<button>").text("Try Again!");
// Show the button
gameOver.append(againButton.attr("type", "button").click(reset));
// Hide the game so they can't keep playing
gameElement.children().hide();
// Add the game over elements
gameElement.append(gameOver);
}
}
/**
* @param {string} playerName
*/
function submitHighscore() {
// keep track of where in local storage the scores will be held
// using a variable to ensure consistency among all calls
var HEXXED_STORAGE_NAME = '_hexxedHighScores';
// get the player's information from the designated input element
var playerName = $('#hsName').val();
// check to make sure the user included their name, otherwise terminate
if(playerName === "") {
alert("You need to enter your name to submit a high score!");
return;
}
// Disable the input and submit to prevent repeat submissions
$('#hsName').prop('disabled', true);
$('#hsSubmit').prop('disabled', true);
// compile the information to be inputted
var dataForSubmission = {
name: playerName,
difficulty: settings.difficulty,
turns: settings.turns,
score: total_score,
timestamp: new Date().toLocaleString()
};
// ensure the browser has the capacity for local storage
if(window.localStorage !== undefined) {
// query local storage for any data currently present
var data = localStorage.getItem(HEXXED_STORAGE_NAME);
console.log(data);
// Determine if to add or create a high scores JSON array
if(data === null || data === undefined || data === "") {
console.log('test');
// no exisiting data, create a new array with the one score
data = [dataForSubmission];
} else {
// exisiting data, parse the exisiting and add the new
data = JSON.parse(data);
console.log(data);
data.push(dataForSubmission);
}
// convert the JSON back to a string
data = JSON.stringify(data);
// push the newly modified / created data to local storage.
localStorage.setItem(HEXXED_STORAGE_NAME, data);
// Notify the user that the score was successfully saved!
$('#hsName').remove();
$('#hsSubmit').remove();
$('#gameOver').append($('<h3>').text("Submitted!"));
} else {
// otherwise, notify the user that local storage isn't allowed
$('#hsName').remove();
$('#hsSubmit').remove();
$('#gameOver').append($('<h3>').text("Sorry, your browser does not support local storage."));
}
}
// ==================================
// DOM Preparation
// Adding the game elements to the HTML
// ==================================
// Display a header that says 'Hexxed'
this.append($('<h1>').text("Hexxed"));
// Display the color user is trying to match
this.append($('<div>').attr('id', 'color').text("Your Goal"));
// Display the user's current guess color
this.append($('<div>').attr('id', 'guess').text("Your Guess"));
// Clears the floats
this.append($('<hr>'));
// Button that generates new color
var newColorBtn = $('<button>').attr('type','button').attr('id', 'new');
// Adds the button to the DOM with text and an action on click
this.append(newColorBtn.text('Try a different color').click(newColor));
// The sliders the user can manipulate
// Red slider
this.append($('<div>').attr('id', 'red').slider(sliderObject));
// Green slider
this.append($('<div>').attr('id', 'green').slider(sliderObject));
// Blue slider
this.append($('<div>').attr('id', 'blue').slider(sliderObject));
// Current value indicators
var redVal = $('<span>').attr('id', 'redVal').text(guess.red),
greenVal = $('<span>').attr('id', 'greenVal').text(guess.green),
blueVal = $('<span>').attr('id', 'blueVal').text(guess.blue),
// The wrapping <p> to store the value indicators
currentVals = $('<p>').attr('id', 'currentVals');
// append the indicators to the <p> with helpful text descriptions
currentVals.append('Current: Red ').append(redVal);
currentVals.append('; Green ').append(greenVal);
currentVals.append('; Blue ').append(blueVal);
// add the value indicator p to the DOM
this.append(currentVals);
// Submit button
var submitBtn = $('<button>').attr('type', 'button').attr('id', 'submit');
// Add the button to the DOM with text and a function to complete on click
this.append(submitBtn.text('Check my Color!').click(check));
// Result area
this.append($('<div>').attr('id', 'result'));
// Generate first color
newColor();
// Returns the jQuery object for chained jQuery calls
return this;
};
$(document).ready(function() {
// Create a game instance in the div entitled hexxed.
$('#hexxed').hexxed();
//$('#hexxed').hexxed({ turns: 10, difficulty: 5 });
});