-
Notifications
You must be signed in to change notification settings - Fork 0
/
rainbow.js
660 lines (596 loc) · 24.9 KB
/
rainbow.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
"use strict";
//document constants
const RAINBOW_CANVAS = "rainbow-canvas";
const RAINBOW_IMAGE = "rainbow-wheel-img";
const RAINBOW_DIFFICULTIES_IMAGES = ["rainbow-LW-img", "rainbow-WW-img", "rainbow-MW-img", "rainbow-HW-img"];
const RAINBOW_GAME_FRAME = "rainbow-game";
const RAINBOW_GAME_SHELL = "rainbow-game-shell"
const RAINBOW_NEW_GAME_DIALOG = "rainbow-new-game-dialog";
const RAINBOW_NEW_GAME_FORM ="new-game-form";
const RAINBOW_NEW_GAME_TEXT_FIELD ="new-game-key-text";
const RAINBOW_RADIO_NAME ="rainbow-difficulty";
const RAINBOW_CLOSE = "rainbow-close";
const RAINBOW_RED_BORDER = "red-border";
const RAINBOW_HIDDEN = "hidden";
const RESIZABLE = true;
//Canvas constants
const CANVAS_BACKGROUND_COLOR="black";
const CANVAS_PADDING = 0; //in Percent
const CANVAS_FONT = "arial";
const CANVAS_ANIMATION_SPEED = 300 //in milliseconds
const CANVAS_FRAME_RATE = 20;
//Canvas - letter constants
const CANVAS_LETTER_PADDING = 16; //in Percent
const CANVAS_LETTER_RADIUS = 14;
const CANVAS_LETTER_BACKGROUND_COLOR = "rgb(255, 162, 0)";
const CANVAS_PLAYABLE_LETTER_RADIUS_RATIO = 1.05;
const CANVAS_SELECTED_LETTER_BACKGROUND_COLOR = "gold";
const CANVAS_PLAYABLE_LETTER_BACKGROUND_COLOR = "white";
const CANVAS_LETTER_COLOR = "rgb(20,20,20)";
//Canvas - key constants
const CANVAS_KEY_FONT_RATIO = 25; //less is bigger
const CANVAS_KEY_FONT_COLOR ="rgb(255, 162, 0)";
//Canvas - moves constants
const CANVAS_MOVES_FONT_COLOR = "rgb(255, 162, 0)";
const CANVAS_MOVES_FONT_RATIO = 25;
//Canvas - button constants
const CANVAS_BUTTON_COLOR = "rgb(255, 162, 0)";
const CANVAS_BUTTON_COLOR_HOVER = "gold";
const CANVAS_BUTTON_LETTER_COLOR = "white";
const CANVAS_BUTTON_RADIUS = 23;
//game constants
const RAINBOW = 'SHERDOG'; // Must be 7 letters
const RAINBOW_LENGTH = 7;
if( RAINBOW.length != RAINBOW_LENGTH ){ throw 'Error RAINBOW not well defined'; };
const DIFFICULTIES = ["LW","WW","MW","HW"];
const VERY_EASY = 0;
const EASY = 1;
const MEDIUM =2;
const HARD =3;
const STARTING_DIFFICULTY = EASY;
const PRIME = 31;
////////////////////
///////GAME////////
///////////////////
//Game Constructor
function Game(name,prime,difficulty){
this.carousel = name.split("");
this.carousel.push(null); //one of the nodes should be empty
this.startingCarousel = this.carousel;
this.carouselMapping = Array.apply(null, {length: this.carousel.length}).map(Number.call, Number); //generate [0,1,2,3,4,5,6,7] array (based on carousel length)
this.prime = prime;
this.key = "";
this.movesCounter = 0;
this.difficulty = difficulty;
this.paused = false;
}
//Key must be a String
Game.prototype.generate = function(decryptedKey){
if (arguments.length === 1) {
//make sure the func arg is of String type.
if (Object.prototype.toString.call(decryptedKey) !== "[object String]"){
throw 'Error generate() paramater must be of type: "String"';
}
// Game.code = key;
this.key = decryptedKey;
var keyArr = decryptedKey.split("");
} else {
// argument not passed
var keyArr = shuffle(this.carouselMapping);
this.key = keyArr.join("");
}
var tempArray = [];
for (var i = 0; i < keyArr.length; i++) {
tempArray[i] = this.carousel[keyArr[i]];
}
this.carousel = tempArray;
};
Game.prototype.encryptKey = function(key){
return convertBase(((parseInt(key) * this.prime) + this.prime).toString(), 10, 32);;
};
Game.prototype.decryptKey = function(key){
key = key.replace('#','').toLowerCase();
var baseTenKey = convertBase(key, 32, 10);
var result = ((parseInt(baseTenKey) - this.prime) / this.prime).toString();
if (!result.includes("0"))
result = "0" + result;
return result;
};
Game.prototype.isKeyValid = function(key){
key = key.replace('#','').toLowerCase();
if (!isAlphaNumeric(key))
return false;
var decryptedKey = this.decryptKey(key);
if(this.encryptKey(decryptedKey) !== key || decryptedKey.length !== this.carouselMapping.length){
return false;
}
for (var i = 0; i < this.carouselMapping.length; i++) {
var occurences = (decryptedKey.match(new RegExp(this.carouselMapping[i],"g")) || []).length; // check how many of the mapped chars are in the decrypted key.
if(occurences != 1){
return false;
}
}
return true;
}
Game.prototype.isGameFinished = function(){
var carouselPointer = this.carousel.indexOf(null)+1;
for (var i = 0; i < RAINBOW.length; i++) {
if(carouselPointer === this.carousel.length){
carouselPointer = 0;
}
if ( RAINBOW[i] !== this.carousel[carouselPointer] ){
return false;
}
carouselPointer++;
}
return true;
}
Game.prototype.playMove = function(index){
this.movesCounter++;
var oppositeCell = index + this.carousel.length/2;
if(oppositeCell >= this.carousel.length){
oppositeCell = index - this.carousel.length/2;
}
if(this.carousel[oppositeCell] === null){
this.carousel[oppositeCell] = this.carousel[index];
this.carousel[index] = null;
return [{"value": this.carousel[oppositeCell],"from": index,"to": oppositeCell}]
}
var emptyCellIndex = this.carousel.indexOf(null);
var playedMovesLog = [];
playedMovesLog.push({"value": this.carousel[index],"from": index,"to": emptyCellIndex});
this.carousel[emptyCellIndex] = this.carousel[index];
playedMovesLog.push({"value": this.carousel[oppositeCell],"from": oppositeCell,"to": index});
this.carousel[index] = this.carousel[oppositeCell];
this.carousel[oppositeCell] = null;
return playedMovesLog;
}
Game.prototype.playable = function(){
if(this.difficulty === VERY_EASY){
var tempArray = [];
for (var i = 0; i < this.carousel.length; i++) {
if(this.carousel[i] != null){
tempArray.push(i);
}
}
return tempArray;
}
var nullLocation = this.carousel.indexOf(null);
var left = leftIndex(this.carousel,nullLocation);
var right = rightIndex(this.carousel,nullLocation);
if(this.difficulty === HARD){
return [left,right];
}
var doubleLeft = leftIndex(this.carousel,left);
var doubleRight = rightIndex(this.carousel,right);
if(this.difficulty === MEDIUM){
return [left,right,doubleLeft,doubleRight];
}
// in case it's EASY
return [left,right,doubleLeft,doubleRight,rightIndex(this.carousel,doubleRight),leftIndex(this.carousel,doubleLeft)];
}
Game.prototype.reset = function(){
this.carousel = this.startingCarousel;
this.generate(this.key);
this.movesCounter = 0;
}
/////////////////////
///////CANVAS////////
/////////////////////
//Rainbow canvas constructor
function Canvas(canvasElement, paddingPercent, imageID, frameID, game){
this.paddingPercent = paddingPercent;
this.frame = document.getElementById(frameID);
// this.size = Math.min( this.frame.clientWidth, this.frame.clientHeight);
this.size = this.frame.clientWidth;
this.padding = (paddingPercent / 100) * this.size;;
this.canvasElement = document.getElementById(canvasElement);
this.canvasContext = this.canvasElement.getContext("2d");
this.image = document.getElementById(imageID);
this.game = game;
this.movingLetters = {};
for (var i = 0; i < this.game.carousel.length; i++) {
this.movingLetters[this.game.carousel[i]] = null;
}
this.animationInAction = false;
}
Canvas.prototype.resetSize = function(){
// this.size = Math.min( this.frame.clientWidth, this.frame.clientHeight);
this.size = this.frame.clientWidth;
this.padding = (this.paddingPercent / 100) * this.size;
this.canvasElement.setAttribute("height",this.size);
this.canvasElement.setAttribute("width",this.size);
}
Canvas.prototype.reDraw = function(){
var gameFinished = this.game.isGameFinished() && !this.animationInAction;
this.canvasContext.fillStyle = CANVAS_BACKGROUND_COLOR;
this.canvasContext.fillRect(0, 0, this.size, this.size);
this.canvasContext.drawImage(this.image, this.padding, this.padding, this.size-this.padding*2, this.size-this.padding*2);
if(!gameFinished){
this.drawResetButton(CANVAS_BUTTON_COLOR);
}else{
this.drawGameWon();
}
this.drawKey();
this.drawMoves();
this.drawNewGameButton(CANVAS_BUTTON_COLOR);
if(!gameFinished){
for (var i = 0; i < this.game.carousel.length; i++) {
if(this.game.carousel[i] != null){
if(this.movingLetters[this.game.carousel[i]] == null){
var playable = false;
if(this.game.playable().includes(i)){
playable = true;
}
this.drawLetterInCorner(this.game.carousel[i],i,CANVAS_LETTER_BACKGROUND_COLOR,playable);
}else{
var position = this.movingLetters[this.game.carousel[i]];
this.drawLetter(this.game.carousel[i],position.x,position.y,CANVAS_LETTER_BACKGROUND_COLOR,false);
}
}
}
}
}
Canvas.prototype.drawKey = function(){
var text = "#" + this.game.encryptKey(this.game.key);
var fontSize = this.size/CANVAS_KEY_FONT_RATIO;
var fontStyle = CANVAS_FONT;
var font = "bold " + fontSize +"px "+fontStyle;
this.canvasContext.fillStyle = CANVAS_KEY_FONT_COLOR; // font color to write the text with
this.canvasContext.font = font;
this.canvasContext.fillText(text, (this.size - (this.size *(30/100)))/CANVAS_KEY_FONT_RATIO ,this.size/CANVAS_KEY_FONT_RATIO);
}
Canvas.prototype.drawMoves = function(){
var text = DIFFICULTIES[this.game.difficulty]+" "+this.game.movesCounter;
var fontSize = this.size/CANVAS_MOVES_FONT_RATIO;
var fontStyle = CANVAS_FONT;
var font = "bold " + fontSize +"px "+fontStyle;
this.canvasContext.fillStyle = CANVAS_MOVES_FONT_COLOR; // font color to write the text with
this.canvasContext.font = font;
this.canvasContext.fillText(text, this.size-fontSize-fontSize/2*text.toString().length ,this.size/CANVAS_MOVES_FONT_RATIO);
}
Canvas.prototype.drawLetterInCorner = function(letter, position,backgroundColor,playable){
var pos = this.positionLetter(position);
this.drawLetter(letter,pos.x,pos.y,backgroundColor,playable);
}
Canvas.prototype.drawNewGameButton = function(color){
var position = this.positionNewGameButton();
var text = '\uf04b';
// var backgroundColor = CANVAS_LETTER_BACKGROUND_COLOR;
var textColor = CANVAS_BUTTON_LETTER_COLOR;
var letterRadius = this.size/CANVAS_BUTTON_RADIUS;
var bold = true;
if(bold){
bold = "bold ";
}
else{
bold = "";
}
this.canvasContext.fillStyle = color;
this.canvasContext.beginPath();
this.canvasContext.arc(position.x, position.y, letterRadius, 0, Math.PI * 2);
this.canvasContext.closePath();
this.canvasContext.fill();
this.canvasContext.fillStyle = textColor; // font color to write the text with
var fontStyle = "FontAwesome";
var font = bold + letterRadius +"px " + fontStyle;
this.canvasContext.font = font;
// Move it down by half the text height and left by half the text width
var width = this.canvasContext.measureText(text).width;
var height = this.canvasContext.measureText("w").width; // this is a GUESS of height
this.canvasContext.fillText(text, position.x - (width/2) ,position.y + (height/2));
}
Canvas.prototype.drawResetButton = function(color){
var position = this.positionResetButton();
var text = '\uf01e';
// var backgroundColor = CANVAS_LETTER_BACKGROUND_COLOR;
var textColor = CANVAS_BUTTON_LETTER_COLOR;
var letterRadius = this.size/CANVAS_BUTTON_RADIUS;
var bold = true;
if(bold){
bold = "bold ";
}
else{
bold = "";
}
this.canvasContext.fillStyle = color;
this.canvasContext.beginPath();
this.canvasContext.arc(position.x, position.y, letterRadius, 0, Math.PI * 2);
this.canvasContext.closePath();
this.canvasContext.fill();
this.canvasContext.fillStyle = textColor; // font color to write the text with
var fontStyle = "FontAwesome";
var font = bold + letterRadius +"px " + fontStyle;
this.canvasContext.font = font;
// Move it down by half the text height and left by half the text width
var width = this.canvasContext.measureText(text).width;
var height = this.canvasContext.measureText("w").width; // this is a GUESS of height
this.canvasContext.fillText(text, position.x - (width/2) ,position.y + (height/2));
}
Canvas.prototype.drawLetter = function(letter, xPosition, yPosition, backgroundColor, playable){
//Styling
var text = letter;
// var backgroundColor = CANVAS_LETTER_BACKGROUND_COLOR;
var textColor = CANVAS_LETTER_COLOR;
var letterRadius = this.size/CANVAS_LETTER_RADIUS;
var bold = true;
if(bold){
bold = "bold ";
}
else{
bold = "";
}
if(playable){
this.canvasContext.fillStyle = CANVAS_PLAYABLE_LETTER_BACKGROUND_COLOR;
this.canvasContext.beginPath();
this.canvasContext.arc(xPosition, yPosition, letterRadius*CANVAS_PLAYABLE_LETTER_RADIUS_RATIO, 0, Math.PI * 2);
this.canvasContext.closePath();
this.canvasContext.fill();
}
this.canvasContext.fillStyle = backgroundColor;
this.canvasContext.beginPath();
this.canvasContext.arc(xPosition, yPosition, letterRadius, 0, Math.PI * 2);
this.canvasContext.closePath();
this.canvasContext.fill();
this.canvasContext.fillStyle = textColor; // font color to write the text with
var fontStyle = CANVAS_FONT;
var font = bold + letterRadius +"px " + fontStyle;
this.canvasContext.font = font;
// Move it down by half the text height and left by half the text width
var width = this.canvasContext.measureText(text).width;
var height = this.canvasContext.measureText("w").width; // this is a GUESS of height
this.canvasContext.fillText(text, xPosition - (width/2) ,yPosition + (height/2));
// To show where the exact center is:
// this.canvasContext.fillRect(pos,pos,5,5);
}
Canvas.prototype.drawGameWon = function(){
var image = document.getElementById(RAINBOW_DIFFICULTIES_IMAGES[this.game.difficulty]);
var size = (this.size)/2;
this.canvasContext.drawImage(image, 0, 0, this.size, this.size);
// this.canvasContext.drawImage(image, this.size/4, this.size/4, size , size* image.height /image.width);
}
Canvas.prototype.positionNewGameButton = function(){
var position = this.size - (this.size)/CANVAS_BUTTON_RADIUS*1.2;
return {"x":position,"y":position};
}
Canvas.prototype.positionResetButton = function(){
var xPosition = this.size - (this.size)/CANVAS_BUTTON_RADIUS*1.4 - ((this.size)/CANVAS_BUTTON_RADIUS)*2;
var yPosition = this.size - (this.size)/CANVAS_BUTTON_RADIUS*1.2;
return {"x":xPosition,"y":yPosition};
}
Canvas.prototype.positionLetter = function(index){
var letterPadding = (CANVAS_LETTER_PADDING / 100) * this.size;
var x = this.size/2 + (this.size/2-this.padding-letterPadding) * Math.cos((2*Math.PI)/16*((index+1)*2-1));
var y = this.size/2 + (this.size/2-this.padding-letterPadding) * Math.sin((2*Math.PI)/16*((index+1)*2-1));
return {"x":x,"y":y};
}
Canvas.prototype.animateLetterMovement = async function(letter, startPosition, endPosition, milliseconds){
var frameRate = CANVAS_FRAME_RATE; //in milliseconds
var frames = milliseconds / frameRate;
var startPos = this.positionLetter(startPosition);
var endPos = this.positionLetter(endPosition);
this.movingLetters[letter] = {"x":startPos.x , "y":startPos.y };
var xAxisMovementRate = (endPos.x - startPos.x )/frames;
var yAxisMovementRate = (endPos.y - startPos.y)/frames;
this.animationInAction = true;
for (var i = 0; i < frames; i++) {
await sleep(frameRate);
startPos.x += xAxisMovementRate;
startPos.y += yAxisMovementRate;
// console.log(this.movingLetters);
this.movingLetters[letter] = {"x":startPos.x , "y":startPos.y };
this.reDraw();
}
this.animationInAction = false;
this.movingLetters[letter] = null;
this.reDraw();
}
Canvas.prototype.getMousePos = function(event){
var rect = this.canvasElement.getBoundingClientRect();
return {
x: Math.round((event.clientX-rect.left)/(rect.right-rect.left)*this.size),
y: Math.round((event.clientY-rect.top)/(rect.bottom-rect.top)*this.size)
};
}
//////////////////////////
////UTILITY FUNCTIONS////
////////////////////////
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
function isAlphaNumeric(str){
var code, i, len;
for (i = 0, len = str.length; i < len; i++) {
code = str.charCodeAt(i);
if (!(code > 47 && code < 58) && // numeric (0-9)
// !(code > 64 && code < 91) && // upper alpha (A-Z)
!(code > 96 && code < 123)) { // lower alpha (a-z)
return false;
}
}
return true;
}
function rightIndex(array, i){
var index = i+1;
if(index == array.length){
index = 0;
}
return index;
}
function leftIndex(array, i){
var index = i-1;
if(index < 0){
index = array.length-1;
}
return index;
}
Array.prototype.contains = function(element){
return this.indexOf(element) > -1;
};
function shuffle(array) {
var currentIndex = array.length, temporaryValue, randomIndex;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
function convertBase(value, from_base, to_base) {
var range = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ+/'.split('');
var from_range = range.slice(0, from_base);
var to_range = range.slice(0, to_base);
var dec_value = value.split('').reverse().reduce(function (carry, digit, index) {
if (from_range.indexOf(digit) === -1) throw new Error('Invalid digit `'+digit+'` for base '+from_base+'.');
return carry += from_range.indexOf(digit) * (Math.pow(from_base, index));
}, 0);
var new_value = '';
while (dec_value > 0) {
new_value = to_range[dec_value % to_base] + new_value;
dec_value = (dec_value - (dec_value % to_base)) / to_base;
}
return new_value || '0';
}
/////////////////////
////////MAIN/////////
/////////////////////
window.onload = function() {
var gameFrame = document.getElementById(RAINBOW_GAME_FRAME);
// var canvasSize = Math.min( gameFrame.clientWidth, gameFrame.clientHeight);
var outerShell = document.getElementById(RAINBOW_GAME_SHELL);
var newWidth = gameFrame.offsetWidth;
var newHeight = gameFrame.offsetWidth;
var gameFinished = false;
outerShell.style.cssText = "height: "+newHeight+"px; width: "+newWidth+"px; font-size: "+newHeight/50+"px;";
var game = new Game(RAINBOW, PRIME, STARTING_DIFFICULTY);
// game.generate("0123456");
game.generate();
var canvas = new Canvas(RAINBOW_CANVAS, CANVAS_PADDING, RAINBOW_IMAGE, RAINBOW_GAME_FRAME, game);
canvas.resetSize();
canvas.reDraw();
//on Resize
window.onresize = function(event) {
newWidth = gameFrame.offsetWidth;
newHeight = gameFrame.offsetWidth;
outerShell.style.cssText = "height: "+newHeight+"px; width: "+newWidth+"px; font-size: "+newHeight/50+"px;";
if(RESIZABLE){
canvas.resetSize();
canvas.reDraw();
}
};
//Dialog Close button listener
var closeButtons = document.getElementsByClassName(RAINBOW_CLOSE);
for (var i = 0; i < closeButtons.length; i++) {
closeButtons[i].addEventListener("click", function(){
game.paused = false;
var newGameDialog = document.getElementById(RAINBOW_NEW_GAME_DIALOG);
newGameDialog.classList.add(RAINBOW_HIDDEN);
});
};
//New Game submit listener
var newGameForm = document.getElementById(RAINBOW_NEW_GAME_FORM);
newGameForm.onsubmit = function(event){
event.preventDefault();
var keyField = document.getElementById(RAINBOW_NEW_GAME_TEXT_FIELD);
var key = keyField.value;
var difficulty = parseInt(document.querySelector('input[name="'+RAINBOW_RADIO_NAME+'"]:checked').value);
var isGameValid = false;
if(key === ""){
game = new Game(RAINBOW,PRIME,difficulty);
game.generate();
isGameValid = true;
}else if(game.isKeyValid(key)){
game = new Game(RAINBOW,PRIME,difficulty);
game.generate(game.decryptKey(key));
isGameValid = true;
}else{
keyField.classList.add(RAINBOW_RED_BORDER);
};
if(isGameValid){
gameFinished = false;
canvas.game = game;
var newGameDialog = document.getElementById(RAINBOW_NEW_GAME_DIALOG);
newGameDialog.classList.add(RAINBOW_HIDDEN);
keyField.classList.remove(RAINBOW_RED_BORDER);
game.paused = false;
canvas.reDraw();
}
}
//Click Listener
canvas.canvasElement.addEventListener('click', function(event){
if(!game.paused){
var mousePos = canvas.getMousePos(event);
var letterRadius = canvas.size/CANVAS_LETTER_RADIUS;
var buttonRadius = canvas.size/CANVAS_BUTTON_RADIUS;
var playableLetters = game.playable();
var playedMoves = [];
//new game button
if(Math.abs(canvas.positionNewGameButton().x - mousePos.x) <= buttonRadius && Math.abs(canvas.positionNewGameButton().y - mousePos.y) <= buttonRadius ){
game.paused = true;
var newGameDialog = document.getElementById(RAINBOW_NEW_GAME_DIALOG);
newGameDialog.classList.remove(RAINBOW_HIDDEN);
}
if(!gameFinished){
//Reset button
if(Math.abs(canvas.positionResetButton().x - mousePos.x) <= buttonRadius && Math.abs(canvas.positionResetButton().y - mousePos.y) <= buttonRadius ){
gameFinished = false;
var key = game.key;
game = new Game(RAINBOW, PRIME, game.difficulty);
game.generate(key);
canvas.game = game;
canvas.reDraw();
}
for (var i = 0; i < playableLetters.length; i++) {
var letterCoordinates = canvas.positionLetter(playableLetters[i]);
if(Math.abs(letterCoordinates.x - mousePos.x) <= letterRadius && Math.abs(letterCoordinates.y - mousePos.y) <= letterRadius ){
playedMoves = game.playMove( playableLetters[i] );
}
}
if(playedMoves.length > 0){
for (var i = 0; i < playedMoves.length; i++) {
canvas.animateLetterMovement(playedMoves[i].value,playedMoves[i].from, playedMoves[i].to, CANVAS_ANIMATION_SPEED);
}
}
if(game.isGameFinished()){
gameFinished = true;
}
}
}
},false);
//Mouse Movement Listener
canvas.canvasElement.addEventListener('mousemove', function(event) {
if(!game.paused){
if(!canvas.animationInAction){
var mousePos = canvas.getMousePos(event);
var letterRadius = canvas.size/CANVAS_LETTER_RADIUS;
var buttonRadius = canvas.size/CANVAS_BUTTON_RADIUS;
var playableLetters = game.playable();
canvas.reDraw();
//new game button
if(Math.abs(canvas.positionNewGameButton().x - mousePos.x) <= buttonRadius && Math.abs(canvas.positionNewGameButton().y - mousePos.y) <= buttonRadius ){
canvas.drawNewGameButton(CANVAS_BUTTON_COLOR_HOVER);
}
if(!gameFinished){
//Reset button
if(Math.abs(canvas.positionResetButton().x - mousePos.x) <= buttonRadius && Math.abs(canvas.positionResetButton().y - mousePos.y) <= buttonRadius ){
canvas.drawResetButton(CANVAS_BUTTON_COLOR_HOVER);
}
for (var i = 0; i < playableLetters.length; i++) {
var letterCoordinates = canvas.positionLetter(playableLetters[i]);
if(Math.abs(letterCoordinates.x - mousePos.x) <= letterRadius && Math.abs(letterCoordinates.y - mousePos.y) <= letterRadius ){
canvas.drawLetterInCorner(game.carousel[playableLetters[i]],playableLetters[i],CANVAS_SELECTED_LETTER_BACKGROUND_COLOR);
}
}
}
}
}
},false);
};