-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
485 lines (446 loc) · 18.4 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
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
/*jshint esversion: 6 */
var alphabet = "abcdefghijklmnopqrstuvwxyz";
var usedLetters = [];
var wrongLetters = [];
var lettersGuessed = 0;
// for playing on mobile, a button for each letter of the alphabet
var letterButtons = [];
var orientation = "";
var categories = [];
// letterbox object (...class? is there such a thing?)
function letterBox (value, htmlElement) {
this.value = value;
this.guessed = false;
this.htmlElement = htmlElement;
}
letterBox.prototype.markOff = function() {
// guessed this one
this.htmlElement.text(this.value);
// lose the border
// actually, don't
// this.htmlElement.addClass(" borderless");
lettersGuessed += 1;
};
// letter objects, hold letters to be guessed
var letters = [];
// category select (start with fruit)
var category = "";
var possibleWords = [];
var maxGuesses = 6;
var firstLoss = true;
// the word or phrase to guess!
var secretWord = "";
////////////////////////////////////////////
// start the game when the document is ready
$(document).ready(initialize);
function initialize(){
// set up events
$("#categories").on ("change", function(){
category = this.value;
// possibleWords = getCategoryList(category).randomizeOrder();
// get the focus off the dropdown, or it will keep changing on you
$("#hangman").focus();
newGame();
});
$(window).on( "orientationchange", function( event ) {
generateLetterButtons(event.orientation);
});
// "extension method" for randomizing the order of an array
Object.defineProperty(Array.prototype, "randomizeOrder", {
value: function ()
{
for (i = 0; i < this.length; i++){
var placeholder = this[i];
var randomPos = Math.floor(Math.random() * this.length);
this[i] = this[randomPos];
this[randomPos] = placeholder;
}
return this;
},
writable: true,
configurable: true
});
// category select (start with fruit)
category = "fruits & vegetables";
populateCategories();
// possibleWords = getCategoryList(category).slice(0).randomizeOrder();
// turn on keypress events
activateKeyPresses();
if ($(window).width() < $(window).height()){
generateLetterButtons("portrait");
}
else {
generateLetterButtons("normal");
}
newGame();
firstLoss = true;
}
function newGame () {
// clear game parameters
letters = [];
usedLetters = [];
wrongLetters = [];
lettersGuessed = 0;
// clear discards list
$("#discards").text("");
// reset hangman image
$("#hangman").attr("src", "images/hangman0.png");
// reset - hide all the Xes
$(".X").css({"display": "none"});
// un-highlight all letter buttons
$(".letterButton").removeClass("highlighted");
// remove the old secret word(s)
$(".wordContainer").remove();
// get the new secret word
secretWord = getSecretWord(category);
// add secret letters to DOM
generateSecretLetterDivs();
}
function startOver(){
// when you lose
firstLoss = false;
// show what the word was
letters.forEach(element => {
element.markOff();
});
// wait one second, then start over
setTimeout(newGame, 3000);
}
function activateKeyPresses(){
// return keypress control to the document
// it will have been disabled while a dialog box is open
document.onkeyup = keyPress;
document.onkeydown = keyDown;
}
function deactivateKeyPresses(){
document.onkeyup = null;
document.onkeydown = null;
}
function keyDown(event) {
// skip non-letter keys, avoid errors
if (alphabet.indexOf(event.key.toLowerCase()) < 0) return;
// highlight button on keydown
letterButtons[alphabet.indexOf(event.key.toLowerCase())].addClass("highlighted");
}
function keyPress(event) {
// skip non-letter keys, avoid errors
if (alphabet.indexOf(event.key.toLowerCase()) < 0) return;
// un-highlight on keyup
letterButtons[alphabet.indexOf(event.key.toLowerCase())].removeClass("highlighted");
guessLetter(event.key.toLowerCase());
}
function guessLetter (guess){
if (alphabet.indexOf(guess) >= 0) {
// it's a letter, but has it been used already?
if (usedLetters.indexOf(guess) >= 0) {
// can't guess the same letter twice
// ignore
}
else {
// remember this letter has been used
usedLetters.push(guess);
// show the corresponding "X" over the button for this letter
letterButtons[alphabet.indexOf(guess)].children(".X").css({"display":"block"});
// now, is this part of the secret word??
var location = secretWord.toLowerCase().indexOf(guess);
if (location >= 0) {
// yes
// check off all matching letters
while (location >= 0) {
letters[location].markOff();
location = secretWord.toLowerCase().indexOf(guess, location + 1);
}
// did we win??
if (lettersGuessed == letters.length) {
// give just half a second to appreciate the beauty of this success
setTimeout(function (){
openDialog ("You win!! Starting over.", "yay",
dialogButtons([{
text: "ok", function: newGame
}])
);
}, 1000);
return;
}
}
else {
// nope
wrongLetters.push(guess);
$("#discards").text(wrongLetters.join(", "));
// update the image
$("#hangman").attr("src", "images/hangman" + wrongLetters.length + ".png");
// did we lose??
if (wrongLetters.length >= maxGuesses) {
if (wrongLetters.length == 6 && firstLoss){
// yes, but...
console.log("you lost");
openDialog ("You lose!", "loser",
dialogButtons([{
text: "Fine.",
function: startOver
},
{
text: "No, wait! He needs a face!",
function: function () {maxGuesses = 7;}
}])
);
}
else if (wrongLetters.length == 7 && firstLoss){
// come on, one more try!
console.log("you lost again");
openDialog ("That's it! You lost for real!", "superloser",
dialogButtons([{
text: "That's fair.",
function: startOver
}, {
text: "But... What about his hat?",
function: function () {maxGuesses = 8;}
}])
);
}
else if (wrongLetters.length == 8 && firstLoss){
// that's it. no more second chances
openDialog ("Just let it go. It's over.", "so sorry",
dialogButtons([{
text: "Ok, ok.",
function: startOver
}, {
text: "nooooooo",
function: function(){
openDialog ("Starting over now.", "get over it",
dialogButtons([{text: "noooooo", function: startOver}]));
}
}])
);
}
else {
// after the first game, maxguesses is set for good and stays where you left it
openDialog ("Game over.", "awwwww",
dialogButtons([{text: "ok", function: startOver}])
);
}
}
}
}
}
else {
// not a letter (punctuation mark or smth)
// ignore
}
}
// dialog box with arbitrary number of buttons and custom function for each
var msgDiv;
function openDialog(message, title, buttons) {
// no keypress events while dialog is open
// all buttons will have been set to reactivate keypresses on click
deactivateKeyPresses();
// use this for keypresses instead (navigate between buttons using arrow keys)
document.onkeyup =
function(e)
{
if (e.keyCode == 39 || e.keyCode == 40) {
$(".button:focus").next().focus();
}
if (e.keyCode == 37 || e.keyCode == 38) {
$(".button:focus").prev().focus();
}
};
buttons[0].text = (buttons[0].text == undefined) ? "Ok" : buttons[0].text;
title = (title == undefined) ? "The page says:" : title;
msgDiv = $('<div class="dialogBox">');
msgDiv.html(message);
msgDiv.attr('title', title);
msgDiv.dialog({
autoOpen: true,
modal: true,
closeOnEscape: false,
// no close option (have to click one of the buttons)
open: function(event, ui) {
$(".ui-dialog-titlebar-close", ui.dialog | ui).hide();
},
draggable: true,
resizable: true,
buttons: buttons
});
}
// make a list of button objects which can be passed to openDialog function
// adding $(this).dialog("close") msgDiv.remove(), and activateKeyPresses()
// which should happen no matter what else
function dialogButtons (buttons){
// function expects an array of button objects:
// [{text: "", function: function()}, ...]
return buttons.map (function(button) {
// for each button, return a new button which is the same,
// except its function has been wrapped in another function
// which includes these three required actions
// and adds a button class
return {
text: button.text,
class: "button",
click: function() {
// close dialog box and remove div
$(this).dialog("close");
msgDiv.remove();
// user-defined custom function
if (button.function != null) button.function();
// return keypress control to document
activateKeyPresses();
}
};
});
}
function generateLetterButtons(layout){
// generate letter buttons from scratch
letterButtons = [];
$("#letterButtonWindow").empty();
// keyboard layout for portrait orientation
if (layout == "portrait"){
alphabet = "qwertyuiopasdfghjklzxcvbnm";
}
// alphabetical layout for landscape-oriented device (which presumably has a keyboard)
else {
alphabet = "abcdefghijklmnopqrstuvwxyz";
}
// generate the buttons
[...alphabet].forEach(letter => {
var letterButton = $('<div class="letterBox letterButton"></div>');
// add the letter, and an invisible "X" which will show once the letter is used
var letterContent = $('<div class="innerLetter">');
letterContent.text(letter);
var xBox = $('<div class="X">');
xBox.text("X");
// add both to the button
letterButton.append(letterContent);
letterButton.append(xBox);
// add click event
letterButton.mouseup(function(){guessLetter(letter);});
// add button to window
$("#letterButtonWindow").append(letterButton);
// alter layout for keyboard
if (layout == "portrait" && (letter == "l" || letter == "p")) {
$("#letterButtonWindow").append($("<br>"));
}
// add to array
letterButtons.push(letterButton);
});
// mark off ones which have been guessed already
usedLetters.forEach(letter => {
// show the corresponding "X" over the button for this letter
letterButtons[alphabet.indexOf(letter)].children(".X").css({"display": "block"});
});
}
function generateSecretLetterDivs() {
// make a container for each word (so they can go on separate lines if need be)
var container = $('<div class="wordContainer"></div>');
// make new boxes for letters
for (i = 0; i < secretWord.length; i++) {
// create the letterbox element
var letterDiv = $('<div class="letterBox"> </div>');
// create entry for letters object array
letters.push (new letterBox(secretWord[i], letterDiv));
// if it's not a space, append to word container
if (letters[i].value != " "){
container.append(letterDiv);
// give non-alphabetical characters for free
if (alphabet.indexOf(letters[i].value.toLowerCase()) < 0) {
letters[i].markOff();
// don't underline apostrophes, commas and such
letterDiv.addClass("borderless");
}
}
// if it is a space, start a new word container
else {
// won't have to guess this "letter"
letters[i].markOff();
// add word container to word window, and start a new container
$("#wordWindow").append(container);
// new container
container = $('<div class="wordContainer"></div>');
}
}
// add final container to word window
$("#wordWindow").append(container);
}
function getSecretWord(category) {
// take the last element off the word list
// since the list has already been randomized, this means that you won't see the same word twice
// until all options have been exhausted (or you switch categories and back again)
if (this.prevCategory != category || possibleWords.length == 0) {
// re-get the list (start over, new random order)
this.prevCategory = category;
possibleWords = getCategoryList(category).slice(0).randomizeOrder();
// never show the same word twice in a row
if (possibleWords[possibleWords.length-1] == secretWord) {
var placeholder = possibleWords[possibleWords.length-1];
possibleWords[possibleWords.length-1] = possibleWords[0];
possibleWords[0] = placeholder;
}
}
return possibleWords.pop();
}
function populateCategories() {
categories = [{
"name": "fruits & vegetables",
"list": ["watermelon", "pineapple", "grapefruit", "zucchini", "pumpkin",
"bell pepper", "brussels sprouts", "bing cherry", "canteloupe", "green onion",
"avocado", "tomatillo", "asparagus", "broccoli", "banana", "horse raddish",
"carrot", "raspberry", "potato", "green bean", "mango", "eggplant", "celery",
"orange", "blueberry", "potato", "nectarine", "asparagus", "cabbage"]
}, {
"name": "factory products",
"list": ["shopping carts", "happy meal toys", "Ikea furniture", "cell phones",
"shoes", "paperclips", "ball point pens", "Bic lighters", "dollar bills",
"legos", "batteries", "staplers", "aluminum foil", "thumb tacks", "tempered glass",
"car parts", "cheap, kitschy art", "balloons", "silverware"]
}, {
"name": "everyone dies™",
"list": ["nuclear missiles", "Death Star", "meteor impact", "zombie plague",
"ice nine", "doomsday machine", "supernova", "alien invasion", "world war three",
"apocalypse", "mass extinction", "global pandemic", "black hole", "supervolcano"]
}, {
"name": "bands of the 1900s",
"list": ["Led Zeppelin", "Smashing Pumpkins", "Red Hot Chili Peppers", "Black Sabbath",
"Nirvana", "White Stripes", "Aerosmith", "The Beatles", "The Supremes", "Jackson Five",
"Weezer", "The Eagles", "The Police", "The Beach Boys", "Sublime", "Metallica",
"Rolling Stones", "Grateful Dead", "Wutang Clan", "Nickleback", "Smashmouth"]
}, {
"name": "surveying tools",
"list": ["contour map", "theodolite", "compass", "transit", "laser level",
"sextant", "measuring chain", "rangefinder", "marker flag", "satellite imagery"]
}, {
"name": "electrical implements",
"list": ["microwave", "toaster oven", "refrigerator", "stove", "blender",
"washing machine", "dryer", "space heater", "electric kettle", "coffee maker",
"lamp", "kitchen timer", "vacuum cleaner", "air conditioner", "humidifier",
"oscillating fan", "hot plate", "movie projector", "stereo", "laser pointer"]
}, {
"name": "invertebrates",
"list": ["worm", "jellyfish", "sea cucumber", "octopus", "squid", "centipede",
"spider", "cuttlefish", "grasshopper", "barnacles", "leech", "dragonfly",
"tapeworm", "tarantula", "ant", "lobster", "crab", "mussel", "snail",
"horseshoe crab", "sponge", "honeybee", "scarab", "snow flea", "earwig"]
}, {
"name": "extinct mammals",
"list": ["woolly mammoth", "mastodon", "saber tooth tiger", "giant sloth",
"stellar's sea cow", "neanderthal", "dire wolf", "cave bear", "paracera- therium",
"thylacine", "Irish elk", "glyptodon", "short-faced bear", "quagga", "aurochs",
"American lion", "wooly rhinoceros", "bulldog rat"]
}, {
"name": "nation-states",
"list": ["Argentina", "Belgium", "Denmark", "Ethiopia", "Finland", "Guatemala", "Honduras",
"Indonesia", "Jordan", "Kazakhstan", "Luxembourg", "Malasia", "Mexico", "Monaco", "Norway",
"Rwanda", "Switzerland", "Thailand", "Uganda", "Uruguay", "Venezuela", "Zimbabwe",
"Hungary", "South Africa", "The Gambia", "Canada", "Brazil", "Jamaica",
"Russia", "Vietnam", "Saudi Arabia", "Italy", "Egypt", "Cambodia",
"Australia", "New Zealand", "Costa Rica", "Nigeria", "Bhutan", "Pakistan",
"Serbia", "Chzech Republic", "Algeria", "Mozambique", "Madagascar"]
}];
// $("#categories").empty();
categories.forEach(function(category){
$("#categories").append($('<option value="' + category.name + '">' + category.name + '</option>'));
});
}
function getCategoryList(category) {
// return the list for the matching category
return categories.filter(item => {return item.name === category;})[0].list;
}