-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkanamemo.js
1138 lines (1016 loc) · 31.8 KB
/
kanamemo.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
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Debugging related stuff
*/
/** @const {boolean} Adjust things for debugging? */
const DEBUG = false
/**
* Quick & dirty way to throw errors.
* @param {string} name - Error name.
* @param {string} message - Error message.
*/
function raise(name, message) {
console.log("Error: "+name)
console.trace()
throw message;
}
/**
* Log a debug message. Will be prefixed with "[DEBUG]"
* @param {string} message - Debug message to display.
*/
function debug(message) {
console.log("[DEBUG] "+message)
}
/**
* Suspend execution for a time. Prefix with await in an async function.
* @param {number} timeout - For how many milliseconds execution should be suspended.
* @returns {Promise} Resolves once the specified timeout has passed.
*/
function sleep(timeout) {
return new Promise(resolve => window.setTimeout(resolve, timeout))
}
/**
* Templates
*/
/**
* HTML template for up facing tiles.
* @const {function}
* @param {string} id - ID for CSS matching.
* @param {Object} skin - An object with a "background" attribute for the background image's URL.
* @returns {string} HTML template literal.
*/
const HTML_UP_TILE_MARKUP = function(id, skin){
return `
<div id="${id}" class="tile" style="background-image: url(${skin.background});">
<div class="tileCharacter">${skin.character}</div>
</div>`
}
/**
* HTML template for down facing tiles.
* Will be showing pictograms no matter what if in DEBUG mode.
* @const {function}
* @param {string} id - ID for CSS matching.
* @param {Object} skin - An object with a "background" attribute for the background image's URL.
* @returns {string} HTML template literal.
*/
const HTML_DOWN_TILE_MARKUP = function(id, skin){
if (DEBUG) {
return `
<div id="${id}" class="tile" style="background-image: url(${skin.background});">
<div class="tileCharacter">${skin.character}</div>
</div>`
} else {
return `
<div id="${id}" class="tile" style="background-image: url(${skin.background});"></div>`
}
}
/**
* HTML template for matched tiles.
* @const {function}
* @param {string} id - ID for CSS matching.
* @param {Object} skin - An object with a "background" attribute for the background image's URL.
* @returns {string} HTML template literal.
*/
const HTML_MATCHED_TILE_MARKUP = function(id, skin){
return `
<div id="${id}" class="tile matched_tile" style="background-image: url(${skin.background});"></div>`
}
/**
* Text template to construct the CSS tile ID for use in the tile HTML templates.
* @const {function}
* @param {string} id - The ID associated with the Tile object (value of Tile.prototype.id).
* @returns {string} HTML template literal.
*/
const TILE_HANDLE=function(id){return `tile_${id}`}
/**
* Class representing throwable errors.
* @property {Array} tags - Tags this error is supposed to be associated with.
* @property {string} name - The error name (class name).
* @property {string} message - The error message.
*/
class Error {
/**
* Create an Error object.
* @param {Array} tags - Tags this error is supposed to be associated with.
* @param {string} message - The error message.
*/
constructor(tags, message) {
this.tags = []
this.name = this.constructor.name
this.message = message
this.addTags(tags)
}
/**
* Tags available for the error in question.
* Subclasses are supposed to override/expand this with their own tags.
* @access protected
* @abstract
*/
get _availableTags() { return [] }
/**
* Have any tags been specified for our error?
* @returns {boolean} true if there are any, false if not.
*/
get hasTags() {
return (this.tags.length > 0)
}
/**
* Title of this error, with tags if it has any.
* @returns {string} Error title.
*/
get errorTitle() {
if (this.hasTags) {
return "Error: "+this.name+", tags: "+this.tags
}
else {
return "Error: "+this.name
}
}
/**
* Tag the error.
* @example error.addTag("TOMATO_IS_KETCHUP")
* @throws - Will throw an error if the error doesn't recognize the tag.
* @param {string} - Tag name. Has to be one of the tags made available by the error.
*/
addTag(tag) {
if (this.tagAvailable(tag)) {
this.tags.push(tag)
} else {
console.log("Error: Error")
console.trace()
throw "Unknown error tag \""+tag+"\" specified for error (\""+this.name+"\"). Error message of the mistagged error: "+this.message
}
}
/**
* Tag the error with multiple tags at once.
* @example error.addTags(["TOMATO_NOT_RESPONDING", "ANVIL_CEILING_FIXTURE_FAILURE"])
* @throws - Will throw an error if the error doesn't recognize one of the tags.
* @param {Array} tags - Tag names.
*/
addTags(tags) {
for (let tag of tags) {
this.addTag(tag)
}
}
/**
* Do we know the specified tag?
* This evaluates whether the tag is on the list of tags this error recognizes.
* @param {string} tag - Tag name to be checked.
* @returns {boolean} true if it is, false if it's not.
*/
tagAvailable(tag) {
if (this._availableTags.includes(tag)) {
return true
}
else {
return false
}
}
/**
* Posts the error title and a trace to the console, and returns the error message.
* Intended to be used in conjuction with throw.
* @example throw error.embed()
* @example throw new TomatoError(["TOMATO_IS_KETCHUP", "Tomato go squashed by an anvil."]).embed()
* @returns {string} error message.
*/
embed() {
console.log(this.errorTitle)
console.trace()
return this.message
}
}
/**
* File error.
* @augments Error - Constructor remains unchanged.
*/
class FileError extends Error {
/**
* Tags:
* - NOT_FOUND: File not found.
* @protected
*/
get _availableTags() {
return [...Error.prototype._availableTags, "NOT_FOUND"]
}
}
/**
* Subclass of Array that optionally takes an Array object. Provides additional functionality.
* All methods return 'this' to allow chaining, unless the documentation says otherwise.
*
*/
class KanamemoArray extends Array {
/**
* An Array subclass with additional functionality meeting the needs of Kanamemo.
* All methods return {this} to allow chaining.
* @param {anything} array - Empty for empty array or number for length, {Array} or {KanamemoArray} to initialize from.
*
* Depending on the value of the array parameter, the initialization
* behaviour changes:
*
* If it's typechecked to be {undefined}", we get an empty array.
*
* Otherwise, if it typechecks to be {number}, we get an empty array
* with a length equal to its value.
*
* Otherwise, if it's determined to be an {Array} or {KanamemoArray} object,
* we initialize with the elements of the specified arrays.
*
* @throws KanamemoArrayError Throws if none of the described cases for the array parameter apply.
* @todo Use proper {Error} subclass for KanamemoArrayError.
*
*/
constructor(array) {
// Make new, empty array?
if (typeof(array) === "undefined") {
super()
// Make new array of specified size?
} else if (typeof(array) === "number") {
super(array)
// Become a copy of the specified array?
} else if (array.constructor === Array || array.isKanamemoArray) {
super()
array.forEach(element => { this.push(element) })
// None of the above, which means something's wrong. Raise error.
} else {
raise("KanamemoArrayError", "KanamemoArray initialized with faulty parameter of type: "+typeof(array)+" and value "+array)
}
/**
* This makes KanamemoArray objects recognize each other.
* @public
*/
this.isKanamemoArray = true
}
/**
* Swap element A with element B.
* @param {number} indexA - Index to be swapped with indexB
* @param {number} IndexB - Index to be swapped with indexA
* @returns {this}
*/
swap (indexA, indexB) {
let elementA = this[indexA]
this[indexA] = this[indexB]
this[indexB] = elementA
return this
}
/**
* Randomize elements according to Fisher-Yates.
* @returns {this}
*/
shuffle() {
if (this.length > 0) {
let currentIndex = this.length
while (currentIndex !== 0) {
let randomIndex = Math.floor(Math.random()*currentIndex)
--currentIndex;
this.swap(currentIndex, randomIndex)
}
}
return this
}
/**
* Initialize each index of the array with the index number.
* @example [1] would reference 1, [2] 2, etc. Stops when this.length is reached.
* returns {this}
*/
initWithIndices() {
for (let i=0; i < this.length; i++) {
this[i] = i
}
return this
}
}
/**
* Individual picture to be included in a set to be matched with others in it.
* Contains information about it (e.g. educational in nature)
* Example: The Japanese character に could have the info that it's a kana belonging
* to the set of hiragana, and that it's derived from the kanji 仁, which means
* benevolence.
* @todo
*/
class Pictogram {}
/**
* Ties together pictograms that can be matched with each other.
*/
class PictogramSet extends KanamemoArray {
/**
* Create a PictogramSet object.
* @param {Array} pictograms - The pictograms that make up this set.
*/
constructor(pictograms) {
super(pictograms)
}
/**
* Get a pair of two randomly picked pictograms from the set.
* @returns {KanamemoArray} Array comprised of the randomly picked pictograms.
*/
getRandomPair() {
let pictogramsAvailable = new KanamemoArray(this)
let pictogramsChosen = new KanamemoArray()
pictogramsAvailable.shuffle()
for (let i = 0; i < 2; i++) { // Loop twice.
pictogramsChosen.push(pictogramsAvailable.pop())
}
return pictogramsChosen
}
}
/**
* A PictogramSet consisting of a matching romaji, hiragana and katakana.
*/
class KanaSet extends PictogramSet {
/**
* Create a KanaSet object.
* @param {string} romaji -
* @param {string} hiragana -
* @param {string} katakana -
*/
constructor(romaji, hiragana, katakana) {
super([romaji, hiragana, katakana])
this.romaji = romaji
this.hiragana = hiragana
this.katakana = katakana
}
}
/**
* File handler that can open and read files into strings.
*/
class File {
/**
* Create a file handler and, if so specified, load the file.
* @param {string} path - Filesystem or HTTP path.
* @param {string} mode - Either FILE (not implemented) or HTTP.
* @param {boolean} openImmediately - True to run .open right away from the constructor (default).
*/
constructor(path, mode, openImmediately=true) {
this.path = path
this.mode = mode
this.request = new XMLHttpRequest()
if (openImmediately) {
this.open(this.path)
}
}
/**
* Open the file.
* @param {string} path - Filesystem or HTTP path.
* @return File contents.
*/
open(path) {
this.request.open("GET", path, false)
this.request.send()
if (!this.requestSuccessful()) {
throw new FileError(["NOT_FOUND"], "File not found: "+path).embed()
}
return this.getContent()
}
requestSuccessful() {
if (this.mode === "HTTP") {
if (this.responseCode == 200) {
return true
}
}
return false
}
/**
* Get the file's content.
* @return {string} file content.
*/
getContent() {
return this.request.responseText
}
/**
* Get file path in its final resolved form (after redirects, etc.)
* @return {string} URL/file path.
*/
getResolvedPath() {
return this.request.responseURL
}
/**
* Get the response from the file server or filesystem (e.g. HTTP status code)
* @return {number} response code.
*/
get responseCode() {
return this.request.status
}
}
/**
* File subclass with JSON functionality.
*/
class JsonFile extends File {
/**
* Return JSON parsed from the file.
*/
getJson() {
let deb = this.getContent()
return JSON.parse(this.getContent())
}
}
/**
* Base class for themes.
* @interface
*/
class Theme {}
/**
* Theme for Tile objects, to be used with when they're rendered on screen.
* @implements {Theme}
*/
class TileTheme extends Theme {
/**
* Create a TileTheme object.
* @param {string} upImg - URL to the background image used for up facing tiles.
* @param {string} downImg - URL to the background image used for down facing tiles.
* @param {string} matchedImg - URL to the background image used for matched tiles.
* @param {string} upCode - HTML template literal to be used for up facing tiles.
* @param {string} downCode - HTML template literal to be used for down facing tiles.
* @param {string} matchedCode - HTML template literal to be used for matched tiles.
*/
constructor(upImg, downImg, matchedImg, upCode, downCode, matchedCode) {
super()
this.img = {
up: upImg,
down: downImg,
matched: matchedImg
}
this.code = {
up: upCode,
down: downCode,
matched: matchedCode
}
}
}
/**
* Manages a DOM element (and its children) for on-screen rendering.
* The DOM can be an already existing one, or can be created by one of our methods.
* @property {string} id - CSS ID of the DOM element in question.
*/
class RenderableHtml {
/**
*
*/
constructor(id) {
this.id = id
}
/**
* Our top level DOM element.
*/
get element() {
return document.getElementById(this.id)
}
/**
* Our top level DOM element's parent element.
*/
get parent() {
return this.element.parentElement
}
/**
* Does our top level DOM element exist (yet)?
*/
get elementExists() {
return !(this.element === null)
}
/**
* Create a document fragment from the specified markup.
* @param {string} markup - Markup specifying a DOM hierarchy.
* @returns {Array} Contains two values, the fragment and the ID of .firstElementChild, like so: [fragment, id]
*/
createDocumentFragmentFromMarkup(markup) {
let fragment = document.createRange().createContextualFragment(markup)
let id = fragment.firstElementChild.id
return [fragment, id]
}
/**
* Take the specified markup and create a document fragment as a child for the specified parent element.
* Will replace this.id with the id of the first element child of the resulting document fragment.
* @param {Object} parentElement - DOM element serving as our parent element.
* @param {string} markup - Markup to convert into DOM to add it to the parent element.
*/
createElement(parentElement, markup) {
let [fragment, id] = this.createDocumentFragmentFromMarkup(markup)
this.id = id
parentElement.appendChild(fragment)
}
/**
* Replace the element of this RenderableHtml with a new document fragment created from the specified markup.
* @param {string} markup - Markup representing a DOM hierarchy.
*/
replaceElementByMarkup(markup) {
let [fragment, id] = this.createDocumentFragmentFromMarkup(markup)
this.id = id
this.parent.replaceChild(fragment, this.element)
}
/**
* Put this element into the DOM. If it doesn't exist yet, create.
* @param {Object} parentElement - DOM element serving as our parent element.
* @param {string} markup - Markup from which to create our element if it doesn't exist eyt.
*/
render(parentElement, markup) {
if (this.elementExists) {
this.replaceElementByMarkup(markup)
} else {
this.createElement(parentElement, markup)
}
}
}
/**
* A grid tile. Knows its pictogram and state (e.g. face up or down).
* @augments RenderableHtml - "id" property is inherited, but altered using the TILE_HANDLE template.
*
* Parameters added as properties:
* @property {string} tileId - ID of the tile (position in the grid)
* @property {string} pictogram - My pictogram.
* @property {PictogramSet} pictogramSet - The PictogramSet object my pictogram belongs to.
* @property {Theme} theme - Theme object that determines my appearance.
*
* Original properties:
* @property {Object} onClickHandlers - The "click" event handlers I need to function.
* @property {number} MATCHED - Used to set and compare state as to whether we're in matched state.
* @property {number} UP - Used to set and compare as to whether we're in UP state.
* @property {DOWN} DOWN - Used to set and compare as to whether we're in DOWN state.
* @property {number} state - Which state we're in (MATCHED, UP, or DOWN).
*/
class Tile extends RenderableHtml{
/**
* A memo tile to click on, and its various states.
* @param {string} tileId - ID of the tile (position in the grid)
* @param {string} pictogram - My pictogram.
* @param {PictogramSet} pictogramSet - The PictogramSet object my pictogram belongs to.
* @param {Theme} Theme object that determines my appearance.
*/
constructor(tileId, pictogram, pictogramSet, theme) {
super(TILE_HANDLE(tileId))
this.tileId = tileId
this.pictogram = pictogram
this.pictogramSet = pictogramSet
this.theme = theme
this.onClickHandlers = {}
/* State pseudo "constants". */
this.MATCHED = 0 // Tile's been matched.
this.UP = 1 // Tile is revealed and showing its pictogram.
this.DOWN = 2 // Tile is showing its back, hiding its pictogram.
this.state = this.DOWN // We assume we'll want tiles starting face down.
}
/**
* The markup for our current state (either matched, up or down).
* @returns {string}
*/
get markup() {
switch (this.state) {
case this.MATCHED:
return this.matchedMarkup
case this.UP:
return this.upMarkup
case this.DOWN:
return this.downMarkup
}
}
/**
* Render and add this tile to the specified parent DOM element, so it's visible on the screen.
* @param {Object} parentElement - Parent DOM element to add the tile DOM hierarchy to display it.
*/
render(parentElement) {
RenderableHtml.prototype.render.call(this, parentElement, this.markup)
this.setOnClickHandler()
}
/**
* Markup for our matched state.
* @returns {string}
*/
get matchedMarkup() {
return this.theme.code.matched(this.id, {background: this.theme.img.matched, character: " "})
}
/**
* Markup for our up state.
* @returns {string}
*/
get upMarkup() {
return this.theme.code.up(this.id, {background: this.theme.img.up, character: this.pictogram})
}
/**
* Markup for our down state.
* @returns {string}
*/
get downMarkup() {
if (DEBUG) {
return this.theme.code.down(this.id, {background: this.theme.img.down, character: this.pictogram})
} else {
return this.theme.code.down(this.id, {background: this.theme.img.down, character: " "})
}
}
/**
* Add the appropriate onClick event handler to the element depending
* on our current state.
* This is only to be called after the interface has been rendered.
* @param {funtion} onClickMatched - Called when clicked in matched state.
* @param {function} onClickUp - Called when clicked in up state.
* @param {function} onClickDown - Called when clicked in down state.
*/
addOnClickHandlers(onClickMatched, onClickUp, onClickDown) {
this.onClickHandlers[this.MATCHED] = onClickMatched
this.onClickHandlers[this.UP] = onClickUp
this.onClickHandlers[this.DOWN] = onClickDown
}
/**
* Adds all "click" handlers for this tile to the DOM element that represents it.
* This method is useful for re-adding the handlers whenever the DOM element is recreated.
*/
setOnClickHandler() {
this.element.addEventListener("click", this.onClickHandlers[this.state])
}
changeToMatched () {
this.state = this.MATCHED
this.render()
}
changeToUp() {
this.state = this.UP
this.render()
}
changeToDown() {
this.state = this.DOWN
this.render()
}
/**
* @param {Tile} tile - Are we in the same pictogram set as this tile?
*/
isInSameSetAs(tile) {
return this.pictogramSet === tile.pictogramSet
}
/* ==================================
State query methods. */
isMatched() { if (this.state == this.MATCHED) { return true } else { return false } }
isUp() { if (this.state == this.UP) { return true } else { return false } }
isDown() { if (this.state == this.DOWN) { return true } else { return false } }
}
/**
* Grid theme.
* @property {TileTheme} tileTheme - TileTheme object used for tile themeing.
* @todo Grid theming isn't really implemented yet.
*/
class GridTheme {
/** Create a GridTheme object.
* @param {TileTheme} TileTheme object to be used for grid tiles.
*/
constructor(tileTheme) {
this.tileTheme = tileTheme
}
}
/**
* The memo tile grid.
*
* Parameters added as properties:
* @property {number} rowCount - Number of rows.
* @property {number} columnCount - Number of columns.
* @property {GridTheme} theme - GridTheme object to determine the grid's appearance.
*
* Original properties:
* @property {Array} tiles - Tile objects representing the grid's tiles.
*/
class Grid extends RenderableHtml {
/** Creates a Grid object.
* @param {number} rowCount - Number of rows.
* @param {number} columnCount - Number of columns.
* @param {GridTheme} theme - GridTheme object to determine the grid's appearance.
* @todo Add actual visuals (such as a background) to the grid that can be themed.
*/
constructor(rowCount, columnCount, theme) {
super("grid") //NOTE: Candidate for change once grid template is implemented.
this.rowCount = rowCount
this.columnCount = columnCount
this.theme = theme
this.tiles = new Array(rowCount*columnCount)
}
/**
* Populate the grid with tiles based on pictogram sets specified.
* @param {PictogramSets} A PictogramSets object with pictograms to choose from to populate the grid with tiles for.
*/
populate(pictogramSets) {
this.populateRandomPairs(pictogramSets)
}
/**
* Randomly picks two pictograms from pictogram sets randomly picked from the specified PictogramSets object.
* Every pictogram gets its own Tile object, which is added to the tiles property.
* @example - From {[a,b,c], [d,e,f]}, it could pick [a,c] and [f,e]. It'd add 4 Tile objects, one for each.
* It does this until the grid is full.
* @warning PictogramSets needs to have enough pictograms to fill the grid.
* @todo Handle PictogramSets not having enough pictograms to fill the grid.
*/
populateRandomPairs(pictogramSets) {
let tileIndexesAvailable = new KanamemoArray(this.tiles.length).initWithIndices().shuffle()
for (let pictogramSet of pictogramSets.shuffle()) {
if (!tileIndexesAvailable.length > 0) {break}
let pictogramAIndex = tileIndexesAvailable.pop()
let pictogramBIndex = tileIndexesAvailable.pop()
let pair = pictogramSet.getRandomPair() // Example: Get random two from [romaji, hiragana, katakana].
this.tiles[pictogramAIndex] = new Tile(pictogramAIndex, pair[0], pictogramSet, this.theme.tileTheme)
this.tiles[pictogramBIndex] = new Tile(pictogramBIndex, pair[1], pictogramSet,this.theme.tileTheme)
}
}
/**
* The grid's Tile objects sorted into rows.
* @todo Not implemented.
*/
get rows() {}
/**
* Get the rendered markup/code for the grid.
* @todo Not implemented.
*/
get markup() {}
/**
* Render the grid into the specified DOM element.
* @param {Object} element - DOM element to render into.
*/
render(element) {
let rowElementsAdded = 0
for (let tile of this.tiles) {
tile.render(element) //NOTE: Will become this.element once grid has its own HTML.
rowElementsAdded += 1
if (rowElementsAdded === this.columnCount) {
element.appendChild(document.createRange().createContextualFragment("<br/>"))
rowElementsAdded = 0
}
}
}
}
/**
* A KanamemoArray with the capability to initialize itself with KanaSet objects initialized with data from a file.
*/
class PictogramSets extends KanamemoArray {
/**
* @param {string} sourceFilePath - File path to read set data from.
*/
constructor(sourceFilePath) {
super()
this.getFromFile(sourceFilePath).sets.forEach(set => {
this.push(new KanaSet(...set))
})
}
/**
* Read JSON from the specified file path.
* @param {string} sourceFilePath - File path to read set data from.
* @returns JSON in object form as it was read from the file.
*/
getFromFile(sourceFilePath) {
//console.log(new JsonFile(sourceFilePath, "HTTP").getJson())
return new JsonFile(sourceFilePath, "HTTP").getJson()
}
}
/**
* A collection of all themeing items required to theme the game.
* Is currently only concerned with GridTheme, which, in turn, is currently only concerned with TileTheme based tile themeing.
* @property {GridTheme} gridTheme
*/
class GameTheme {
/** Create GameTheme object.
* @param {GridTheme} gridTheme - Theme object for the grid.
*/
constructor(gridTheme) {
this.gridTheme = gridTheme
}
}
/**
* Manages the DOM element we're rendering into. Is the beginning of the rendering hierarchy.
* @property {Object} element - DOM element we'll be rendering into.
*/
class HtmlCanvas {
/** Create an HtmlCanvas object.
* @param element
*/
constructor(element) {
this.element = element
}
/**
* Put what's already rendered on display.
*/
render(markup) {
this.element.innerHTML = markup
}
}
/**
* Represents the game and manages its parts and execution.
* @property {Canvas} - Object managing the interface we're working with (e.g. DOM hierarchy).
* @property {string} collection - Path to the collection JSON file specifying our pictograms.
* @property {GameTheme} theme - GameTheme object with all the media configured we need to render the game.
* @property sets {PictogramSets} - Pictogram sets as taken from the specified JSON file sorted into an Array-like object.
*/
class Game {
/**
* Create a Game object.
* @param {Canvas} canvas - Object managing the interface we're working with (e.g. DOM hierarchy).
* @param {string} collection - Path to the collection JSON file specifying our pictograms.
* @param {GameTheme} theme - GameTheme object with all the media configured we need to render the game.
*/
constructor(canvas, collection, theme) {
this.canvas = canvas
this.collection = collection
this.theme = theme
this.sets = new PictogramSets(this.collection)
}
/**
* Get the game displayed/updated on the screen according to its current state.
* @abstract
*/
render() {}
/**
* Initialize the game (add DOM elements and events, for example).
* @abstract
*/
setUp() {}
/**
* Initialize and start the game.
*/
run() {
this.setUp()
}
}
/**
* Object passed directly to javascript event functions, which then execute its handleEvent method.
* @properties {Game} game - Game object representing the game, so it's available during event handling.
*/
class KanaGameEvent {
/** Create KanaGameEvent
* @param {KanaGame} game - Game object representing the game.
*/
constructor(game) {
this.game = game
}
/**
* Events such as "onclick" will execute this. Subclass & override.
*/
handleEvent(event) {}
}
/**
* Event handler for tiles.
* @augments KanaGameEvent - We inherit all properties unchanged.
* @properties {Tile} tile - Tile object representing the tile this event pertains to.
*/
class KanaGameTileEvent extends KanaGameEvent {
/**
* Create a KanaGameTileEvent object.
* @param {KanaGame} game - Game object representing the game.
* @param {Tile} tile - Tile object representing the tile this event pertains to.
*/
constructor(game, tile) {
super(game)
this.tile = tile
}
}
/**
* Event handler for what happens when a tile in the matched state is clicked.
* @augments KanaGameOnMatchedTileClickEvent - Constructor remains unchanged.
*/
class KanaGameOnMatchedTileClickEvent extends KanaGameTileEvent {
/**
* @todo Not implemented.
*/
handleEvent(event) {
console.log("Matched tile event fired: "+event)
}
}
/**
* Event handler for what happens when a tile in the up state is clicked.
* @augments KanaGameOnUpTileClickEvent - Constructor remains unchanged.
*/
class KanaGameOnUpTileClickEvent extends KanaGameTileEvent {
/**
* @todo Not implemented.
*/
handleEvent(event) {
console.log("Up tile event fired: "+event)
}
}
/**
* Event handler for what happens when a tile in the down state is clicked.
* @augments KanaGameTileEvent - Constructor remains unchanged.
*/
class KanaGameOnDownTileClickEvent extends KanaGameTileEvent {
/**
* Change tile to the up state, and process all tiles in the up state subsequently.
* This is where functionality such as checking whether the up facing tiles on the
* board are matching and the actions depending on that are hooked in.
*/
handleEvent(event) {
// Flip our tile up.
this.tile.changeToUp()
this.game.upTiles.push(this.tile)
this.game.processUpTiles()
}