-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
1295 lines (1184 loc) · 40.2 KB
/
Copy pathmain.js
File metadata and controls
1295 lines (1184 loc) · 40.2 KB
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
'use strict'
function LinkGame(config) {
if (!(this instanceof LinkGame)) {
return new LinkGame(config);
}
this.score = 0; // 得分
this.$box = $('#' + (config.boxId || 'game'));
this.cellWidth = config.cellWidth || 42; // 每格的的宽度
this.cellHeight = config.cellHeight || 42; // 每格的高度
this.cols = config.cols + 2 || 10; // 列数
this.rows = config.rows + 2 || 8; // 行数
this.level = config.level || 0; // 等级
this.leftDisorderTime = 5; // 剩余重排次数
// 检查是否有自定义图片,如果有则使用自定义图片,否则使用默认图片
if (customImageManager && customImageManager.hasImages()) {
// 存储图片对象(包含URL和文件名)
this.giftObjects = customImageManager.getImageObjects();
// 同时保存URL数组以便兼容现有代码
this.gifts = customImageManager.getImages();
console.log('使用自定义图片,共', this.gifts.length, '张');
} else {
// 默认小图片集合 - 作为对象数组存储,包含URL和文件名
this.giftObjects = [
{ url: 'images/gifts/0.png', fileName: '礼物0' },
{ url: 'images/gifts/1.png', fileName: '礼物1' },
{ url: 'images/gifts/2.png', fileName: '礼物2' },
{ url: 'images/gifts/3.png', fileName: '礼物3' },
{ url: 'images/gifts/4.png', fileName: '礼物4' },
{ url: 'images/gifts/5.png', fileName: '礼物5' },
{ url: 'images/gifts/6.png', fileName: '礼物6' },
{ url: 'images/gifts/7.png', fileName: '礼物7' },
{ url: 'images/gifts/8.png', fileName: '礼物8' },
{ url: 'images/gifts/9.png', fileName: '礼物9' },
{ url: 'images/gifts/10.png', fileName: '礼物10' },
{ url: 'images/gifts/11.png', fileName: '礼物11' },
{ url: 'images/gifts/12.png', fileName: '礼物12' },
{ url: 'images/gifts/13.png', fileName: '礼物13' },
{ url: 'images/gifts/14.png', fileName: '礼物14' },
{ url: 'images/gifts/15.png', fileName: '礼物15' },
{ url: 'images/gifts/16.png', fileName: '礼物16' },
{ url: 'images/gifts/17.png', fileName: '礼物17' },
{ url: 'images/gifts/18.png', fileName: '礼物18' },
{ url: 'images/gifts/19.png', fileName: '礼物19' },
{ url: 'images/gifts/20.png', fileName: '礼物20' },
{ url: 'images/gifts/21.png', fileName: '礼物21' },
{ url: 'images/gifts/22.png', fileName: '礼物22' },
{ url: 'images/gifts/23.png', fileName: '礼物23' },
{ url: 'images/gifts/24.png', fileName: '礼物24' },
{ url: 'images/gifts/25.png', fileName: '礼物25' },
{ url: 'images/gifts/26.png', fileName: '礼物26' },
{ url: 'images/gifts/27.png', fileName: '礼物27' },
{ url: 'images/gifts/28.png', fileName: '礼物28' },
];
// 同时保存URL数组以便兼容现有代码
this.gifts = this.giftObjects.map(obj => obj.url);
console.log('使用默认图片');
}
this.nums = [
'images/0.png',
'images/1.png',
'images/2.png',
'images/3.png',
'images/4.png',
'images/5.png',
'images/6.png',
'images/7.png',
'images/8.png',
'images/9.png',
];
this.xnums = [
'images/x0.png',
'images/x1.png',
'images/x2.png',
'images/x3.png',
'images/x4.png',
'images/x5.png',
];
this.pnums = [
'images/p0.png',
'images/p1.png',
'images/p2.png',
'images/p3.png',
'images/p4.png',
'images/p5.png',
'images/p6.png',
'images/p7.png',
'images/p8.png',
'images/p9.png',
];
return this;
}
// IndexedDBImageManager已在HTML中直接引入
// 自定义图片管理器
function CustomImageManager() {
this.customImages = [];
this.idbManager = null;
this.initialized = false;
this.initPromise = this.initialize();
}
CustomImageManager.prototype = {};
// 初始化方法
CustomImageManager.prototype.initialize = async function () {
try {
// IndexedDBImageManager已在HTML中直接引入
this.idbManager = new IndexedDBImageManager();
await this.loadFromStorage();
this.initialized = true;
} catch (error) {
console.error('初始化CustomImageManager失败:', error);
this.initialized = false;
}
};
// 从IndexedDB加载自定义图片
CustomImageManager.prototype.loadFromStorage = async function () {
try {
this.customImages = [];
const images = await this.idbManager.getAllImages();
// 处理可能的数据格式转换
images.forEach(image => {
this.customImages.push({
url: image.url,
fileName: image.fileName
});
});
console.log('加载了存储的自定义图片:', this.customImages.length, '张');
} catch (e) {
console.error('加载存储的自定义图片失败:', e);
this.customImages = [];
}
};
// 压缩图片
CustomImageManager.prototype._compressImage = function (dataUrl, maxWidth = 500, quality = 0.8) {
return new Promise((resolve) => {
const img = new Image();
img.onload = function () {
const canvas = document.createElement('canvas');
let width = img.width;
let height = img.height;
// 保持比例缩小图片
if (width > maxWidth) {
const ratio = maxWidth / width;
width = maxWidth;
height = height * ratio;
}
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0, width, height);
// 转换为base64
const compressedDataUrl = canvas.toDataURL('image/jpeg', quality);
resolve(compressedDataUrl);
};
img.src = dataUrl;
});
};
// 保存到IndexedDB
CustomImageManager.prototype.saveToStorage = async function () {
try {
await this.idbManager.clearAll();
for (let i = 0; i < this.customImages.length; i++) {
const image = this.customImages[i];
// 修复参数传递问题:将image对象作为单个参数传递
await this.idbManager.addImage(image);
}
console.log('保存自定义图片到IndexedDB成功');
return true;
} catch (e) {
console.error('保存自定义图片到IndexedDB失败:', e);
return false;
}
};
// 添加图片
CustomImageManager.prototype.addImage = async function (dataUrl, fileName) {
// 等待初始化完成
await this.initPromise;
if (!this.initialized) {
console.error('CustomImageManager尚未初始化完成,无法添加图片');
return false;
}
try {
// 检查是否有相同的图片
const exists = this.customImages.some(img => img.fileName === fileName);
if (exists) {
alert('已存在同名图片!');
return false;
}
// 压缩图片
const compressedDataUrl = await this._compressImage(dataUrl);
// 添加到数组
this.customImages.push({
url: compressedDataUrl,
fileName: fileName
});
// 保存到IndexedDB
const saveResult = await this.saveToStorage();
if (saveResult) {
console.log('添加图片成功:', fileName);
return true;
} else {
// 保存失败,从数组中移除
this.customImages.pop();
console.error('添加图片失败,保存到IndexedDB失败');
return false;
}
} catch (e) {
console.error('添加图片时发生错误:', e);
return false;
}
};
// 移除图片
CustomImageManager.prototype.removeImage = async function (index) {
// 等待初始化完成
await this.initPromise;
if (!this.initialized) {
console.error('CustomImageManager尚未初始化完成,无法删除图片');
return false;
}
try {
if (index >= 0 && index < this.customImages.length) {
this.customImages.splice(index, 1);
const saveResult = await this.saveToStorage();
if (saveResult) {
console.log('删除图片成功');
return true;
} else {
console.error('删除图片失败,保存到IndexedDB失败');
return false;
}
} else {
console.error('删除图片失败,索引无效');
return false;
}
} catch (e) {
console.error('删除图片时发生错误:', e);
return false;
}
};
// 获取所有图片
CustomImageManager.prototype.getImages = function () {
return this.customImages.map(image => image.url);
};
// 获取所有图片对象
CustomImageManager.prototype.getImageObjects = function () {
return this.customImages;
};
// 检查是否有自定义图片
CustomImageManager.prototype.hasImages = function () {
return this.customImages.length > 0;
};
// 导出图片配置
CustomImageManager.prototype.exportImages = async function () {
// 等待初始化完成
await this.initPromise;
if (!this.initialized) {
console.error('CustomImageManager尚未初始化完成,无法导出图片');
return false;
}
try {
const data = {
version: 1,
exportTime: new Date().toISOString(),
images: this.customImages
};
// 创建Blob对象
const blob = new Blob([JSON.stringify(data)], { type: 'application/json' });
// 创建下载链接
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `linklink_images_${new Date().getTime()}.json`;
a.click();
// 释放URL对象
URL.revokeObjectURL(url);
console.log('导出图片配置成功');
return true;
} catch (e) {
console.error('导出图片配置失败:', e);
return false;
}
};
// 导入图片配置
CustomImageManager.prototype.importImages = async function (jsonData) {
// 等待初始化完成
await this.initPromise;
if (!this.initialized) {
console.error('CustomImageManager尚未初始化完成,无法导入图片');
return false;
}
try {
let data;
// 尝试解析JSON数据
try {
data = JSON.parse(jsonData);
} catch (e) {
console.error('JSON解析失败:', e);
alert('导入文件格式错误!');
return false;
}
// 检查数据格式
if (!data.images || !Array.isArray(data.images)) {
// 尝试兼容旧格式
try {
const oldImages = JSON.parse(jsonData);
if (Array.isArray(oldImages)) {
this.customImages = oldImages;
await this.saveToStorage();
console.log('成功导入旧格式的图片配置');
return true;
}
} catch (e) {
console.error('尝试兼容旧格式失败:', e);
}
console.error('数据格式错误,没有images数组');
alert('导入文件格式错误!');
return false;
}
// 验证每个图片对象
const validImages = [];
for (let i = 0; i < data.images.length; i++) {
const img = data.images[i];
if (img.url && img.fileName) {
validImages.push(img);
}
}
// 保存导入的图片
this.customImages = validImages;
const saveResult = await this.saveToStorage();
if (saveResult) {
console.log('导入图片配置成功,共导入', validImages.length, '张图片');
return true;
} else {
console.error('导入图片配置失败,保存到IndexedDB失败');
return false;
}
} catch (e) {
console.error('导入图片配置时发生错误:', e);
return false;
}
};
// 清除所有自定义图片
CustomImageManager.prototype.clearAll = async function () {
// 等待初始化完成
await this.initPromise;
if (!this.initialized) {
console.error('CustomImageManager尚未初始化完成,无法清除图片');
return false;
}
try {
this.customImages = [];
await this.idbManager.clearAll();
console.log('清除所有自定义图片成功');
return true;
} catch (e) {
console.error('清除所有自定义图片失败:', e);
return false;
}
};
;
// 创建自定义图片管理器实例
const customImageManager = new CustomImageManager();
// 为CustomImageManager类添加重新初始化方法
CustomImageManager.prototype.reinitialize = function () {
if (this.initPromise && this.initPromise.state === 'pending') {
// 初始化正在进行中,直接返回现有promise
return this.initPromise;
}
// 创建新的初始化promise
this.initPromise = new Promise((resolve, reject) => {
try {
this.initialize().then(resolve).catch(reject);
} catch (error) {
reject(error);
}
});
return this.initPromise;
};
// 全局函数:包装异步操作,提供错误处理和重试机制
function wrapAsyncOperation(operation, retryMessage) {
return function () {
const args = arguments;
const context = this;
// 检查customImageManager初始化状态
if (!customImageManager.initialized) {
// 尝试重新初始化
customImageManager.reinitialize().then(() => {
operation.apply(context, args);
}).catch(err => {
console.error('初始化失败:', err);
alert(retryMessage || '操作失败,请稍后重试');
});
} else {
try {
operation.apply(context, args);
} catch (err) {
console.error('操作执行错误:', err);
alert(retryMessage || '操作失败,请稍后重试');
}
}
};
}
LinkGame.prototype = {
init: function (isReset) {
var self = this;
this.stack = [];
this.count = (this.rows - 2) * (this.cols - 2); // 图片的总数
// 计算所需的图片种类数量
// 如果有自定义图片,确保不超过自定义图片的数量
var minRequiredTypes = Math.max(11, this.level + 11);
if (customImageManager && customImageManager.hasImages()) {
// 自定义图片模式下,图片种类数量取自定义图片数量和所需最小数量的较小值
this.iconTypeCount = Math.min(customImageManager.getImages().length, Math.ceil(this.count / 2));
console.log('自定义图片模式,图片种类数量:', this.iconTypeCount);
} else {
// 默认模式
this.iconTypeCount = minRequiredTypes;
}
this.remain = this.count; // 剩余的未有消去的图片
this.pictures = []; // 图片集合
this.linkPictures = [];
this.preClickInfo = null; // 上一次被点中的图片信息
this.leftTime = 100; // 剩余时间
this.points = []; // 图片可以相消时的拐点集合
this.timmer = setInterval(function () {
self.updateCountDown();
}, 1000);
this.createMap();
this.disorder();
!isReset && this.bindDomEvents();
this.updateLevel();
this.domUpdateScore();
},
reset: function () {
this.init(true);
},
nextLevel: function () {
clearInterval(this.timmer);
this.reset();
},
// 模板替换
replaceTpl: function (tpl, data) {
return tpl.replace(/\${(\w+)}/ig, function (match, $1) {
return data[$1];
});
},
// 合并数组,并把相同的元素排除掉
mergeArray: function (target, source) {
source.forEach(function (e) {
if (target.indexOf(e) === -1) {
target.push(e);
}
})
},
// 生成一定范围内的随机数
random: function (min, max) {
return parseInt((Math.random() * max) + min);
},
// 交换对象属性
swapProperties: function (obj1, obj2, properties) {
properties.forEach(function (property) {
var temp = obj1[property];
obj1[property] = obj2[property];
obj2[property] = temp;
});
},
// 克隆对象(浅克隆)
cloneObj: function (source) {
var target = {};
for (var pro in source) {
source.hasOwnProperty(pro) && (target[pro] = source[pro]);
}
return target;
},
// 获取历史记录
getHistoryScore: function () {
return window.localStorage.getItem('highestScore') || 0;
},
// 保存最高分
setHistoryScore: function (score) {
var highestScore = this.getHistoryScore('highestScore');
if (score > highestScore) {
window.localStorage.setItem('highestScore', score);
}
},
updateDomNumbers: function ($container, value, type) {
var numList = [];
var nums = type === 1 ? this.nums : (type === 2 ? this.xnums : this.pnums);
$container.html('');
do {
numList.push(value % 10);
value = parseInt(value / 10);
} while (value > 0);
while (numList.length) {
$container.append(this.replaceTpl('<img src="${src}" />', {
src: nums[numList.pop()]
}));
}
},
updateCountDown: function () {
--this.leftTime;
if (this.leftTime < 0) {
clearInterval(this.timmer);
this.gameOver();
return;
}
this.updateDomNumbers($('.time'), this.leftTime, 1);
},
gameOver: function () {
$('.game-over').removeClass('hidden').find('.history-score').text(this.getHistoryScore() || 0);
this.updateDomNumbers($('.current-score'), this.score, 3);
this.setHistoryScore(this.score);
},
updateLevel: function () {
this.updateDomNumbers($('.level'), this.level + 1, 1);
},
// 创建游戏地图,实现图标成对生成机制
// 每对图标包含:一个为图片内容图标,另一个为图片名称文本图标
createMap: function () {
var count = 0;
// 存储每对图标的关联关系
this.iconPairs = {};
for (var row = 0; row < this.rows; row++) {
this.pictures.push([]);
for (var col = 0; col < this.cols; col++) {
// 边界元素
if (row === 0 || row === this.rows - 1 || col === 0 || col === this.cols - 1) {
this.pictures[row].push({
row: row,
col: col,
isEmpty: true,
isBoundary: true
});
// 内部元素
} else {
// 确定当前使用的图片索引
var picIndex = parseInt(count / 2) % this.iconTypeCount;
var picPath = this.gifts[picIndex];
// 为偶数位置创建图片图标,为奇数位置创建对应的文本图标
if (count % 2 === 0) {
// 图片内容图标
this.pictures[row].push({
row: row,
col: col,
isEmpty: false,
index: count,
pic: picPath,
type: 'image',
pairId: picIndex,
width: this.cellWidth,
height: this.cellHeight,
isBoundary: false
});
// 记录图片图标对应的文本图标信息
this.iconPairs[count] = count + 1;
} else {
// 文本图标 - 使用图片的实际文件名作为文本内容
var baseName = this.giftObjects[picIndex].fileName;
// 移除文件名的后缀部分
if (baseName && baseName.lastIndexOf('.') > -1) {
baseName = baseName.substring(0, baseName.lastIndexOf('.'));
}
// 确保文本内容不为空
if (!baseName || baseName.trim() === '') {
baseName = '图' + picIndex;
}
// 设置实际文件名作为文本内容
console.log('为图标设置文本内容:', baseName);
this.pictures[row].push({
row: row,
col: col,
isEmpty: false,
index: count,
text: baseName,
type: 'text',
pairId: picIndex,
width: this.cellWidth,
height: this.cellHeight,
isBoundary: false
});
// 记录文本图标对应的图片图标信息
this.iconPairs[count] = count - 1;
}
count++;
}
}
}
},
// 打乱顺序
disorder: function () {
var pictures = this.pictures;
var random = this.random.bind(this);
for (var i = 0; i < this.count * 10; i++) {
// 随机选中2张图片,交换所有必要属性
var picture1 = pictures[random(1, this.rows - 2)][random(1, this.cols - 2)];
var picture2 = pictures[random(1, this.rows - 2)][random(1, this.cols - 2)];
// 交换所有必要的属性,包括新添加的type、text、pairId等
this.swapProperties(picture1, picture2, ['pic', 'isEmpty', 'type', 'text', 'pairId']);
}
this.renderMap();
this.updateDisorderTime();
},
updateDisorderTime: function () {
this.updateDomNumbers($('.disorder'), this.leftDisorderTime, 2);
},
renderMap: function () {
this.$box.html(''); // 将视图清空
var html = '';
var pictures = this.pictures;
for (var row = 1; row < this.rows - 1; row++) {
html += '<tr class="game-row">';
for (var col = 1; col < this.cols - 1; col++) {
var picture = this.cloneObj(pictures[row][col]);
var emptyClass = picture.isEmpty ? 'empty' : '';
if (picture.type === 'image') {
// 图片内容图标
var imageTpl = '<td><div class="pic-box ${empty}" data-row="${row}" data-col="${col}" data-index="${index}"><img class="pic" draggable=false src="${pic}" width=${width} height=${height} /></div></td>';
html += this.replaceTpl(imageTpl, {
empty: emptyClass,
row: picture.row,
col: picture.col,
index: picture.index,
pic: picture.pic,
width: picture.width,
height: picture.height
});
} else if (picture.type === 'text') {
// 文本图标 - 优化样式以确保内容清晰可辨
var textTpl = '<td><div class="pic-box ${empty}" data-row="${row}" data-col="${col}" data-index="${index}"><div class="text-pic" style="width: ${width}px; height: ${height}px; display: flex; align-items: center; justify-content: center; color: white; font-size: 12px; font-weight: bold; word-break: break-word; background: rgba(0,0,0,0.7); border-radius: 5px; text-shadow: 1px 1px 2px rgba(0,0,0,0.8); padding: 5px;">${text}</div></div></td>';
html += this.replaceTpl(textTpl, {
empty: emptyClass,
row: picture.row,
col: picture.col,
index: picture.index,
text: picture.text,
width: picture.width,
height: picture.height
});
}
}
html += '</tr>';
}
this.$box.html(html);
},
// 检测连通性
checkMatch: function (curClickInfo) {
var pictures = this.pictures,
preClickInfo = this.preClickInfo ? this.preClickInfo : {},
preRow = +preClickInfo.row,
preCol = +preClickInfo.col,
preIndex = +preClickInfo.index,
curRow = +curClickInfo.row,
curCol = +curClickInfo.col,
curIndex = +curClickInfo.index;
// 如果点击的图片是空白的,则退出
if (pictures[curRow][curCol].isEmpty) {
return;
}
this.preClickInfo = curClickInfo;
this.domAddActive(curIndex);
if (preIndex !== preIndex) { // NaN
return;
}
// 检查是否是同一张图片
if (preIndex === curIndex) {
this.domRemoveActive(preIndex);
return;
}
// 检查是否是配对的图片内容图标和文本图标
var prePicture = pictures[preRow][preCol];
var curPicture = pictures[curRow][curCol];
// 确保两个图标类型不同(一个是image,一个是text)
// 并且它们的pairId相同,即属于同一对
// 只有满足这两个条件才能进行连线消除
if (prePicture.type !== curPicture.type && prePicture.pairId === curPicture.pairId) {
if (this.canCleanup(preCol, preRow, curCol, curRow)) {
this.linkPictures = [];
for (var i = 0; i < this.points.length - 1; i++) {
this.mergeArray(this.linkPictures, this.countPoints(this.points[i], this.points[i + 1]));
}
this.drawLine();
this.updateStatus(preRow, preCol, curRow, curCol, preIndex, curIndex);
} else {
this.domRemoveActive(preIndex);
}
} else {
this.domRemoveActive(preIndex);
}
},
countPoints: function (start, end) {
var points = [];
var pictures = this.pictures;
if (start[0] === end[0]) { // 同列
var x = start[0];
if (start[1] > end[1]) { // 从下到上
for (var i = start[1]; i >= end[1]; i--) {
points.push(pictures[i][x]);
}
} else { // 从上到下
for (var i = start[1]; i <= end[1]; i++) {
points.push(pictures[i][x]);
}
}
} else if (start[1] === end[1]) { // 同行
var y = start[1];
if (start[0] > end[0]) { // 从右到左
for (var i = start[0]; i >= end[0]; i--) {
points.push(pictures[y][i]);
}
} else { // 从左到右
for (var i = start[0]; i <= end[0]; i++) {
points.push(pictures[y][i]);
}
}
}
return points;
},
domAddActive: function (index) {
$('.game-row .pic-box').eq(index).addClass('active');
return this;
},
domRemoveActive: function (index) {
$('.game-row .pic-box').eq(index).removeClass('active');
return this;
},
domAddEmpty: function (index) {
$('.game-row .pic-box').eq(index).addClass('empty').removeClass('active');
return this;
},
// 记分
domUpdateScore: function () {
this.updateDomNumbers($('.scoring'), this.score, 1);
},
// 连线
drawLine: function (callback) {
var $canvas = $('#canvas');
if (!$canvas[0].getContext('2d')) return; // 不支持Canvas
var linkList = this.linkPictures;
var coordinate = [];
for (var i = 0; i < linkList.length; i++) {
var x = linkList[i].col === 0 ? 0 : (linkList[i].col === this.cols - 1 ? $('#game').width() : linkList[i].col * 80 - 40);
var y = linkList[i].row === 0 ? 0 : (linkList[i].row === this.rows - 1 ? $('#game').height() : linkList[i].row * 80 - 40);
coordinate.push([x, y]);
}
var ctx = $canvas[0].getContext('2d');
ctx.beginPath();
ctx.strokeStyle = "#fbff98";
ctx.fillStyle = "#fbff98";
ctx.lineWidth = 4;
ctx.save();
for (var i = 0; i < linkList.length; i++) {
if (i === 0) {
ctx.moveTo(coordinate[i][0], coordinate[i][1]);
}
ctx.lineTo(coordinate[i][0], coordinate[i][1]);
}
ctx.stroke();
ctx.restore();
$canvas.removeClass('hidden');
setTimeout(function () {
ctx.clearRect(0, 0, 800, 800);
$canvas.addClass('hidden');
}, 200);
},
updateStatus: function (preRow, preCol, curRow, curCol, preIndex, curIndex) {
var self = this;
this.remain -= 2;
this.score += 10 * (this.linkPictures.length - 1);
this.preClickInfo = null;
this.domUpdateScore();
setTimeout(function () {
self.pictures[preRow][preCol].isEmpty = true;
self.pictures[curRow][curCol].isEmpty = true;
self.domAddEmpty(preIndex).domAddEmpty(curIndex);
if (self.remain === 0) {
++self.level;
self.nextLevel();
}
}, 200);
},
isRowEmpty: function (x1, y1, x2, y2) {
if (y1 != y2) {
return false;
}
x1 > x2 && (x1 = x1 + x2, x2 = x1 - x2, x1 = x1 - x2); //强制x1比x2小
for (var j = x1 + 1; j < x2; ++j) { //from (x2,y2+1) to (x2,y1-1);
if (!this.pictures[y1][j].isEmpty) {
return false;
}
}
return true;
},
isColEmpty: function (x1, y1, x2, y2) {
if (x1 != x2) {
return false;
}
y1 > y2 && (y1 = y1 + y2, y2 = y1 - y2, y1 = y1 - y2); //强制y1比y2小
for (var i = y1 + 1; i < y2; ++i) { //from (x2+1,y2) to (x1-1,y2);
if (!this.pictures[i][x1].isEmpty) {
return false;
}
}
return true;
},
addPoints: function () {
var args = arguments,
len = args.length,
i = 0;
for (; i < len;) {
this.points.push(args[i++]);
}
},
// 判断两个坐标是否可以相互消除
canCleanup: function (x1, y1, x2, y2) {
this.points = [];
if (x1 === x2) {
if (1 === y1 - y2 || 1 === y2 - y1) { //相邻
this.addPoints([x1, y1], [x2, y2]);
return true;
} else if (this.isColEmpty(x1, y1, x2, y2)) { //直线
this.addPoints([x1, y1], [x2, y2]);
return true;
} else { //两个拐点 (优化)
var i = 1;
while ((x1 + i < this.cols) && this.pictures[y1][x1 + i].isEmpty) {
if (!this.pictures[y2][x2 + i].isEmpty) {
break;
} else {
if (this.isColEmpty(x1 + i, y1, x1 + i, y2)) {
this.addPoints([x1, y1], [x1 + i, y1], [x1 + i, y2], [x2, y2]);
return true;
}
i++;
}
}
i = 1;
while ((x1 - i >= 0) && this.pictures[y1][x1 - i].isEmpty) {
if (!this.pictures[y2][x2 - i].isEmpty) {
break;
} else {
if (this.isColEmpty(x1 - i, y1, x1 - i, y2)) {
this.addPoints([x1, y1], [x1 - i, y1], [x1 - i, y2], [x2, y2]);
return true;
}
i++;
}
}
}
}
if (y1 === y2) { //同行
if (1 === x1 - x2 || 1 === x2 - x1) {
this.addPoints([x1, y1], [x2, y2]);
return true;
} else if (this.isRowEmpty(x1, y1, x2, y2)) {
this.addPoints([x1, y1], [x2, y2]);
return true;
} else {
var i = 1;
while ((y1 + i < this.rows) && this.pictures[y1 + i][x1].isEmpty) {
if (!this.pictures[y2 + i][x2].isEmpty) {
break;
} else {
if (this.isRowEmpty(x1, y1 + i, x2, y1 + i)) {
this.addPoints([x1, y1], [x1, y1 + i], [x2, y1 + i], [x2, y2]);
return true;
}
i++;
}
}
i = 1;
while ((y1 - i >= 0) && this.pictures[y1 - i][x1].isEmpty) {
if (!this.pictures[y2 - i][x2].isEmpty) {
break;
} else {
if (this.isRowEmpty(x1, y1 - i, x2, y1 - i)) {
this.addPoints([x1, y1], [x1, y1 - i], [x2, y1 - i], [x2, y2]);
return true;
}
i++;
}
}
}
}
//一个拐点
if (this.isRowEmpty(x1, y1, x2, y1) && this.pictures[y1][x2].isEmpty) { // (x1,y1) -> (x2,y1)
if (this.isColEmpty(x2, y1, x2, y2)) { // (x1,y2) -> (x2,y2)
this.addPoints([x1, y1], [x2, y1], [x2, y2]);
return true;
}
}
if (this.isColEmpty(x1, y1, x1, y2) && this.pictures[y2][x1].isEmpty) {
if (this.isRowEmpty(x1, y2, x2, y2)) {
this.addPoints([x1, y1], [x1, y2], [x2, y2]);
return true;
}
}
//不在一行的两个拐点
if (x1 != x2 && y1 != y2) {
i = x1;
while (++i < this.cols) {
if (!this.pictures[y1][i].isEmpty) {
break;
} else {
if (this.isColEmpty(i, y1, i, y2) && this.isRowEmpty(i, y2, x2, y2) && this.pictures[y2][i].isEmpty) {
this.addPoints([x1, y1], [i, y1], [i, y2], [x2, y2]);
return true;
}
}
}
i = x1;
while (--i >= 0) {
if (!this.pictures[y1][i].isEmpty) {
break;
} else {
if (this.isColEmpty(i, y1, i, y2) && this.isRowEmpty(i, y2, x2, y2) && this.pictures[y2][i].isEmpty) {
this.addPoints([x1, y1], [i, y1], [i, y2], [x2, y2]);
return true;