-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathklotski.puzzle.js
2549 lines (2193 loc) · 66 KB
/
klotski.puzzle.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
//=============================================================================
// Klotski (華容道) main program
//
// include libraries: kinetic-v4.5.4.js (http://kineticjs.com/)
// preloadjs-0.6.2.min.js (http://createjs.com/)
// soundjs-0.6.2.min.js (http://createjs.com/)
//
// V1.5
// 01/08/2018 - (1) Change "展示" to "示範"
//
// V1.4
// 09/07/2017 - (1) Bug Fixed: load audio from MicroSoft Edge will cause program hang
// ==> Change to use PreloadJS & SoundJS to load and play audio
// (2) Performance improvement: Slover skip calculation the mirror state
//
// V1.3
// 08/31/2013 - (1) Edit mode: display step number = 0 while press clear button
// (2) Edit mode: change initial block position while switch to edit mode
//
// V1.2
// 08/22/2013 - add assign argument from url
// ex: http://......?l=4-5 (open level 4-5 )
// ex: http://......?l=橫刀立馬 (open classic name = 橫刀立馬)
//
// V1.1
// 08/14/2013 - release version
//
// 08/08/2013 - implement more edit mode (not finished yet!)
//
// V1.1
// 08/03/2013 - add edit mode (not finished yet!)
//
// V1.0
// 07/23/2013 - (1) first version support play mode & demo mode
//
// 05/10/2013 - create by Simon Hung
//=============================================================================
//===========
// define
//===========
var VERSION_STRING = "1.5";
var DATA_VERSION = 1;
var MIN_SCREEN_X = 1000;
var MIN_SCREEN_Y = 650;
var BOTTOM_BOUND = 60; //bottom bound for action button
var BLOCK_CELL_SIZE = 90;
var MAX_MOV_STEP = Math.floor(BLOCK_CELL_SIZE/4);
var CELL_BORDER_SIZE = 0;
var BACKGROUND_COLOR = "#FAFAD2"; //Light Goldenrod Yellow
var TITLE_COLOR = "black";
var BOARD_BORDER_WIDTH = 50;
var BOARD_WIDTH = BLOCK_CELL_SIZE * G_BOARD_X + BOARD_BORDER_WIDTH*2;
var BOARD_HEIGHT = BLOCK_CELL_SIZE * G_BOARD_Y + BOARD_BORDER_WIDTH*2;
var MIN_HINTS_STEP = 5;
var MAX_HINTS_STEP = 10;
var ACTIVE_HINTS_COUNT = 15;
//==================
// global variable
//==================
var screenX, screenY;
var boardStageX, boardStageY;
var titleStartX, titleStartY;
var boardStartX, boardStartY;
var blockStartX, blockStartY;
var minX, minY;
var gStage;
var gBoardLayer;
var gButtonLayer
var gBackgroundLayer; //kinetic layer
var playSpeed = 1; //speed: 1, 2, 3, ..., no used
var dataVersion = 0;
var boardState; //current boardState [x][y]
var stepInfo; //current step information
var manualMoveCount = 0; //move count for active hints button
var cellSize = BLOCK_CELL_SIZE - CELL_BORDER_SIZE;
/*
window.onresize = function(event) {
//alert("resize");
location.reload();
}
*/
window.onload = function()
{
//just for fixed: chrome sets cursor to text while dragging, why?
//http://stackoverflow.com/questions/2745028/chrome-sets-cursor-to-text-while-dragging-why
//This will disable any text selection on the page and it seems that browser starts to show custom cursors.
document.onselectstart = function(){ return false; } ;
init();
loadResource(initBoard); //after resource load complete will callback to initBoard
};
var gLevelSelectObj;
var gCurSelectedBoard;
var gPassLevelDialog;
var gOKDialog;
var gHintsCount;
function init()
{
initScreenSize();
initScreenPosColor();
showLoadingMsg("dialogStage", boardStageX, boardStageY);
}
function initBoard()
{
hideLoadingMsg();
initScreenVariable();
createStageLayer();
addBackgroundLayer();
restoreConfigInfo(); //get config info: volume state & data_version
gLevelSelectObj = new vSelectBoard();
gCurSelectedBoard = gLevelSelectObj.init(
"selectMainStage", "selectTabsStage", "selectBoardStage", boardStageX, boardStageY, setSelectedLevel );
gPassLevelDialog = new passedDialog();
gOKDialog = new okDialog();
stepInfo = [];
gHintsCount = 0;
manualMoveCount = 0;
//------------------------------------
// 08/22/2013
// force assign level from url
//------------------------------------
var assignLevel = getUrlArgument();
if(assignLevel != null) {
getAssignLevel(assignLevel); //direct assign initial level from url //08/22/2013
} else {
getPlayInfo(); //get last step and board info
}
setPlayMode(stepInfo.length);
createFunctionButton();
createGameButton();
enableFunctionButton();
enableVolumeButton();
enableGameButton();
setTimeout(function(){audioPlayStartup();}, 500 );
}
var playMode = 0; //0: start mode, 1: play mode, 2:demo mode, 3: edit mode
function clearLastModeObject(newplayMode)
{
switch(playMode) {
case 1:
clearPlayModeButton();
break;
case 2:
clearDemoModeButton();
break;
case 3:
clearEditModeButton();
break;
}
playMode = newplayMode;
}
function setButtonState()
{
switch(playMode) {
case 1:
setPlayModeButtonState();
break;
case 2:
setDemoModeButtonState();
break;
case 3:
setEditModeButtonState();
break;
}
}
function setPlayMode(step)
{
clearLastModeObject(1); //set mode = "play mode" and clear last
addPlayModeButton();
createBoard(gCurSelectedBoard.boardInfo.board);
moveBoardStep(step);
}
function setDemoMode()
{
clearLastModeObject(2); //set mode = "demo mode" and clear last
addDemoModeButton();
createBoard(gCurSelectedBoard.boardInfo.board);
var rc = setAutoMoveStepInfo();
moveBoardStep(0);
return rc;
}
function setEditMode()
{
clearLastModeObject(3); //set mode = "edit mode" and clear last
addEditModeButton();
createEditBoard();
writeStepInfo(0);
}
//---------------------------------------------------------
// get url argument (08/22/2013)
// format : (1) http://....?l=2-1 (level 2-1)
// (2) http://....?l=橫刀立馬 (by classic name)
//---------------------------------------------------------
function getUrlArgument()
{
var urltext = decodeURIComponent(document.location.href);
if (urltext.indexOf('?') < 0) return null;
var argText = urltext.substring(urltext.indexOf('?')+1).replace(/\s/g, '');
//----------------------------------------------------------------
//reference: http://www.w3schools.com/jsref/jsref_obj_regexp.asp
//----------------------------------------------------------------
if( /l=\d{1,2}-\d{1,2}/.test(argText)) { // l=3-5 or l=1-56
return { type:'tabsLevel', tabsLevel: argText.substring(2).split("-") };
}
if(argText.indexOf('l=') == 0 && argText.length >= 3) { //l=橫刀立馬
return { type:'name', name: argText.substring(2) };
}
return null;
}
//---------------------------------------
// get assign level from boardlist info
// 08/22/2013
//---------------------------------------
function getAssignLevel(assignLevel)
{
var newSelectedBoard = null;
switch(assignLevel.type) {
case 'tabsLevel': //by tabs-level
var tabsId = parseInt(assignLevel.tabsLevel[0], 10) - 1; // (0 - )
var level = parseInt(assignLevel.tabsLevel[1],10); // (1 - )
newSelectedBoard = gLevelSelectObj.changeBoardByTabsLevel(tabsId, level);
break;
case 'name': //by classic name
newSelectedBoard = gLevelSelectObj.changeBoardByClassicName(assignLevel.name);
break;
default:
break;
}
if(newSelectedBoard != null) {
gCurSelectedBoard = newSelectedBoard;
stepInfo = [];
gHintsCount = 0;
manualMoveCount = 0;
}
}
//-----------------------------------------------------
//get last play step & board info from local storage
//-----------------------------------------------------
function getPlayInfo()
{
var playInfo = restorePlayInfo();
if(playInfo == null) return;
var newSelectedBoard = gLevelSelectObj.changeSelectedBoard(playInfo);
if(newSelectedBoard != null) {
gCurSelectedBoard = newSelectedBoard;
stepInfo = playInfo.stepInfo;
gHintsCount = playInfo.hints;
manualMoveCount = playInfo.moveCount;
}
}
function initScreenSize()
{
screenX = 0, screenY = 0;
//----------------------------------------------------------------------
// Window size and scrolling:
// URL: http://www.howtocreate.co.uk/tutorials/javascript/browserwindow
//----------------------------------------------------------------------
if( typeof( window.innerWidth ) == 'number' ) {
//Non-IE
screenX = window.innerWidth;
screenY = window.innerHeight;
} else if((document.documentElement) &&
(document.documentElement.clientWidth || document.documentElement.clientHeight ) )
{
//IE 6+ in 'standards compliant mode'
screenX = document.documentElement.clientWidth;
screenY = document.documentElement.clientHeight;
} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
//IE 4 compatible
screenX = document.body.clientWidth;
screenY = document.body.clientHeight;
}
if(screenX < MIN_SCREEN_X) boardStageX = MIN_SCREEN_X;
else boardStageX = screenX - 10;
if(screenY < MIN_SCREEN_Y) boardStageY = MIN_SCREEN_Y;
else boardStageY = screenY - 10;
boardStartX = Math.floor((boardStageX - BOARD_WIDTH )/2);
//boardStartY = Math.floor((boardStageY - BOARD_HEIGHT)/2);
boardStartY = Math.floor((boardStageY - BOTTOM_BOUND - BOARD_HEIGHT)/2);
}
function initScreenVariable()
{
levelNameStartX = boardStartX + 50;
levelNameStartY = boardStartY + 30;
stepMsgStartX = boardStartX + BOARD_WIDTH-60;
stepMsgStartY = boardStartY + 30;
titleStartX = 10;
titleStartY = 10;
titleScale = (images.title.width+30 > boardStartX)?boardStartX/(images.title.width)-0.1:1;
// +== blockStartX
// |
// V
// +----------------+
// | +------------+ | <== blockStartY
// | | | |
blockStartX = Math.floor((boardStageX - G_BOARD_X * BLOCK_CELL_SIZE)/2);
//blockStartY = Math.floor((boardStageY - G_BOARD_Y * BLOCK_CELL_SIZE)/2);
blockStartY = boardStartY + Math.floor((BOARD_HEIGHT - G_BOARD_Y * BLOCK_CELL_SIZE)/2);
minX = blockStartX + CELL_BORDER_SIZE/2; //while CELL_BORDER_SIZE = 0, minX = blockStartX
minY = blockStartY+ CELL_BORDER_SIZE/2; //while CELL_BORDER_SIZE = 0, minY = blockStartY
}
function initScreenPosColor()
{
var baseX = 100;
var boardStageOffsetX = Math.floor((screenX - boardStageX)/2);
var boardStageOffsetY = Math.floor((screenX - boardStageY)/2);
document.getElementById('selectMainStage').style.cssText = "top:" + (10) + "px; left:" + (10) + "px; position: absolute;";
document.getElementById('selectTabsStage').style.cssText = "top:" + (20) + "px; left:" + (20) + "px; position: absolute;";
document.getElementById('selectBoardStage').style.cssText = "top:" + (55) + "px; left:" + (30) + "px; position: absolute;";
}
//------------------------------------------------------
// select new level
// isCallback: means callback from select level dialog
//------------------------------------------------------
function setSelectedLevel(selectedBoard, isCallback)
{
stepInfo = [];
gHintsCount = 0;
manualMoveCount = 0;
switch(playMode) {
case 1:
case 2:
gCurSelectedBoard = selectedBoard;
createBoard(gCurSelectedBoard.boardInfo.board);
//1: play mode, 2:demo mode
if(playMode == 2) { //demo mode
savePlayModeInfo();
var rc = setAutoMoveStepInfo();
//display animation title while callback from board select
if(isCallback) animateTitle(gTxtMsg.DemoMode, rc.time);
} else {
//if(isCallback) animateTitle(gTxtMsg.GameMode);
}
moveBoardStep(0);
break;
case 3:
setEditBoard(selectedBoard.boardInfo.board);
break;
}
}
function createStageLayer()
{
//create stage object
gStage = new Kinetic.Stage({
container: 'boardStage',
width: boardStageX,
height: boardStageY
});
//create layer object
gBackgroundLayer = new Kinetic.Layer();
gMessageLayer = new Kinetic.Layer();
gButtonLayer = new Kinetic.Layer();
gBoardLayer = new Kinetic.Layer();
gStage.add(gBackgroundLayer);
gStage.add(gMessageLayer);
gStage.add(gButtonLayer);
gStage.add(gBoardLayer);
}
//--------------------------
// add background to layer
//--------------------------
function addBackgroundLayer()
{
var borderWidth = 20;
var textOffset = 15;
var titleFontSize = 55;
var titleText2 = new Kinetic.Text({
x: textOffset,
y: boardStageY-titleFontSize,
text: "Klotski",
fill: BACKGROUND_COLOR,
fontSize: titleFontSize,
//fontFamily: "Calibri",
fontStyle:"bold",
shadowColor: 'black',
shadowBlur: 10,
shadowOffset: [2, 2],
shadowOpacity:0.3
});
var versionText = new Kinetic.Text({
x: textOffset+titleText2.getWidth(),
y: boardStageY-titleFontSize/3,
text: VERSION_STRING,
fill: BACKGROUND_COLOR,
fontSize: titleFontSize/3,
fontStyle:"bold",
shadowColor: 'black',
shadowBlur: 9,
shadowOffset: [2, 2],
shadowOpacity:0.3
});
var background = new Kinetic.Rect({
x: 0,
y: 0,
width: boardStageX,
height: boardStageY,
fill: BACKGROUND_COLOR
});
var board = new Kinetic.Rect({
x: boardStartX,
y: boardStartY,
width: BOARD_WIDTH,
height: BOARD_HEIGHT,
fillPatternImage: images.board
});
var title = new Kinetic.Image({
x: titleStartX,
y: titleStartY,
image: images.title,
scaleX:titleScale,
scaleY:titleScale
});
document.body.style.background = BACKGROUND_COLOR; //body background color
gBackgroundLayer.add(background);
gBackgroundLayer.add(title);
gBackgroundLayer.add(titleText2);
gBackgroundLayer.add(versionText);
gBackgroundLayer.add(board);
gBackgroundLayer.draw();
}
//------------------------------------
// initial board state & create block
//------------------------------------
var blockObj = [];
function createBoard(boardString)
{
blockObj = [];
curBoardStep = 0;
boardState = [];
for(var x = 0; x < G_BOARD_X; x++) {
boardState[x] = [];
for(var y = 0; y < G_BOARD_Y; y++) {
boardState[x][y] = -1;
}
}
gBoardLayer.removeChildren();
var blockId = 1; //blockObj[0] : for empty (don't use)
var i = 0;
var VOID_CHAR = '?';
for(var y = 0; y < G_BOARD_Y; y++) {
for(var x = 0; x < G_BOARD_X; x++) {
if(boardState[x][y] >= 0) { i++; continue;}
var style = gBlockBelongTo[boardString.charCodeAt(i++) - VOID_CHAR.charCodeAt(0)];
//don't create block for empty
if(style) blockObj[blockId] = createBlock(blockId, x, y, style, playMode==1?1:0);
var sizeX = gBlockStyle[style][0];
var sizeY = gBlockStyle[style][1];
for(var xx = 0; xx < sizeX; xx++) {
for(var yy = 0; yy < sizeY; yy++) {
boardState[x+xx][y+yy] = style?blockId:0; //empty id = 0;
}
}
if(style) blockId++;
}
}
gBoardLayer.draw();
}
//----------------------------------------------
// build board from boardState
// ==> move exist block to boardState position
//----------------------------------------------
function buildBoard(boardState)
{
var tmpBoardState = [];
var id = 0;
//copy 2 dimensional array
for(var x = 0; x < G_BOARD_X; x++) {
tmpBoardState[x] = boardState[x].slice(0);
}
for(var y = 0; y < G_BOARD_Y; y++) {
for(var x = 0; x < G_BOARD_X; x++) {
if((id = tmpBoardState[x][y]) != 0) {
blockObj[id].movePos(x,y);
//clear current block
var sizeX = blockObj[id].getAttr('sizeX');
var sizeY = blockObj[id].getAttr('sizeY');
for(var yy = 0; yy < sizeY; yy++) {
for(var xx = 0; xx < sizeX; xx++) {
tmpBoardState[x+xx][y+yy] = 0;
}
}
}
}
}
gBoardLayer.draw();
}
//------------------------------------------
// Text message to screen (for debug only)
//------------------------------------------
function writeMessage(message)
{
var context = gMessageLayer.getContext();
//gMessageLayer.clear();
context.font = '12pt arial';
context.fillStyle = 'blue';
context.fillText(message+" ", 20,20);
}
//-----------------------------------------
// display board title and move step info
//-----------------------------------------
function writeStepInfo(step, auto)
{
var context = gMessageLayer.getContext();
gMessageLayer.clear();
if(typeof auto == 'undefined') auto = 0;
if(auto) {
context.fillStyle = '#C40000';
context.strokeStyle = "#FFBBCC";
} else {
context.fillStyle = '#0000C4';
context.strokeStyle = "#BABAFA";
}
var len = (1 - (step+"").length)*12;
context.font = '17pt Calibri';
context.strokeText(step, stepMsgStartX+1+len, stepMsgStartY+1);
context.fillText(step, stepMsgStartX+len, stepMsgStartY);
var titleInfo = gCurSelectedBoard.titleInfo;
if(playMode == 3) { //edit mode
titleInfo = gTxtMsg.EditMode;
}
context.font = '18pt Calibri';
context.fillStyle = "#BABAFA";
context.fillText(titleInfo, levelNameStartX+1, levelNameStartY+1);
context.fillStyle = "#0000C4";
context.fillText(titleInfo, levelNameStartX, levelNameStartY);
}
//----------------------------------
// screen point to board position
//----------------------------------
function point2Pos(x,y)
{
var posX = posY = 0;
var offsetX = x - minX;
if(offsetX < 0) offsetX = 0;
while(offsetX >= BLOCK_CELL_SIZE) { offsetX -= BLOCK_CELL_SIZE; posX++;}
var offsetY = y - minY;
if(offsetY < 0) offsetY = 0;
while(offsetY >= BLOCK_CELL_SIZE) { offsetY -= BLOCK_CELL_SIZE; posY++;}
return {posX: posX, posY: posY, offsetX: offsetX, offsetY: offsetY};
}
//----------------------------------------
// check shiftX, don't out of the board X
//----------------------------------------
function getShiftX(x, y, shiftX, blockSizeX, blockSizeY)
{
var posX = posY = 0;
var offsetY = y - minY;
if(offsetY < 0) offsetY = 0;
while(offsetY >= BLOCK_CELL_SIZE) { offsetY -= BLOCK_CELL_SIZE; posY++;}
var offsetX;
if(shiftX < 0) {
//block left position
offsetX = x - minX + shiftX;
if(offsetX < 0) {
return shiftX-offsetX;
}
while(offsetX >= BLOCK_CELL_SIZE) { offsetX -= BLOCK_CELL_SIZE; posX++;}
if(!allCellYEmpty(posX, posY,blockSizeY)) {
return shiftX + BLOCK_CELL_SIZE - offsetX;
}
} else {
//block right position
offsetX = x - minX + shiftX + BLOCK_CELL_SIZE * blockSizeX - 1;
if(offsetX < 0) error("desgin error");
while(offsetX >= BLOCK_CELL_SIZE) { offsetX -= BLOCK_CELL_SIZE; posX++;}
if(posX >= G_BOARD_X || !allCellYEmpty(posX, posY,blockSizeY)) {
return shiftX - offsetX - 1;
}
}
return shiftX;
}
//----------------------------------------
// check shiftY, don't out of the board Y
//----------------------------------------
function getShiftY(x, y, shiftY, blockSizeX, blockSizeY)
{
var posX = posY = 0;
var offsetX = x - minX;
if(offsetX < 0) offsetX = 0;
while(offsetX >= BLOCK_CELL_SIZE) { offsetX -= BLOCK_CELL_SIZE; posX++;}
var offsetY;
if(shiftY < 0) {
//block up position
var offsetY = y - minY + shiftY;
if(offsetY < 0) {
return shiftY-offsetY;
}
while(offsetY >= BLOCK_CELL_SIZE) { offsetY -= BLOCK_CELL_SIZE; posY++;}
if(!allCellXEmpty(posX, posY,blockSizeX)) {
return shiftY + BLOCK_CELL_SIZE - offsetY;
}
} else {
//block down position
var offsetY = y - minY + shiftY + BLOCK_CELL_SIZE * blockSizeY - 1;
if(offsetY < 0) debug("desgin error");
while(offsetY >= BLOCK_CELL_SIZE) { offsetY -= BLOCK_CELL_SIZE; posY++;}
if(posY >= G_BOARD_Y || !allCellXEmpty(posX, posY,blockSizeX)) {
return shiftY - offsetY - 1;
}
}
return shiftY;
}
//----------------------------------------------------------
// check all cell (x,y), (x+1,y) ...(x+size,y) are empty
//----------------------------------------------------------
function allCellXEmpty(x, y, size)
{
for(var i = 0; i < size; i++) {
if(boardState[x+i][y] != 0) return 0;
}
return 1;
}
//----------------------------------------------------------
// check all cell (x,y), (x,y+1) ...(x,y+size) are empty
//----------------------------------------------------------
function allCellYEmpty(x, y, size)
{
for(var i = 0; i < size; i++) {
if(boardState[x][y+i] != 0) return 0;
}
return 1;
}
//---------------------------------------------
// change block style value from (posX, posY)
//---------------------------------------------
function setBoardState(boardState, posX, posY, style, value)
{
var sizeX = gBlockStyle[style][0];
var sizeY = gBlockStyle[style][1];
for(var y = 0; y < sizeY; y++) {
for(var x = 0; x < sizeX; x++) {
boardState[posX+x][posY+y] = value;
}
}
}
//-----------------------------------------------------
// |1bit| 5 bit | 4 bit| 4 bit|4bit|4bit|
// stepInfo = |auto|blockId|startX|startY|endX|endY|
// 21| 16| 12| 8| 4| 0|
//-----------------------------------------------------
function stepInfo2PosInfo(stepId)
{
var value = stepInfo[stepId-1];
var autoPlay = (value >> 21) & 0x1;
var blockId = (value >> 16) & 0x1f; //for work with edit mode (14 + 6 + 6 + 1 = 27 blocks for edit)
var startX = (value >> 12) & 0xf;
var startY = (value >> 8) & 0xf;
var endX = (value >> 4) & 0xf;
var endY = value & 0xf;
return { id: blockId, startX: startX, startY: startY, endX: endX, endY: endY, auto: autoPlay }
}
//----------------------------------------------------------------------------------
// add new move step to stepInfo
// (1) append will add to last
// (2) if curBoardStep < stepInfo.length means usr press the undo button
// cut off remain and add new
// (3) if auto enable (move by click hints button) will not merge with old step
//---------------------------------------------------------------------------------
var curBoardStep = 0;
function setStepInfo(id, startX, startY, endX, endY, auto, append)
{
var curStep = stepInfo.length;
if(startX == endX && startY == endY) return curBoardStep;
if(!append && curStep > curBoardStep) {
// remove undo steps
stepInfo.splice(curBoardStep, curStep - curBoardStep);
curStep = curBoardStep;
}
if(!auto && curStep != 0) {
var lastPosInfo = stepInfo2PosInfo(curStep);
if(lastPosInfo.endX == startX && lastPosInfo.endY == startY) {
//same block with last moved
if(lastPosInfo.startX == endX && lastPosInfo.startY == endY) {
//same block move back to last moved
// ==> remove last step
stepInfo.pop();
curStep--;
} else {
//update last step
stepInfo[curStep-1] = ((auto?1:0)<<21) + (id << 16) + (lastPosInfo.startX << 12) + (lastPosInfo.startY << 8) + (endX << 4) + endY;
}
curBoardStep = curStep;
return curStep;
}
}
stepInfo[curStep++] = ((auto?1:0)<<21) + (id << 16) + (startX << 12) + (startY << 8) + (endX << 4) + endY;
if(!auto) {
curBoardStep = curStep;
manualMoveCount++; //move count for enable hints button
}
return curStep;
}
//----------------------------------------------------
// get move action combine with: "U", "D", "L", "R"
// only work with empty cell <= 3
//----------------------------------------------------
function getStepAction(posInfo, back, reverse)
{
var dirX, dirY, style;
var sizeX, sizeY;
var posX, posY;
var action = [];
if(back) { //from (endX, endY) to (startX, startY)
dirX = posInfo.startX - posInfo.endX;
dirY = posInfo.startY - posInfo.endY;
posX = posInfo.endX;
posY = posInfo.endY;
} else { //from (startX, startY) to (endX, endY)
dirX = posInfo.endX - posInfo.startX;
dirY = posInfo.endY - posInfo.startY;
posX = posInfo.startX;
posY = posInfo.startY;
}
style = blockObj[posInfo.id].getAttr('style');
sizeX = gBlockStyle[style][0];
sizeY = gBlockStyle[style][1];
while(dirX || dirY) {
var errCheck = 0;
while (dirY < 0 && allCellXEmpty(posX, posY-1, sizeX) == 1) {
action.push('U'); dirY++; posY--;
errCheck = 1;
}
while(dirY > 0 && allCellXEmpty(posX, posY+sizeY, sizeX) == 1) {
action.push('D'); dirY--; posY++;
errCheck = 1;
}
while(dirX < 0 && allCellYEmpty(posX-1, posY, sizeY) == 1) {
action.push('L'); dirX++; posX--;
errCheck = 1;
}
while(dirX > 0 && allCellYEmpty(posX+sizeX, posY, sizeY) == 1) {
action.push('R'); dirX--; posX++;
errCheck = 1;
}
if(!errCheck) { //too many empty may cause this error (empty cell > 3)
error("getStepAction(): design error!");
break;
}
}
if(reverse) {
var rAction = [];
var size = action.length;
for(var i = 0; i < size; i++) {
switch(action[size-1-i]) {
case 'U':
rAction[i] = 'D';
break;
case 'D':
rAction[i] = 'U';
break;
case 'L':
rAction[i] = 'R';
break;
case 'R':
rAction[i] = 'L';
break;
}
}
//debug("id=" + posInfo.id + " " + rAction );
action = rAction;
}
debug("id=" + posInfo.id + " " + action );
return {auto: posInfo.auto, move: action}
}
function createBlock(id, x, y, style, draggable)
{
var block = new Kinetic.Rect({
//begin mine attributes ===============================
id: id,
startPosX: x,
startPosY: y,
sizeX: gBlockStyle[style][0],
sizeY: gBlockStyle[style][1],
style: style,
blockMoved: 0,
//endn mine attributes ================================
x: minX+BLOCK_CELL_SIZE*x,
y: minY+BLOCK_CELL_SIZE*y,
width: BLOCK_CELL_SIZE*gBlockStyle[style][0]-CELL_BORDER_SIZE,
height: BLOCK_CELL_SIZE*gBlockStyle[style][1]-CELL_BORDER_SIZE,
fillPatternImage: images['block' + style],
//fill: '#00D2FF',
//stroke: 'black',
strokeWidth: CELL_BORDER_SIZE,
draggable:draggable,
dragBoundFunc: function(lastPos) { //last position
var curX = this.getPosition().x; //current position
var curY = this.getPosition().y;
var shiftX = lastPos.x - curX, shiftY = lastPos.y - curY;
//console.log("x,y = (" + curX + "," + curY + ") x1,y1 = (" + lastPos.x + "," + lastPos.y + ")");
if(Math.abs(shiftX) > MAX_MOV_STEP) { //don't move to fast cause over 1 position
if(shiftX > 0) shiftX = MAX_MOV_STEP;
else shiftX = -MAX_MOV_STEP;
}
if(Math.abs(shiftY) > MAX_MOV_STEP) {
if(shiftY > 0) shiftY = MAX_MOV_STEP;
else shiftY = -MAX_MOV_STEP;
}
var moveDirectionH = 0, moveDirectionV = 0, moveDirection = 0;
var curPos = point2Pos(curX, curY); //block position of left-up cell
switch(true) {
case (curPos.offsetX == 0 && curPos.offsetY == 0): //two direction for choice
if(shiftY < 0 && curPos.posY > 0 && allCellXEmpty(curPos.posX, curPos.posY-1, this.getAttr('sizeX'))) {
moveDirectionV = 1; //move UP
}
if(shiftY > 0 && curPos.posY+this.getAttr('sizeY') < G_BOARD_Y && allCellXEmpty(curPos.posX, curPos.posY+this.getAttr('sizeY'), this.getAttr('sizeX'))) {
moveDirectionV = 2; //move down
}
if(shiftX < 0 && curPos.posX > 0 && allCellYEmpty(curPos.posX-1, curPos.posY, this.getAttr('sizeY'))) {
moveDirectionH = 3; //move left
}
if(shiftX > 0 && curPos.posX+this.getAttr('sizeX') < G_BOARD_X && allCellYEmpty(curPos.posX+this.getAttr('sizeX'), curPos.posY, this.getAttr('sizeY'))) {
moveDirectionH = 4; //move right
}
switch(true) {
case (moveDirectionV != 0 && moveDirectionH != 0): //select one
if(Math.abs(shiftX) > Math.abs(shiftY)) moveDirection = moveDirectionH; //select move H
else moveDirection = moveDirectionV; //select move V
break;
case (moveDirectionV != 0):
moveDirection = moveDirectionV;
break;
case (moveDirectionH != 0):
moveDirection = moveDirectionH;
break;
}
break;
case (curPos.offsetX == 0):
if(shiftY < 0) moveDirection = 1; //up
else if(shiftY > 0) moveDirection = 2; //down
break;
case (curPos.offsetY == 0):
if(shiftX < 0) moveDirection = 3; //left
else if(shiftX > 0) moveDirection = 4; //right
break;
default:
error("createBlock(): design error !");
break;
}
if(moveDirection == 0) {
return { x:curX, y: curY }; //don't need move
}
switch(moveDirection) {
case 1: //up
case 2: //down
shiftX = 0;
shiftY = getShiftY(curX, curY, shiftY, this.getAttr('sizeX'), this.getAttr('sizeY'));
break;
case 3: //left
case 4: //right
shiftY = 0;
shiftX = getShiftX(curX, curY, shiftX, this.getAttr('sizeX'), this.getAttr('sizeY'));
break;
default:
error("createBlock(): design error");
break;
}
if(shiftX != 0 || shiftY != 0) this.setAttrs({blockMoved:1});
return {x: curX+shiftX, y:curY+shiftY};
}
});
block.setPos = function(x,y)
{
this.setAttrs({startPosX: x, startPosY: y});
}
block.movePos = function(x,y)
{
var curX = minX + x * BLOCK_CELL_SIZE;
var curY = minY + y * BLOCK_CELL_SIZE;
this.setAttrs({startPosX: x, startPosY: y});
this.setPosition(curX, curY);
}