-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.js
3612 lines (3595 loc) · 163 KB
/
main.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
"use strict";
/* 常量 */
const BlankPNG = `data:image/webp;base64,UklGRkAAAABXRUJQVlA4WAoAAAAQAAAAAAAAAAAAQUxQSAIAAAAAAFZQOCAYAAAAMAEAnQEqAQABAAFAJiWkAANwAP789AAA`;
const EBody = document.body;
const EElement = document.documentElement;
const RESPATH = `images/interface/`;
const dSurface = $('dSurface');
const PKindUpperLimit = 5;
const PKindTraverseOrder = [5,0,1,2,3,4]; //(用于GetAP)植物遍历顺序
const GrowSoilImg = "images/interface/GrowSoil.webp";
const WaterShadowImg = `images/Zombies/WaterShadow.webp`;
const WaterSplashImg = `images/Zombies/Drop_Water.webp`;
/* 江南自定义事件注册 */
const EVENT_STARTGAME = new Event("jng-event-startgame");
const EVENT_ENDGAME = new Event("jng-event-endgame");
const EVENT_EXITGAME = new Event("jng-event-exitgame");
/* API */
let $User = {
// oSym里的时间跨度,默认是1,值为1-5加速1-5倍
NowStep: 1,
// oSym里的计时间隔,默认是10;值为20,10,5,分别是减速一半,原速,加速一倍
TimeStep: 10,
// 是否自动拾取阳光
AutoSun: Number(localStorage['JNG_TR_AUTOSUN']) || false,
// 用户标识
Tag: localStorage.tag ? localStorage.tag : "local",
// 用户名
Name: localStorage.name ? localStorage.name : "local",
// 是否开启低性能模式
LowPerformanceMode: false,
// 是否启用blob动画
Async_GIFS_Animate: true,
Coins: 0,
// 记录用户获得成就
Achievement: localStorage.JNG_TR_Achievement ? JSON.parse(localStorage.JNG_TR_Achievement) : {},
// 是否启用坚果包扎术
enabledWallNutFirstAid: isNullish(localStorage.JNG_TR_WallNutFirstAid) ? false : true,
// 阳光铲
enabledSunShovel: !isNullish(localStorage.JNG_TR_SunShovel) && localStorage.JNG_TR_EnabledItems && JSON.parse(localStorage.JNG_TR_EnabledItems).SunShovel === 1 ? true : false,
// 强化初始阳光
enabledMoreStartingSun: !isNullish(localStorage.JNG_TR_MoreStartingSun) && localStorage.JNG_TR_EnabledItems && JSON.parse(localStorage.JNG_TR_EnabledItems).MoreStartingSun === 1 ? true : false,
// 池塘清洁车
enabledPoolCleaner: isNullish(localStorage.JNG_TR_PoolCleaner) ? false : true,
// 战术丢车
enabledMowerLaunch: isNullish(localStorage.JNG_TR_MowerLaunch) ? false : true,
// 宝马雕车
enabledValuableMowers: isNullish(localStorage.JNG_TR_ValuableMowers) ? false : true,
// 是否画血
DrawBlood: localStorage.JNG_TR_DrawBlood ? JSON.parse(localStorage.JNG_TR_DrawBlood) : false,
//显示键盘快捷键
ShowShortcuts: localStorage.JNG_TR_ShowShortcuts ? JSON.parse(localStorage.JNG_TR_ShowShortcuts) : false,
// 是否时间同步
TaskForceTimeSync: localStorage.JNG_TR_TaskForceTimeSync ? JSON.parse(localStorage.JNG_TR_TaskForceTimeSync) : true,
// 是否开启动态难度
OpenDynamicDifficulty: navigator.language?.includes("zh") ?? false,
// 是否开启剧情
IS_PLOT_OPEN: localStorage.JNG_TR_IS_PLOT_OPEN ? JSON.parse(localStorage.JNG_TR_IS_PLOT_OPEN) : (!IsDevEnvi),
// 游戏音效音量百分比,默认100%
AudioEffectVolumePercent: localStorage.JNG_TR_AudioPercent ? Number.parseFloat(localStorage.JNG_TR_AudioPercent) : 1,
// 游戏bgm音量百分比,默认100%
MusicVolumePercent: localStorage.JNG_TR_MusicPercent ? Number.parseFloat(localStorage.JNG_TR_MusicPercent) : 1,
_tmpARCARD: {},
};
class __oSymTaskPool__ {
constructor() {
this.taskPool = [];
}
get(T, f, taskIndex, ar) {
let taskObject = this.taskPool.pop() ?? {};
taskObject.T = T;
taskObject.f = f;
taskObject.taskIndex = taskIndex;
taskObject.ar = ar;
return taskObject;
}
recycle(taskObject) {
delete taskObject.f;
delete taskObject.ar;
this.taskPool.push(taskObject);
return taskObject;
}
};
const oSym = {
ZMonitorRefresh: 100,
BuMonitorRefresh: 10,
Init(callback, arg = []) { //在每次关卡文件load的时候初始化
const self = this;
self.Rewrite(self);
self.Now = 0; //系统时间
self.Timer = null; //系统时间定时器
self.TQ = [];
self.TQSet = new Set();
self.NowStep = 1; //oSym里的时间跨度,默认是1,值为1-5加速1-5倍
self.TimeStep = 10; //oSym里的真实定时器计时间隔,默认是10,值为20,10,5,分别是减速一半,原速,加速一倍
self.changed = Infinity; //是否改写了数组(保存的是最短的delayT)
self.taskNum = 0; //数组任务个数
self.taskTotal = 0; //目前是创建的第几个事件,目的是在排序的时候可以判断事件先后
self.NowSpeed = 1;
self.__IncreasedTime__ = null; //你在addTask里设置addTask需要拿现在的时间和理论上调用addTask的时间做差,减去你调用的偏差的时间。
self.__pool__ = self.__pool ?? new __oSymTaskPool__();
if ($User.NowSpeed) {
CSpeed($User.NowSpeed, false);
}
self.addTask(0, callback, arg);
self.Start(); //启动系统进程
},
CalcTimePassed(d) { //提供一个通用的方法计算应该经过了多少时间
return Math.min(d, 100); //最多只能经过100ms,防止一下子过大的突变
},
//用重写的方式,避免每次执行的时候都要判断
Rewrite(self) {
if (!$User.TaskForceTimeSync) {
self.Start = () => {
if (self.Timer === null) {
let task, now, step = self.NowStep,
lastTime = Date.now(),
curTime, TQ = self.TQ;
const timeStep = self.TimeStep;
const stack = self.TQSet;
const pool = self.__pool__;
const process = () => {
now = self.Now += step;
if ((self.changed -= step) < 1) {
self.Resort(self);
}
for (let i = self.taskNum - 1; i >= -1; --i) {
task = TQ[i];
if (i === -1 || now < task.T) {
self.taskNum = i + 1;
break;
}
if (task.T === -Infinity) {
if(IsDevEnvi===true){
console.warn("[PvZTR] -Infinity Task", Object.assign({}, task));
}
continue;
}
try {
task.f(...task.ar);
task.T = -Infinity;
} catch (err) {
console.error(err);
}
}
stack.forEach(task => {
if (now >= task.T) {
try {
task.f(...task.ar);
} catch (err) {
console.error(err);
}
stack.delete(pool.recycle(task));
}
});
};
self.Timer = setInterval(process, self.TimeStep);
}
};
self.addTask = (delayT = 0, callback, arg = [], useSet = false) => {
//因为游戏中的1相当于浏览器真实计时的10ms,所以传入的delayT(毫秒)要除以10
const self = this;
/*const task = {
T: self.Now + delayT, //执行时间(自定义的oSym时间)
f: callback, //执行函数
taskIndex: self.taskTotal++,
ar: arg, //参数的数组形式,用于执行函数传递参数
};*/
const task = self.__pool__.get(self.Now + delayT, callback, self.taskTotal++, arg);
if (delayT < 15 || useSet) { //如果反复写入,则使用集合
self.TQSet.add(task);
} else { //如果为长时间冷却的,则使用数组
self.TQ.push(task);
self.changed = Math.min(self.changed, delayT);
}
return task;
};
}
else {
self.Start = () => {
if (self.Timer === null) {
let task, now, step,
lastTime = Date.now(),
curTime, TQ = self.TQ;
const stack = self.TQSet;
const pool = self.__pool__;
const process = () => {
//时间强同步
curTime = Date.now();
step = Math.max(self.CalcTimePassed(curTime - lastTime) * self.NowSpeed / 10, 0);
lastTime = curTime;
//时间强同步 End
now = self.Now += step;
if ((self.changed -= step) < 1) {
self.Resort(self);
}
for (let i = self.taskNum - 1; i >= -1; --i) {
task = TQ[i];
if (i === -1 || now < task.T) {
self.taskNum = i + 1;
break;
}
if (task.T === -Infinity) {
if(IsDevEnvi===true){
console.warn("[PvZTR] -Infinity Task", Object.assign({}, task));
}
continue;
}
try {
//时间强同步
self.__IncreasedTime__ = task.T - self.Now;
//时间强同步 End
task.f(...task.ar);
task.T = -Infinity;
} catch (err) {
console.error(err);
}
}
stack.forEach(task => {
if (now >= task.T) {
try {
//时间强同步
self.__IncreasedTime__ = task.T - self.Now;
//时间强同步 End
task.f(...task.ar);
} catch (err) {
console.error(err);
}
stack.delete(pool.recycle(task));
}
});
//时间强同步
self.__IncreasedTime__ = null;
//时间强同步 End
};
let loopid = self.Timer = Math.random();
requestAnimationFrame(function loop() {
if (self.Timer !== loopid) {
return;
}
process();
requestAnimationFrame(loop);
});
}
};
self.addTask = (delayT = 0, callback, arg = [], useSet = false) => {
//因为游戏中的1相当于浏览器真实计时的10ms,所以传入的delayT(毫秒)要除以10
const self = this;
delayT += self.__IncreasedTime__ ?? 0;
const task = self.__pool__.get(self.Now + delayT, callback, self.taskTotal++, arg);
if (delayT < 15 || useSet) { //如果反复写入,则使用集合
self.TQSet.add(task);
} else { //如果为长时间冷却的,则使用数组
self.TQ.push(task);
self.changed = Math.min(self.changed, delayT);
}
return task;
};
}
},
Resort(self) {
const TQ = self.TQ;
const pool = self.__pool__;
self.changed = Infinity;
TQ.sort((a, b) => {
return b.T - a.T || b.taskIndex - a.taskIndex; //按时间从大到小排,如果相等则按task的先后排序
});
self.taskNum = TQ.length;
while (self.taskNum--) {
if (TQ[self.taskNum].T !== -Infinity) {
break;
}
pool.recycle(TQ.pop());
}
self.taskNum++;
},
removeTask(task) {
if (!(this.TQSet.delete(task))) {
task.T = -Infinity;
}
},
Stop() { //中止系统进程
clearInterval(oSym.Timer);
oSym.Timer = null;
},
Clear() {
this.TQ.length = 0;
this.TQSet.clear();
this.taskNum = 0;
this.taskTotal = 0;
},
Sleep(keepTime) {
return new Promise(resolve => oSym.addTask(keepTime, resolve));
},
};
const LevelConfig = { //关卡默认配置
config: {
'Tutorial': {
backgroundMask: 'BgMask-Tutorial',
SummonZombieArea:[undefined,undefined,150],
LoadAccess(callback) {
oAudioManager.playAudio('Bgm_Tutorial_Noise', 1);
oSym.addTask(90, callback);
},
},
'Forest': {
backgroundImage: 'images/interface/Forest.webp',
backgroundMask: 'BgMask-Forest',
AllowUserCard:true,
DynamicDifficulty:true,
CoinRatio:1,
SummonZombieArea:[undefined,160,100,370],
},
'Forestjx': {
backgroundImage: 'images/interface/ForestJx.webp',
backgroundMask: 'BgMask-Forest',
AllowUserCard:true,
CoinRatio:1.5,
SummonZombieArea:[undefined,160,100,370],
LoadAccess(callback) {
oAudioManager.playAudio('Bgm_Marsh_Noise', 1,0.5);
oSym.addTask(90, callback);
},
},
'Marsh': {
backgroundImage: 'images/interface/Marsh.webp',
backgroundMask: 'BgMask-Marsh',
LoadMusic: "Bgm_Marsh_Ready",
StartGameMusic: "Bgm_Marsh_Fight",
DKind: 0,
DynamicDifficulty:true,
AllowUserCard:true,
CoinRatio:1,
SpawnLevelLimit:0.6,
LoadAccess(callback) {
oAudioManager.playAudio('Bgm_Marsh_Noise', 1,0.5);
oSym.addTask(90, callback);
},
},
'Marshjx': {
backgroundImage: 'images/interface/MarshJx.webp',
backgroundMask: 'BgMask-Marsh',
AllowUserCard:true,
CoinRatio:2,
LoadAccess(callback) {
oAudioManager.playAudio('Bgm_Marsh_Noise_JX', 1);
oSym.addTask(90, callback);
},
},
'Polar': {
backgroundMask: 'BgMask-Polar',
get DKind(){
return (oS.Lvl.replace(/[^0-9]/ig,"")<=15)?1:0;
},
get SunNum() {
return oS.DKind ? 150 : 300;
},
get LoadMusic() {
return `Bgm_Polar_Ready_${oS.DKind ? 1 : 2}`;
},
get StartGameMusic() {
return `Bgm_Polar_Fight_${oS.DKind ? 1 : 2 + Math.round(Math.random()*2)}`;
},
get backgroundImage() {
return `images/interface/Polar${oS.DKind ? '' : '2'}.webp`;
},
get LoadAccess() {
return a=>{
oAudioManager.playAudio('Bgm_Polar_Noise', 1);
!oS.DKind && (NewEle('PolarFire2', "span", null, {className: 'PolarFire'}, $('tGround')), NewEle('PolarFire', "span", null, {className: 'PolarFire'}, $('tGround')));
oSym.addTask(90, a);
}
},
DynamicDifficulty:true,
AllowUserCard:true,
CoinRatio:1,
SummonZombieArea:[70,190,240,370],
},
'Polarjx': {
backgroundMask: 'BgMask-Polar',
get DKind(){
return (oS.Lvl.replace(/[^0-9]/ig,"")<=15)?0:1;
},
get SunNum() {
return oS.DKind ? 150 : 300;
},
get backgroundImage() {
return `images/interface/Polar${oS.DKind ? '' : '2'}.webp`;
},
SummonZombieArea:[70,190,240,370],
ZombieRandomSpeed:0,
AllowUserCard:true,
CoinRatio:2.5,
},
'Industry': {
PicArr: (function() {
let arr = ["images/interface/Industry.webp"];
for (let i=0; i<4; i++) {
arr.push("images/interface/haze" + i + ".png");
arr.push("images/interface/fog" + i + ".png");
}
return arr;
})(),
backgroundImage: `images/interface/Industry.webp`,
LoadMusic: `Bgm_Industry_Ready`,
AllowUserCard:true,
backgroundMask: "BgMask-Industry",
get StartGameMusic(){
return (oS.Lvl.replace(/[^0-9]/ig,"")<21)?`Bgm_Industry_Fight`:`Bgm_Industry_Fight_2`
},
LoadAccess(callback) {
oAudioManager.playAudio('Bgm_Industry_Noise',1);
oSym.addTask(90, callback);
},
get DynamicDifficulty(){
return (oS.Lvl.replace(/[^0-9]/ig,"")<19)?true:false;
},
CoinRatio:1.5,
SummonZombieArea:[undefined,undefined,150],
},
'Industryjx': {
PicArr: [`images/interface/Industryjx.webp`],
backgroundImage: `images/interface/Industryjx.webp`,
LoadMusic: `Bgm_Industry_Ready_JX`,
backgroundMask: "BgMask-IndustryJX",
AllowUserCard:true,
DKind:0,
get StartGameMusic(){
return `Bgm_Industry_Fight_JX`;
},
LoadAccess(callback) {
oAudioManager.playAudio('Bgm_Industry_Noise_JX',1);
oSym.addTask(90, callback);
},
CoinRatio:2.5,
SummonZombieArea:[undefined,undefined,150],
},
'Mirage': {
PicArr: [`images/interface/Mirage.webp`, `images/interface/Mirage_Night.webp`, 'images/Props/WaterPath/edgeMask.webp', 'images/Props/WaterPath/fullWater.webp', 'images/interface/Tombstone.webp'],
LoadMusic: `Bgm_Mirage_Ready`,
AllowUserCard:true,
backgroundMask: "BgMask-Mirage",
DKind:1,
get StartGameMusic(){
return `Bgm_Mirage_Fight`;
},
get backgroundImage() {
return `images/interface/Mirage${oS.DKind ? '' : '_Night'}.webp`;
},
LoadAccess(callback) {
oAudioManager.playAudio('Bgm_Mirage_Noise',1);
oSym.addTask(90, callback);
},
CoinRatio:2,
SpawnLevelLimit:0.7,
SummonZombieArea:[undefined,undefined,150],
},
'SeasonA': {
backgroundImage: 'images/interface/Fuben_Autumn.webp',
backgroundMask: 'BgMask-Forest',
LF: [0, 1, 1, 3, 1, 1],
CoinRatio:1.2,
LoadMusic: "Fuben_Autumn_Ready",
AllowUserCard:true,
StartGameMusic: "Fuben_Autumn_Fight",
SummonZombieArea:[undefined,160,100,370],
},
'SeasonW': {
backgroundImage: 'images/interface/Fuben_Winter.webp',
backgroundMask: 'BgMask-Polar',
LoadMusic: "Fuben_Winter_Ready",
StartGameMusic: "Fuben_Winter_Fight",
SunNum: 200,
CoinRatio:1.5,
DKind: 0,
AllowUserCard:true,
SummonZombieArea:[70,180,240,370],
},
},
query() {
let nLvl = (''+oS['Lvl']).replace(/[^a-zA-Z]+/g, '');
if(this.config[nLvl]) {
return this.config[nLvl];
}
return {};
},
},
oS = {
//静态数据,不会因为关卡以及游戏进程而改变,无需Init只在页面最初定义一次
W: 1067,
GroundW:900,
EDAllScrollLeft:0,
GroundPictureWidth:1400,
FightingSceneLeft:115,
H: 600,
C: 9,
LawnMowerX: 70,
Lvl: 0,
Silence: Number.parseFloat(localStorage.JNG_TR_AudioPercent) === 0,
DefaultStartGame() { //默认开始游戏初始化代码
if (oS.StartGameMusic) oAudioManager.playMusic(oS.StartGameMusic);
SetVisible($("tdShovel"), $("dFlagMeter"), $("dTop"));
oS.ControlFlagmeter && oFlagContent.init({ fullValue: oP.FlagNum-1, curValue: 0 }); //显示进度条
oS.InitLawnMover(); //剪草机
PrepareGrowPlants(_ => {
oP.Monitor(); //开启全局僵尸调度
BeginCool(); //冷却
oS.DKind && !oS.IZombie && AutoProduceSun(50); //掉落阳光
oSym.addTask(1500, _=>{
oP.AddZombiesFlag(); //启动僵尸出场
oS.ControlFlagmeter && oFlagContent.show();
});
})
},
DefaultFlagToEnd(gotoLevelString=null) {
ShowWinItem(NewImg("imgSF", "images/interface/Clearance_reward.png", "left:535px;top:200px;width:116px;height:119px;", EDAll, {
onclick: e=>oS.Lvl.indexOf('jx') < 0 ?
GetNewProp(e.target, 'Clearance_reward', '星星', '星星是闯关成功的象征。加油搜集更多星星吧!', gotoLevelString??NextLevel(), "30%", "387px") :
GetWin(e.target, gotoLevelString??Exitlevel(oS.Lvl, 1))
}));
},
GlobalVariables: {}, //储存重写前的暴露在window上的函数
warmStart: 0, //游戏是否已冷启动过了
Init(rewrite_oS_Json, setting_oP_Json, rewrite_GlobalVariables_Json) {
const self = this;
/* 重写全局变量、函数开始 */
for (let key in rewrite_GlobalVariables_Json) {
self.GlobalVariables[key] = window[key]; //把重写前的一些公开函数储存进GlobalVariables
window[key] = rewrite_GlobalVariables_Json[key]; //重写函数
}
//储存选定卡片的普通数组。
//格式{DID:卡牌dom的id,CDReady:是否冷却,SunReady:阳光充足,PName:植物之构造函数} 。
//该数组在LetsGO函数执行时被写入数据。在选卡阶段请勿尝试调用本数组!
window.ArCard = [];
//预选植物json数据,格式{${植物EName: {Select: 该植物卡牌是否被选择, PName: 对应植物的构造函数}}, SelNum}
window.ArPCard = {SelNum: 0, $: {}};
window.ArSun = {}; //场地上阳光数据
window.$Z = {}; //场地上僵尸数据
window.$P = {}; //场地上植物数据
window.EDAll = $("dAll");
window.EDAlloffsetLeft = EDAll.offsetLeft;
window.FightingScene = $('dFightingScene');
window.Ground = $('tGround');
window.EDPZ = $("dPZ");
window.EDPZ_Spare1 = $("dPZ_Spare1");
window.EDPZ_Spare2 = $("dPZ_Spare2");
window.EDNewAll = EDAll.cloneNode(true); //用于调用 SelectModal时重置大舞台
window.ESSunNum = $("sSunNum");
/*
检测是否处于关卡进行状态
当deep=0时,为非严格检测,只要进入关卡就返回true
当deep=1时,为严格检测,必须真正开始游戏后才返回true
*/
window.IsGaming = deep => !!((deep ? oGd?.$['4_-2_1'] : oS.PName.length > 0) && oSym.Timer);
/* 重写全局变量、函数结束 */
/* 重写oS对象上挂载的变量开始 */
const DefaultProperties = {
/* 关卡常用配置如下 */
PicArr: [],
DynamicPicArr: [],
AudioArr: [],
MusicArr: [],
VideoArr: [],
Coord: 1,
DeltaY: 100, //height of each tile, 100 for 5 lanes, 88 for 6 lanes
LF: [0, 1, 1, 1, 1, 1],
ZF: null,
PName: [],
LoadingPName: [],
ZName: [],
SunNum:150,
backgroundImage: null, //重置场景参数,以防延续上一关的场景
backgroundMask: null,
isScroll: true,
InitLawnMover: null,
InitWaterPath: null,
SummonZombieArea: [], //生成僵尸预览的范围
HaveFog: null,
FixedProps: {},//固定携带的道具
ProduceSun: true, //是否允许生产类植物生产阳光
AllowUserCard: false, //是否允许用户携带自己获得的卡片
SortCardType:1,//排序卡的方式,1是全部排序,0是只排序用户获得卡片,-1是不排序
StaticCard: 1, //控制卡的个数是否是固定的。0表示源源不断的随机给卡,每个卡用一次
ScoreConditionNotMet: false, //in certain WinWithScore levels, score is used as an objective instead of a win condition, and this will be set to true at the start of the level. When you get enough score, this is set to false. If toWin is triggered but ScoreConditionNotMet is true, trigger toOver(2) instead
DynamicDifficulty: false,//是否开启动态难度
ZombieRandomSpeed: 0.15,//僵尸速度是否随机(表示僵尸的最大正负速度)
ControlFlagmeter: true, //是否授权底层自动控制关卡进度条
CanSelectCard: true, //是否允许玩家自由选卡,默认值为允许
DKind: 1, //控制白天或黑夜:1表示白天,0表示黑夜 (Note: oS.DKind is mostly to control natural sun drop. Some levels without a nighttime background still have oS.DKind = 0 (Last Stand). Use GetTrueDKind() to check day/night based on background)
BowlingLimitC: Infinity,
BonusWarnings: [], //warnings to manually add to the warning system in case the automatic system didn't recognize all the warnings
EDAllScrollLeft:0,
NoFinalWave: false, //if true then don't show the FINAL WAVE warning when it's the final wave
UpsideDown: false,
DisableUpgrades: false, //disable upgrades such as Sun Shovel, Sun Headstart, etc.
PlantOrder: 1, //record the planting order for zombies that use this targeting mechanism, like Necromancer Zombie
coolSpeed: 0.5, //multiplier for plant cards' cooldown speed (e.g. oStopwatch), 0.5 is default
LoadAccess: null,
/* 供函数内部调用的配置如下 */
PicNum: 0,
AccessNum: 0,
MCID: null, //玩家鼠标所指植物卡牌的ID
Chose: 0, //鼠标状态:0——无特殊状态,1——种植植物,-1——拖动铲子
isStartGame: 0, //关卡是否在进行,0未开始游戏,1开始游戏,2关卡结束
CoinRatio: 0,
MaxManualLawnCleaner: 1, // 玩家允许手动触发的小推车数量,当小推车手动触发时,该项会递减
ChoseCard: "", //选择的卡片ID
TempChoseCard: -1, //navigate through plant card list with E, R shortcut key (for services.js)
TempChoseProp: -1, //navigate through prop list with C shortcut key (for services.js)
RestartType: null,
//oS.RestartType: "Survival" if it's a survival level but the checkpoint is not yet reached (when retrying the level the player will start over from the first challenge of the level). "SurvivalCheckpoint" if it's a survival level but the checkpoint is reached (when retrying the player will start from the last checkpoint). All checkpoint progress will be lost if the player quits a Survival level. This property only affects the quit/restart prompt in services.js, you still have to manually change the oS.Lvl yourself. (example: Polar29jx and Industry24jx survival level series)
MPID: "", //鼠标所在植物的ID
CardsType: {},
SpawnLevelLimit:0,//生成下一波所需要的僵尸等级比例
autoWaterFlowDirection: true, //是否自动生成水道路径
changeDKindConfig: {},
TombConfig: null,
__BalancedPlant__:false,//测试功能,平衡植物,目前已经替换完成,这个选项保留在这,如还有需要进行植物大改计划,开启即可
// 是否开启僵尸图层自动调整功能,该功能适用于围歼战或水道关卡
observeZombieLayer: false,
// 每次进入关卡都会有一个独一无二的token,可以利用其判断关卡是否退出或者重新开始
LvlToken: '' + Math.random(),
};
//记录挂载在oS上的变量,以便调用SelectModal时将其清除
self.SelfVariables = new Set(Object.keys(rewrite_oS_Json).concat(Object.keys(DefaultProperties)));
self.SunNum=null;
Object.assign(self, rewrite_oS_Json);
//这里需要分两步进行,两次使用不一样的方法
Object.assignWithoutOverwrite(self, LevelConfig.query(),DefaultProperties);
if(false&&self.__BalancedPlant__){//到时候手动设置为true来更改植物
__TEST_REWRITE_BALANCED_PLANTS__();
for(let i =0;i< oS.PName.length;i++) {
oS.PName[i] = window[oS.PName[i].prototype.EName] ?? oS.PName[i];
}
}
//oS.ZF如无配置的话默认与oS.LF一致
! self.ZF && (self.ZF = self.LF);
//播放LoadMusic,并加载其他音频
self.LoadMusic && self.warmStart && oAudioManager.playMusic(self.LoadMusic);
self.MusicArr = (oS.StartGameMusic ? [oS.StartGameMusic] : []).concat(self.MusicArr);
//处理普通关卡的选卡
if (self.PName.length > 0 && self.StaticCard && self.CanSelectCard) {
//选卡排序的准备
let ori_value_json = {};
for(let i =0;i<self.PName.length;i++){
ori_value_json[self.PName[i].prototype.EName]=1e7+i;//一个非常大的整数,保证未在表中有的植物会被排在最后
}
let value_json = {};
if (self.AllowUserCard) {
let userGetStr = JSON.parse(localStorage.JNG_TR_GotPlants ?? "[]"),
userGet = userGetStr.map(ename => window[ename]);
self.PName = self.PName.concat(userGet).unique();
if(self.SortCardType===0){
let valueKeyArray = AllPlantsENameArr.getValueIndexedJson();
let valueKeyUserGet = userGetStr.getValueIndexedJson();
for(let i =0;i<self.PName.length;i++){
let name = self.PName[i].prototype.EName;
if(valueKeyUserGet[name]){
value_json[name]=valueKeyArray[name]??1e7+i;
}else{
value_json[name]=valueKeyArray[name]??i;
}
}
}
}
if(self.SortCardType===1){
for(let i =0;i<AllPlantsENameArr.length;i++){
value_json[AllPlantsENameArr[i]]=i;
}
}
if(self.SortCardType>=0){
self.PName.sort((a,b)=>{
return (value_json[a.prototype.EName]??ori_value_json[a.prototype.EName])-(value_json[b.prototype.EName]??ori_value_json[b.prototype.EName]);
});
}
//If the number of cards in PName exceeds the number of card slots allowed, allow free selection
//If oS.Slots is not manually stated in the level file, in non-Mirror Adventure levels, the default number of card slots is 7 and can be purchased up to 10, and in other locations there will be 10 card slots
let chklvl = /Forest|Marsh|Polar|Industry|Mirage/.test(oS.Lvl) && !/jx|Bonus_level/.test(oS.Lvl);
self.CanSelectCard = self.PName.length > (oS.Slots || (chklvl ? JSON.parse(localStorage.JNG_TR_Slots || 7) : 10));
}
//check for plants that can only be used for a limited number of times
self.PName.forEach((targetPlant) => {
if (targetPlant.prototype.SpawnLimit) {
targetPlant.spawntimes = 0;
targetPlant.prototype.SpawnLimitReached = false;
}
});
/* 重写oS对象上挂载的变量结束 */
/* other开始 */
oAudioManager.Init();
if(IsGaming(false)){//如果是关卡,则清理不常用的audios
oAudioManager.checkClearUnusedAudio();
}
oP.FlagToMonitor = setting_oP_Json?.FlagToMonitor || new Object();
oP.FlagToEnd = setting_oP_Json?.FlagToEnd || self.DefaultFlagToEnd;
// 分离oS.PName与oS.LoadingPName,便于选卡中不出现的植物的加载
oS.LoadingPName.push(...oS.PName);
oCoord[self.Coord](); //初始化战斗场地
oP.Init(setting_oP_Json);
oT.Init(self.R); //初始化植物触发器系统
oZ.Init(self.R);
oGd.Init();
oBu.Init(); //载入植物子弹系统
oCoinContent.Init(); //初始化货币系统
oTombstone.Init();
self.LoadProgress(); //启动加载
oZombieLayerManager.init();
/* other结束 */
},
LoadProgress() {
oS.LoadingStage = "LoadingRes";
let PicArr = oS.PicArr;
let DynamicPicArr = oS.DynamicPicArr;
let AudioArr = oS.AudioArr.concat(CZombies.prototype.AudioArr);
/* 加载植物资源 */
for (let plant of oS.LoadingPName) {
let proto = plant.prototype;
proto.PicArr.forEach(pic => {
oDynamicPic.checkOriginalURL(pic) ? DynamicPicArr.push(pic) : PicArr.push(oURL.removeParam(pic, "useDynamicPic"));
});
AudioArr = AudioArr.concat(proto.AudioArr);
}
/* 加载僵尸资源 */
const AppearX = GetX(11);
const LF = oGd.$ZF;
const MaxR = oS.R + 1;
const Zombies = Array.from(oS.ZName);
for (let zombie of Zombies) {
let proto = zombie.prototype;
proto.PicArr.forEach(pic => {
oDynamicPic.checkOriginalURL(pic) ? DynamicPicArr.push(pic) : PicArr.push(oURL.removeParam(pic, "useDynamicPic"));
});
proto.Init(AppearX, proto, LF, MaxR);
// 如果当前僵尸有绑定SubsidiaryZombies,则一并加入循环处理
if (!isNullish(proto.SubsidiaryZombies)) Zombies.push(...proto.SubsidiaryZombies);
}
/* 需要列入加载监控的promise如下: */
oS.PicArr = PicArr.unique().filter(pic => pic && !/^data:image\/\w+;base64/.test(pic));
oS.DynamicPicArr = DynamicPicArr.unique();
oS.MustLoadNum = oS.PicArr.length + oS.DynamicPicArr.length + oS.MusicArr.length + oS.VideoArr.length;
oS.ResolveLoadNum = 0;
oS.RejectLoadNum = 0;
//向api提交加载普通图片请求
const ImgProm = oLoadRes.loadImage({
resourceArr: oS.PicArr,
singleResolveCB: _ => (oS.ResolveLoadNum++),
singleRejectCB: _ => (oS.RejectLoadNum++),
});
//向api提交加载动态url图片请求
const DynamicImgProm = oDynamicPic.Init({
singleResolveCB: _ => (oS.ResolveLoadNum++),
singleRejectCB: _ => (oS.RejectLoadNum++),
});
//向api提交加载bgm请求
const MusicProm = oLoadRes.loadAudio({
resourceArr: oS.MusicArr,
type: "music",
singleResolveCB: _ => (oS.ResolveLoadNum++),
singleRejectCB: _ => (oS.RejectLoadNum++),
});
//向api提交加载视频请求
const VideoProm = oLoadRes.loadVideo({ resourceArr: oS.VideoArr,timeout:500000 });
Promise.allSettled([ImgProm, DynamicImgProm, MusicProm, VideoProm]).then(_ => oS.LoadReady(oS));
/* 不需要列入加载监控的promise如下: */
//向api提交加载音效请求
oLoadRes.loadAudio({ resourceArr: AudioArr });
},
LoadReady(_this) {
if (oS.LoadingStage !== "LoadingRes") return;
SetNone($("loading"));
oS.LoadingStage = "Finished";
//根据游戏调速设置系统对象的计时
oSym.NowStep = $User.NowStep;
oSym.TimeStep = $User.TimeStep;
//恢复进度条状态
$("sFlagMeterTitleF").innerHTML = _this.LevelName;
SetHidden($("dFlagMeterContent"), $('dFlagMeter'));
//设置背景
SetVisible($("tGround"));
! isNullish(_this.backgroundImage) && ($("tGround_Image").style.background = "url(" + _this.backgroundImage + ") no-repeat");
_this.backgroundMask && FightingScene.classList.add(_this.backgroundMask); //设置背景蒙版
oS?.changeDKindConfig?.background_sky &&
($("tGround_Sky").style.background = `url:(${oS.changeDKindConfig.background_sky})`);
DisplayZombie(..._this.SummonZombieArea);
const callback = function(StartTime) {
NewEle("imgGrowSoil", 'img', "visibility:hidden;z-index:50", null, FightingScene);
NewEle("dTitle", "div", 0, 0, EDAll);
if ($User.enabledMoreStartingSun && $('dSunNum').style.visibility != 'hidden' && !oS.DisableUpgrades) oS.SunNum+=100;
innerText(ESSunNum, _this.SunNum);
oSelectCardGUI.Init(); //初始化选择卡片界面中
if(oS.isScroll){
oSym.addTask(!StartTime ? 90 : StartTime, oS.ScrollScreen);
}else{
oS.NoScroll();
}
};
//如有需要可在关卡内定义LoadAccess,把回调作为参数上传
//若是正常关卡,直接执行回调
_this.LoadAccess ? _this.LoadAccess(callback) : callback();
},
NoScroll(){
SetVisible($("dMenu"));
const CardList =$("dCardList");
EDAll.scrollLeft =oS.EDAllScrollLeft;
CardList.style.left = `${oS.EDAllScrollLeft}px`;
oSelectCardGUI.selectSeveralCards(oS.PName);
oSym.addTask(90*oSym.NowSpeed, LetsGO);
},
ScrollScreen(time = 0, targetLeft = (oS.GroundPictureWidth-oS.W)) { //向右滚动,显示僵尸出场和选择卡片
let totalTime = 130;
const CardList =$("dCardList");
if (time < totalTime) {
EDAll.scrollLeft = Math.round(Math.Lerp(0, targetLeft, (Math.sin(time / totalTime * Math.PI - Math.PI / 2) + 1) / 2));
let nowTime = new Date();
requestAnimationFrame(() => {
oS.ScrollScreen(time + (new Date() - nowTime) / 10 * oSym.NowSpeed, targetLeft);
CardList.style.left = `${EDAll.scrollLeft}px`;
});
} else {
EDAll.scrollLeft = targetLeft;
CardList.style.left = `${targetLeft}px`;
SetVisible($("dMenu"));
if (oS.CanSelectCard) {
//let mumDOM = NewEle("mum", "div", "position: absolute; width: 390px; height: 390px; left: 710px; top: 80px; background-image: url(images/interface/mum.webp);", {}, EDAll);
{
//ClearChild(mumDOM);
oSelectCardGUI.show(_ => {
let tmpArCard = $User._tmpARCARD[oS.Lvl];
if (tmpArCard) {
let trueArCard = [];//上一次选过的卡,如果是不能选或者不推荐选的,那就不自动选
for (let plant of tmpArCard){
![1,3].includes(oS.CardsType[plant.prototype.EName]) && trueArCard.push(plant);
}
oSelectCardGUI.selectSeveralCards(trueArCard);
}
});
if (!oPropSelectGUI.rerender) oPropSelectGUI.Init();
oPropSelectGUI.show();
oPropSelectGUI.rerender = 0;
};
} else {
oSelectCardGUI.selectSeveralCards(oS.PName);
oSym.addTask(90*oSym.NowSpeed, oS.ScrollBack, [LetsGO]);
}
}
},
ScrollBack(callback) { //界面往左滚动
const CardList =$("dCardList");
const viewDOM = $("viewDOM");
let oriScrollLeft = EDAll.scrollLeft;
// ↓130是上面的totalTime
let totalTime = Math.round(Math.abs(oS.EDAllScrollLeft-oriScrollLeft)/500*130);//要乘以理论上的比例
let time = 0;
let dt = $User.LowPerformanceMode?4:2;
if (oS.CanSelectCard && viewDOM) {
viewDOM.style.left = `${-EDAll.scrollLeft}px`;
viewDOM.style.visibility = `hidden`;
}
(function fun() {
if(time<totalTime&&oriScrollLeft!=oS.EDAllScrollLeft) {
let scrollLeft = Math.floor(Math.Lerp(oriScrollLeft,oS.EDAllScrollLeft,(Math.sin(time/totalTime*Math.PI-Math.PI/2)+1)/2));
EDAll.scrollLeft = scrollLeft;
CardList.style.left = `${scrollLeft}px`;
oSym.Timer?loop():oSym.addTask(0,loop);
function loop(){
let nowTime = new Date();
requestAnimationFrame(()=>{
time+=(new Date()-nowTime)/10*oSym.NowSpeed;
fun(callback);
});
}
} else {
EDAll.scrollLeft = oS.EDAllScrollLeft;
CardList.style.left = `${oS.EDAllScrollLeft}px`;
oSym.addTask(0, callback);
}
})();
}
},
oCoord = {
['1']() {
//设定总行数
oS.R = 5;
oS.DeltaY = 100;
//根据鼠标坐标X范围确定中点X坐标和列C的数组,返回格式[X, C]
window.ChosePlantX = X => {
let C = GetC(X-oS.FightingSceneLeft+oS.EDAllScrollLeft);
return [GetX(C), C];
};
//根据鼠标坐标Y范围确定中点Y坐标和列R的数组,返回格式[Y, R]
window.ChosePlantY = Y => {
let R = GetR(Y, true);
return [GetY(R), R];
};
//根据横坐标X找列C
{
//let CList = $SSmlList([ - 50, 100, 140, 220, 295, 379, 460, 540, 625, 695, 775, 855, 935, 1031], [ - 2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]);
let CList = $SSmlList([ - 50, 100, 140, 225, 305, 385, 465, 545, 625, 705, 785, 865, 935, 1031], [ - 2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]);
window.GetC = X => {
let C = $SEqlSml(Math.floor(X)-CList[1], CList[0], CList[2]);
return C;
}
};
//根据纵坐标Y找行R
window.GetR = (Y, UpsideDownCounted = false) => {
if (oS.UpsideDown && UpsideDownCounted) Y -= 40;
let R = $SSml(Y, [86, 174, 270, 380, 470], [0, 1, 2, 3, 4, 5]);
if (oS.UpsideDown && UpsideDownCounted) R = oS.R - R;
return R;
}
//返回列C的格子水平方向中点X
window.GetX = (C) => {
let X = $SEql(C, {
"-2": -50,
"-1": 100,
0 : 140,
1 : 187,
2 : 267,
3 : 347,
4 : 427,
5 : 507,
6 : 587,
7 : 667,
8 : 747,
9 : 827,
10 : 865,
11 : 950,
12 : 1050,
});
return X;
}
// 返回行R的僵尸/植物底部坐标Y
window.GetY = (R, UpsideDownCounted = false) => {
let Y = [75, 175, 270, 380, 470, 575][R];
if (oS.UpsideDown && UpsideDownCounted) Y = oS.H - Y + oS.DeltaY;
return Y;
}
//根据行返回Y范围,杨桃、保龄球用
window.GetY1Y2 = R => $SEql(R, {
0: [0, 75],
1: [76, 175],
2: [176, 270],
3: [271, 380],
4: [381, 470],
5: [471, 575]
});
// 获取当前行的中点Y坐标
window.GetMidY = R => {
let [y1, y2] = window.GetY1Y2(R);
return Math.round((y1 + y2) / 2);
}
//获取僵尸恰好超过3/4点的格子,僵尸水道方向切换用
{
let CList = $SSmlList([ - 50, 100, 140, 197, 277, 357, 437, 517, 597, 677, 757, 837, 935, 1031], [ - 2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]);
window.GetMidC = X => $SEqlSml(Math.floor(X)-CList[1], CList[0], CList[2]);
};
window.GetMidR = Y => $SSml(Y, [86, 162, 256, 362, 452, 560], [0, 1, 2, 3, 4, 5, 6]) - 1;
window.GetRoofDelta = () => {return 0;};
//生成小推车
!oS.InitLawnMover && (oS.InitLawnMover = _ => {
for(let R = 1; R < 6; R++) {
let WaterLane = false;
for (let C = 1; C <= oS.C; C++) {
if (oGd.$GdType[R][C] === 2) {
WaterLane = true;
break;
}
}
oSym.addTask(R*10, CustomSpecial, [($User.enabledPoolCleaner && WaterLane) ? oPoolCleaner : oLawnCleaner, R, -1]);
}
});
//迷雾
oS.HaveFog && oFog.init().firstRender();
// 初始化僵尸容器
oZombieLayerManager.initContainer();
oP.ConfigureDeltaTop();
//make sure that all rows beyond row 5 in oS.LF and oS.ZF are invalid
oS.LF = oS.LF.slice(0,6);
oS.ZF = oS.ZF.slice(0,6);
},
['2'](){
oS.R = 6;
oS.DeltaY = 88;
window.ChosePlantX = X => {
let C = GetC(X-oS.FightingSceneLeft+oS.EDAllScrollLeft);
return [GetX(C), C];
};
//根据鼠标坐标Y范围确定中点Y坐标和列R的数组,返回格式[Y, R]
window.ChosePlantY = Y => {
let R = GetR(Y, true);
return [GetY(R), R];
};
//根据横坐标X找列C
{
//let CList = $SSmlList([ - 50, 100, 140, 220, 295, 379, 460, 540, 625, 695, 775, 855, 935, 1031], [ - 2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]);
let CList = $SSmlList([ - 50, 100, 140, 225, 305, 385, 465, 545, 625, 705, 785, 865, 935, 1031], [ - 2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]);
window.GetC = X => $SEqlSml(Math.floor(X)-CList[1], CList[0], CList[2]);
};