-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
390 lines (313 loc) · 10.5 KB
/
script.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
/* Nathan Kanigsberg
Project 1 - Juno College JavaScript Course
August 3, 2020 */
/** @namespace */
const game = {};
/** @type {array} board array */
game.board = [];
/** @type {JQuery} jQuery gameBoard object */
game.$board = $('.game-board');
/** @type {array} game-piece colours */
game.colours = ['red', 'green', 'blue', 'yellow', 'orange', 'purple'];
/** @type {array} the objective to match */
game.objective = [];
/** @type {number} the active row */
game.activeRow = 11; //start with bottom row
/**
* Game pieces that player will be interacting with
*/
class gamePiece {
/**
* @param {number} x - x coordinate
* @param {number} y - y coordinate
* @param {string} colour - the colour of the gamepiece
* @param {boolean} active - whether clickable or not
*/
constructor(x, y, colour, active) {
this.x = x;
this.y = y;
this.colour = colour;
this.active = active;
}
}
/**
* Builds the game board
* @param {array} board - the board array
*/
game.buildBoard = function(board) {
// build rows
for (let y = 0; y < 12; y++) {
board.push([]); //push row array
game.$board.append(`<div class="row row-${y} inactive"></div>`); //append row to html
// build columns
for (let x = 0; x < 5; x++) {
// first four columns - add game-pieces
if (x < 4) {
/** @type {gamePiece} a new gamepiece at the current coordinates */
const newPiece = new gamePiece(x, y, 'empty', false);
board[y].push(newPiece); //push gamePiece to current row array
// append gamePiece to html
game.$board.find(`div.row-${y}`).append(`<span class="game-piece ${newPiece.colour}" x="${newPiece.x}" y="${newPiece.y}"></span>`);
// last column - add score-pip container
} else {
game.$board.find(`div.row-${y}`).append(`<span class="score" x="${x}" y="${y}"></span>`);
}
}
// add score pips to container
for (let i = 0; i < 4; i++) {
$(`.score[y="${y}"]`).append(`<span class="score-pip score-pip-${i} empty"></span>`);
}
}
};
/** Generate the objective */
game.generateObjective = function() {
for (let i = 0; i < 4; i++) {
game.objective[i] = Math.floor(Math.random() * game.colours.length);
}
};
/** Remove warnings */
game.removeWarnings = function() {
// only do if warning exists
if ($('p.warning').length) {
$('div.game-container').find('p.warning').remove();
$('div.game-container').css('height', '670px'); //restore default height
}
};
/** Change button to restart */
game.buttonRestart = function(button) {
$(`button.${button}`).off('click').text('New Game').css('background', '#67b904').on('click', function() {
location.reload();
});
};
/** Listen for user input and change color of corresponding piece */
game.changeColour = function() {
/** @type {array} the possible colours of the gamepiece */
const colours = game.colours.slice();
colours.unshift('empty'); // add 'empty' to start of the colours array
/** change to next colour when clicked */
game.$board.on('click', 'span.game-piece', function() {
// remove warnings
game.removeWarnings();
/** @type {number} the current column */
const column = parseInt($(this).attr('x'));
/** @type {number} the current row */
const row = parseInt($(this).attr('y'));
/**
* Get the current gamepiece
* @return {gamePiece} The current game piece
*/
const getCurrentGamePiece = function () {
const arrayRow = game.board[row];
return arrayRow[column];
};
/** @type {gamePiece} the currently selected gamepiece */
const currentGamePiece = getCurrentGamePiece();
/** only change colour if piece is active */
if (currentGamePiece.active === true) {
/** @type {number} index of current colour */
const colourIndex = colours.indexOf(currentGamePiece.colour);
// console.log(colourIndex);
/** @type {number} the new colour index */
const newIndex = (colourIndex + 1) % colours.length; // use modulo to wrap to beginning of array
/** change the colour */
currentGamePiece.colour = colours[newIndex];
$(this).removeClass(`${colours[colourIndex]}`).addClass(`${colours[newIndex]}`);
};
});
};
/**
* Activates the row passed as an argument
* @param {number} row - the row to activate
*/
game.activateRow = function(row) {
game.board[row].forEach(element => element.active = true); //activate each gamePiece
$(`div.row-${row}`).removeClass('inactive'); //remove 'inactive' class from html piece
};
/**
* Deactivates the row passed as an argument
* @param {number} row - the row to deactivate
*/
game.deactivateRow = function(row) {
game.board[row].forEach(element => element.active = false); //deactivate each gamePiece
$(`div.row-${row}`).addClass('inactive'); //add 'inactive' class from html piece
};
/**
* Checks row for empty pieces
* @param {array} row - the row to search
* @returns {boolean} true if any empty pieces are found, false otherwise
*/
game.emptyPieces = function(row) {
for (let i in row) {
if (row[i].colour === 'empty') return true;
}
return false;
};
/**
* Checks rows and displays scores when button pressed
*/
game.checkRow = function() {
/** @type {JQuery} Submit button */
const $button = $('button.submit');
/** on button click evaluate score and move to next row */
$button.on('click', function() {
game.removeWarnings(); // remove previous warnings
/** @type {array} - current row array */
const currentRow = game.board[game.activeRow];
// if not on the last row
if (game.activeRow > 0) {
// if each element has a colour (isn't empty)
if (!game.emptyPieces(currentRow)) {
//SCORE AND DISPLAY PEGS
/** @type {array} a copy of the objectives that can be manipulated */
let objectiveClone = game.objective.slice();
/** @type {array} the code represented on this row */
let rowCode = [];
/** @type {number} number of pieces with correct colour */
let numCorrectColour = 0;
/** @type {number} number of pieces with correct location */
let numCorrectLocation = 0;
/** @type {boolean} whether or not win condition is met */
let win = false;
// convert colours to code string (rowCode)
for (let i in currentRow) {
const code = game.colours.indexOf(`${currentRow[i].colour}`);
rowCode[i] = code;
};
// determine number of score pegs for correct location (& colour)
for (let i in rowCode) {
if (objectiveClone[i] === rowCode[i]) {
objectiveClone[i] = 7; //number outside of range to match, so won't allow for duplicate matching (eliminates it from future match attempts)
rowCode[i] = 8; //different number so they won't match each other
numCorrectLocation++;
numCorrectColour++;
};
};
// determine number of score pegs for correct colour only
for (let i in rowCode) {
if (objectiveClone.includes(rowCode[i])) {
const firstMatch = objectiveClone.indexOf(rowCode[i]);
objectiveClone[firstMatch] = 7; //number outside of range to match, so won't allow for duplicate matching
numCorrectColour++;
};
}
// if all four correct, set win condition
if (numCorrectLocation === 4) {
win = true;
}
// loop through score pips and colour based on score
for (let i = 0; i < 4; i++) {
if (numCorrectLocation > 0) {
$(`span.score[y="${game.activeRow}"] .score-pip-${i}`).addClass('correctLocation');
numCorrectLocation--;
numCorrectColour--;
} else if (numCorrectColour > 0) {
$(`span.score[y="${game.activeRow}"] .score-pip-${i}`).addClass('correctColour');
numCorrectColour--;
};
};
// deactivate current row
game.deactivateRow(game.activeRow);
// if win condition is set
if (win) {
// win the game
game.finish('win');
} else {
// activate next row
game.activateRow(game.activeRow - 1);
game.activeRow--;
}
// if there is an empty gamepiece
} else {
// append warning to container - choose all pegs
$('div.game-container').append('<p class="warning">Empty pegs!</p>').css('height', '+=40');
}
// if on last row
} else {
// game over man
game.finish('lose');
}
});
};
/**
* Show the solution to the player
*/
game.showSolution = function() {
// only if solution isn't shown already (prevents duplicate html)
if (!$('div.solution').length) {
// append solution to html
$('div.give-up-container').append(`<div class="give-up">
<h3>Solution:</h3>
<div class="solution">
<span class="game-piece ${game.colours[game.objective[0]]}"></span>
<span class="game-piece ${game.colours[game.objective[1]]}"></span>
<span class="game-piece ${game.colours[game.objective[2]]}"></span>
<span class="game-piece ${game.colours[game.objective[3]]}"></span>
</div>
</div>`);
// enlarge container to fit
$('div.give-up-container').css('height', '+=100');
}
}
/**
* Finishes the game
* @param {string} condition - 'win' or 'lose' condition
*/
game.finish = function(condition) {
// if player wins the game
if (condition === 'win') {
$('div.row').removeClass('inactive').addClass('win');
$(`div.row-${game.activeRow}`).removeClass('win').addClass('win-row');
$('div.game-container').prepend('<p class="game-over game-over-win">You Win!<p>');
// if player loses the game
} else if (condition === 'lose') {
game.deactivateRow(game.activeRow);
$('div.row').removeClass('inactive').addClass('lose');
$('div.game-container').prepend('<p class="game-over game-over-lose">You Lose!<p>');
}
//show solution
game.showSolution();
//increase size of game-container to fit game-over message
$('div.game-container').css('height', '+=50');
// change buttons to restart
game.buttonRestart('give-up');
game.buttonRestart('submit');
};
/**
* Listen for give up button click and end game, display solution
*/
game.giveUp = function() {
$('button.give-up').on('click', function() {
// change button to restart
game.buttonRestart('give-up');
// show solution
game.showSolution();
});
// move container below gameboard at small screen sizes on load (aesthetic choice)
if ($(document).width() < 587)
$('div.give-up-container').insertAfter('div.game-container');
// move container below gameboard at small screen sizes dynamically
$(window).on('resize', function() {
if ($(document).width() < 587) {
$('div.give-up-container').insertAfter('div.game-container');
} else {
$('div.give-up-container').insertAfter('div.instructions-container');
}
});
};
/**
* Initialize the game
*/
game.init = function() {
game.buildBoard(game.board);
game.generateObjective();
game.changeColour();
game.activateRow(game.activeRow);
game.checkRow();
game.giveUp();
};
/**
* Document Ready
*/
$(document).ready(function(){
game.init();
});