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
|
(function(){
'use strict';
// Extend the element method
Element.prototype.wordSearch = function(settings) {
return new WordSearch(this, settings);
}
/**
* Word seach
*
* @param {Element} wrapWl the game's wrap element
* @param {Array} settings
* constructor
*/
function WordSearch(wrapEl, settings) {
this.wrapEl = wrapEl;
// Add `.ws-area` to wrap element
this.wrapEl.classList.add('ws-area');
//Words solved.
this.solved = 0;
// Default settings
var default_settings = {
'directions': ['W', 'N', 'WN', 'EN'],
'gridSize': 10,
'words': ['one', 'two', 'three', 'four', 'five'],
'debug': false
}
this.settings = Object.merge(settings, default_settings);
// Check the words' length if it is overflow the grid
if (this.parseWords(this.settings.gridSize)) {
// Add words into the matrix data
var isWorked = false;
while (isWorked == false) {
// initialize the application
this.initialize();
isWorked = this.addWords();
}
// Fill up the remaining blank items
if (!this.settings.debug) {
this.fillUpFools();
}
// Draw the matrix into wrap element
this.drawmatrix();
}
}
/**
* Parse words
* @param {Number} Max size
* @return {Boolean}
*/
WordSearch.prototype.parseWords = function(maxSize) {
var itWorked = true;
for (var i = 0; i < this.settings.words.length; i++) {
// Convert all the letters to upper case
this.settings.words[i] = this.settings.words[i].toUpperCase();
var word = this.settings.words[i];
if (word.length > maxSize) {
alert('The length of word `' + word + '` is overflow the gridSize.');
console.error('The length of word `' + word + '` is overflow the gridSize.');
itWorked = false;
}
}
return itWorked;
}
/**
* Put the words into the matrix
*/
WordSearch.prototype.addWords = function() {
var keepGoing = true,
counter = 0,
isWorked = true;
while (keepGoing) {
// Getting random direction
var dir = this.settings.directions[Math.rangeInt(this.settings.directions.length - 1)],
result = this.addWord(this.settings.words[counter], dir),
isWorked = true;
if (result == false) {
keepGoing = false;
isWorked = false;
}
counter++;
if (counter >= this.settings.words.length) {
keepGoing = false;
}
}
return isWorked;
}
/**
* Add word into the matrix
*
* @param {String} word
* @param {Number} direction
*/
WordSearch.prototype.addWord = function(word, direction) {
var itWorked = true,
directions = {
'W': [0, 1], // Horizontal (From left to right)
'N': [1, 0], // Vertical (From top to bottom)
'WN': [1, 1], // From top left to bottom right
'EN': [1, -1] // From top right to bottom left
},
row, col; // y, x
switch (direction) {
case 'W': // Horizontal (From left to right)
var row = Math.rangeInt(this.settings.gridSize - 1),
col = Math.rangeInt(this.settings.gridSize - word.length);
break;
case 'N': // Vertical (From top to bottom)
var row = Math.rangeInt(this.settings.gridSize - word.length),
col = Math.rangeInt(this.settings.gridSize - 1);
break;
case 'WN': // From top left to bottom right
var row = Math.rangeInt(this.settings.gridSize - word.length),
col = Math.rangeInt(this.settings.gridSize - word.length);
break;
case 'EN': // From top right to bottom left
var row = Math.rangeInt(this.settings.gridSize - word.length),
col = Math.rangeInt(word.length - 1, this.settings.gridSize - 1);
break;
default:
var error = 'UNKNOWN DIRECTION ' + direction + '!';
alert(error);
console.log(error);
break;
}
// Add words to the matrix
for (var i = 0; i < word.length; i++) {
var newRow = row + i * directions[direction][0],
newCol = col + i * directions[direction][1];
// The letter on the board
var origin = this.matrix[newRow][newCol].letter;
if (origin == '.' || origin == word[i]) {
this.matrix[newRow][newCol].letter = word[i];
} else {
itWorked = false;
}
}
return itWorked;
}
/**
* Initialize the application
*/
WordSearch.prototype.initialize = function() {
/**
* Letter matrix
*
* param {Array}
*/
this.matrix = [];
/**
* Selection from
* @Param {Object}
*/
this.selectFrom = null;
/**
* Selected items
*/
this.selected = [];
this.initmatrix(this.settings.gridSize);
}
/**
* Fill default items into the matrix
* @param {Number} size Grid size
*/
WordSearch.prototype.initmatrix = function(size) {
for (var row = 0; row < size; row++) {
for (var col = 0; col < size; col++) {
var item = {
letter: '.', // Default value
row: row,
col: col
}
if (!this.matrix[row]) {
this.matrix[row] = [];
}
this.matrix[row][col] = item;
}
}
}
/**
* Draw the matrix
*/
WordSearch.prototype.drawmatrix = function() {
for (var row = 0; row < this.settings.gridSize; row++) {
// New row
var divEl = document.createElement('div');
divEl.setAttribute('class', 'ws-row');
this.wrapEl.appendChild(divEl);
for (var col = 0; col < this.settings.gridSize; col++) {
var cvEl = document.createElement('canvas');
cvEl.setAttribute('class', 'ws-col');
cvEl.setAttribute('width', 40);
cvEl.setAttribute('height', 40);
// Fill text in middle center
var x = cvEl.width / 2,
y = cvEl.height / 2;
var ctx = cvEl.getContext('2d');
ctx.font = '400 28px Calibri';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillStyle = '#333'; // Text color
ctx.fillText(this.matrix[row][col].letter, x, y);
// Add event listeners
cvEl.addEventListener('mousedown', this.onMousedown(this.matrix[row][col]));
cvEl.addEventListener('mouseover', this.onMouseover(this.matrix[row][col]));
cvEl.addEventListener('mouseup', this.onMouseup());
divEl.appendChild(cvEl);
}
}
}
/**
* Fill up the remaining items
*/
WordSearch.prototype.fillUpFools = function() {
for (var row = 0; row < this.settings.gridSize; row++) {
for (var col = 0; col < this.settings.gridSize; col++) {
if (this.matrix[row][col].letter == '.') {
// Math.rangeInt(65, 90) => A ~ Z
this.matrix[row][col].letter = String.fromCharCode(Math.rangeInt(65, 90));
}
}
}
}
/**
* Returns matrix items
* @param rowFrom
* @param colFrom
* @param rowTo
* @param colTo
* @return {Array}
*/
WordSearch.prototype.getItems = function(rowFrom, colFrom, rowTo, colTo) {
var items = [];
if ( rowFrom === rowTo || colFrom === colTo || Math.abs(rowTo - rowFrom) == Math.abs(colTo - colFrom) ) {
var shiftY = (rowFrom === rowTo) ? 0 : (rowTo > rowFrom) ? 1 : -1,
shiftX = (colFrom === colTo) ? 0 : (colTo > colFrom) ? 1 : -1,
row = rowFrom,
col = colFrom;
items.push(this.getItem(row, col));
do {
row += shiftY;
col += shiftX;
items.push(this.getItem(row, col));
} while( row !== rowTo || col !== colTo );
}
return items;
}
/**
* Returns matrix item
* @param {Number} row
* @param {Number} col
* @return {*}
*/
WordSearch.prototype.getItem = function(row, col) {
return (this.matrix[row] ? this.matrix[row][col] : undefined);
}
/**
* Clear the exist highlights
*/
WordSearch.prototype.clearHighlight = function() {
var selectedEls = document.querySelectorAll('.ws-selected');
for (var i = 0; i < selectedEls.length; i++) {
selectedEls[i].classList.remove('ws-selected');
}
}
/**
* Lookup if the wordlist contains the selected
* @param {Array} selected
*/
WordSearch.prototype.lookup = function(selected) {
var words = [''];
for (var i = 0; i < selected.length; i++) {
words[0] += selected[i].letter;
}
words.push(words[0].split('').reverse().join(''));
if (this.settings.words.indexOf(words[0]) > -1 ||
this.settings.words.indexOf(words[1]) > -1) {
for (var i = 0; i < selected.length; i++) {
var row = selected[i].row + 1,
col = selected[i].col + 1,
el = document.querySelector('.ws-area .ws-row:nth-child(' + row + ') .ws-col:nth-child(' + col + ')');
el.classList.add('ws-found');
}
//Cross word off list.
var wordList = document.querySelector(".ws-words");
var wordListItems = wordList.getElementsByTagName("li");
for(var i=0; i<wordListItems.length; i++){
if(words[0].toLowerCase() == wordListItems[i].innerHTML.toLowerCase()){
wordListItems[i].innerHTML = "<del>"+wordListItems[i].innerHTML+"</del>";
}
}
//Increment solved words.
this.solved++;
//Game over?
if(this.solved == this.settings.words.length){
this.gameOver();
}
}
}
/**
* Game Over
*/
WordSearch.prototype.gameOver = function() {
//Create overlay.
var overlay = document.createElement("div");
overlay.setAttribute("id", "ws-game-over-outer");
overlay.setAttribute("class", "ws-game-over-outer");
this.wrapEl.parentNode.appendChild(overlay);
//Create overlay content.
var overlay = document.getElementById("ws-game-over-outer");
overlay.innerHTML = "<div class='ws-game-over-inner' id='ws-game-over-inner'>"+
"<div class='ws-game-over' id='ws-game-over'>"+
"<h2>Congratulations!</h2>"+
"<p>You've found all of the words!</p>"+
"</div>"+
"</div>";
}
/**
* MouseĀ event - Mouse down
* @param {Object} item
*/
WordSearch.prototype.onMousedown = function(item) {
var _this = this;
return function() {
_this.selectFrom = item;
}
}
/**
* Mouse event - Mouse move
* @param {Object}
*/
WordSearch.prototype.onMouseover = function(item) {
var _this = this;
return function() {
if (_this.selectFrom) {
_this.selected = _this.getItems(_this.selectFrom.row, _this.selectFrom.col, item.row, item.col);
_this.clearHighlight();
for (var i = 0; i < _this.selected.length; i ++) {
var current = _this.selected[i],
row = current.row + 1,
col = current.col + 1,
el = document.querySelector('.ws-area .ws-row:nth-child(' + row + ') .ws-col:nth-child(' + col + ')');
el.className += ' ws-selected';
}
}
}
}
/**
* Mouse event - Mouse up
*/
WordSearch.prototype.onMouseup = function() {
var _this = this;
return function() {
_this.selectFrom = null;
_this.clearHighlight();
_this.lookup(_this.selected);
_this.selected = [];
}
}
})();
|