GameModelManager.ts
40.7 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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
import { AudioManager } from "simba-cc-audio-manager";
import { ResUtils } from "simba-cc-resutils";
import { ConfigManager } from "simba-config-manager";
import { CompositeDisposable, Emitter } from "simba-eventkit";
import { TimeManager } from "simba-sdk";
import { DeepReadonlyObject, shallowEqual } from "simba-utils";
import { ConditionExpression, GameRecord, getPlot, Language, PlotManager, ReadonlyPlot, ReadonlyPlots, richNodesToCocosString, SentenceType, SpecialPlotId } from "../../avg/AVG";
import { DateType, PageIndex } from "../../avg/EditorEnums";
import { EditorEvents } from "../../avg/EditorEvents";
import { GameConstData } from "../../common/gameplay/gamedata/GameConstData";
import { FuncStateEnum, RedPotStateEnum } from "../../common/gameplay/gamedata/GameEnumData";
import { ICharacterVoiceConfig } from "../../config/CharacterVoiceConfig";
import { dateSceneConfig } from "../../config/DateSceneConfig";
import { i18nConfig } from "../../config/I18nConfig";
import { itemConfig } from "../../config/ItemConfig";
import { relationLevelConfig } from "../../config/RelationLevelConfig";
import { IRole, role } from "../../config/Role";
import { taoBaoShopUrlConfig } from "../../config/TaoBaoShopUrlConfig";
import { channel } from "../../GameConfig";
import { AutoPopViewType, DiscoverItemType, FreeState, GuideState, PlotSceneType, PlotSessionState, TutorialState, TutorialType, WorkSpaceTaskState } from "../Enums";
import { SpecialToastType } from "../ui/SpecialToast";
import { DatingEventSceneModel, DatingEventStatus } from "./DatingEventSceneModel";
import GameRoleDataModel from "./GameRoleDataModel";
import { MessageSceneModel } from "./MessageSceneModel";
import { UnlockSpecialPlotModelManager } from "./UnlockSpecialPlotModelManager";
/**
* 游戏model管理类
*/
export namespace GameModelManager {
let emitter = new Emitter;
export const MessageSceneChanged = emitter.createEvent<(scenes: MessageSceneModel[]) => void>();
export const MainDatingEventChanged = emitter.createEvent<(scenes: DatingEventSceneModel[]) => void>();
export const CheckDateGuide = emitter.createEvent<() => void>();//约会界面检测引导
export const CheckMsgGuide = emitter.createEvent<() => void>();//消息列表界面检测引导
export const AutoPopView = emitter.createEvent<(view: AutoPopViewType) => void>();//展示自动弹出界面
export const ShowDatingEventArrowGuide = emitter.createEvent<(isShow: boolean, wordPos?: cc.Vec3) => void>();//约会列表界面展示箭头
export const ShowPlotBlocked = emitter.createEvent<() => void>();//展示剧情阻断弹窗
export const PlotBlockedChanged = emitter.createEvent<() => void>();//剧情阻断改变
export const ForceClickMsgItem = emitter.createEvent<(id: number) => void>();
export const ForceClickDatingItem = emitter.createEvent<(id: number) => void>();
/**报幕数据准备就绪事件 */
export const ForceClickDataReady = emitter.createEvent<() => void>();
export const UnlockItem = emitter.createEvent<(itemId: number) => void>();
/**回滚剧情数据完成刷新所有状态 */
export const RefreshAllStatus = emitter.createEvent<() => void>();
/**触发死亡选项之后的事件派发 */
export const DeadEvent = emitter.createEvent<(pid: number) => void>();
/**关闭约会界面 */
export const CloseDatingSceneView = emitter.createEvent<(id: number) => void>();
/**刷新对应类型的番外 */
export const RefreshExtraPlotByType = emitter.createEvent<(id: number) => void>();
/**关闭番外界面 */
export const CloseExtraSceneView = emitter.createEvent<() => void>();
/**触发剧情属性值变化之后弹起特殊Toast */
export const SpecialToast = emitter.createEvent<(type: SpecialToastType) => void>();
/**从主界面跳转到游戏页面 */
export const JumpToViewInGame = emitter.createEvent<(index: PageIndex) => void>();
/**关闭设置界面 */
export const CloseSettingView = emitter.createEvent<(index: PageIndex) => void>();
let messageScenes: MessageSceneModel[] | undefined;
// let momentScenes: MomentSceneModel[] | undefined;
let mainDatingScenes: DatingEventSceneModel[] | undefined;
export let currPlots: ReadonlyPlot[] | undefined;
let phoneCallIndex: number = -1;
let unlockGift = false;
let isChangPlotSceneType: boolean = false;
let isMainPlot: boolean = true;
let isNeedEnterCurDateChapter: boolean = true;
let _autoPopView: AutoPopViewType[] = [];
export function isChangePlotSceneType() { return isChangPlotSceneType }
export function setIsChangePlotSceneType(isChange: boolean) {
isChangPlotSceneType = isChange;
}
export function isMainPlotSceneType() { return isMainPlot }
export function setIsMainPlotSceneType(isChange: boolean) {
isMainPlot = isChange;
}
export async function rollbackPhoneCallIfNeeded() {
if (phoneCallIndex >= 0 && phoneCallIndex < GameRecord.getCurrentRecordItems().length - 1) {
let ret = await PlotManager.rollbackToIndex(phoneCallIndex);
savePhoneCall();
return ret;
} else {
return PlotManager.getCurrentPlots();
}
}
//#region //数据模块
let roleDatasMap: Map<number, GameRoleDataModel> = new Map<number, GameRoleDataModel>();
let languagesMap: Map<number, string> = new Map<number, string>(); //语言
//#endregion
export function getMessageScenesModel() {
return messageScenes!;
}
export function getMessageSceneModel(id: number) {
return messageScenes!.find(v => v.id === id);
}
export function getMainDatingEventScenesModel() {
return mainDatingScenes!;
}
export function getMainDatingEventSceneModel(id: number) {
return mainDatingScenes!.find(v => v.id === id);
}
export function getMainDatingEventScenesModelByChapterindex(chapterIndex: number): DatingEventSceneModel[] {
let scenes: DatingEventSceneModel[] = [];
if (!mainDatingScenes) {
return [];
}
for (let i = 0; i < mainDatingScenes.length; i++) {
if (ConfigManager.getConfig(dateSceneConfig, mainDatingScenes[i].id).chapter_index === chapterIndex) {
scenes.push(mainDatingScenes[i]);
}
}
return scenes;
}
let creating: boolean = false;
/**开启分支剧情,
* plots:如果需要同时开启多个分支剧情,则数组中存储这些分支中对应的起始剧情id
*/
export async function startBranches(plots: number[]) {
if (creating) return;
creating = true;
if (0 === plots.length) {
// console.warn("no plots to mark as branch start plot id");
return;
}
for (let i = 0; i < plots.length; i++) {
let pid = plots[i];
if (SpecialPlotId.ToBeContinued === pid || SpecialPlotId.End === pid) {
// console.error("you can not start a branch with SpecialPlotId, id is = ", pid);
continue;
}
let p = await getPlot(pid);
if (!p) {
// console.warn("no plot which plot id is = ", pid);
continue;
}
if (currPlots) {
currPlots.push(p);
}
let hasStarted: boolean = checkIsBranchStarted(pid);
if (hasStarted) {
// cc.warn("branch has been started which start plot id is = ", pid);
continue;
}
console.log('开启新分支pid', pid);
let index = await PlotManager.startNewPlotBranch(pid);
pushBranchToRecord(pid, index);
}
creating = false;
}
/**
*
* @param plotId 检测指定剧情下的分支是否已经开启
* @returns
*/
function checkIsBranchStarted(plotId: number): boolean {
const branchRecordKey: string = "BRANCH_INDEX_ENTRY";
let ret: boolean = false;
let itemArr: { startPlot: number, index: number }[] = [];
let recordStr: string = GameRecord.globalVariables[branchRecordKey] as string;
if (recordStr && "" !== recordStr.trim()) {
itemArr = JSON.parse(recordStr) as { startPlot: number, index: number }[];
}
ret = itemArr.findIndex((v) => v.startPlot === plotId) >= 0;
return ret;
}
/**
*
* @param plotId 将分支计入存档
* @param index
*/
function pushBranchToRecord(plotId: number, index: number) {
const branchRecordKey: string = "BRANCH_INDEX_ENTRY";
let exist: boolean = false;
let itemArr: { startPlot: number, index: number }[] = [];
let recordStr: string = GameRecord.globalVariables[branchRecordKey] as string;
if (recordStr && "" !== recordStr.trim()) {
itemArr = JSON.parse(recordStr) as { startPlot: number, index: number }[];
}
exist = itemArr.findIndex((v) => v.startPlot === plotId) >= 0;
if (!exist) {
itemArr.push({
startPlot: plotId,
index: index
});
GameRecord.globalVariables[branchRecordKey] = JSON.stringify(itemArr);
GameRecord.saveRecord();
}
}
/**
* 获取分支剧情状态(约会状态)
* @param plotSceneTypeId 剧情类型id
* @param start_plot_id 起始剧情id
* @returns 剧情状态
*/
export function getBranchStatus(plotSceneTypeId: number, start_plot_id: number): DatingEventStatus {
let s = DatingEventStatus.New;
let curP = PlotManager.getCurrentPlots();
let progress = curP.findIndex((v) => v.plotSceneTypeId === plotSceneTypeId) >= 0;
let isNew = curP.findIndex((v) => v.plotSceneTypeId === plotSceneTypeId && v.id === start_plot_id) >= 0;
s = isNew ? DatingEventStatus.New : progress ? DatingEventStatus.InProgress : DatingEventStatus.Completed;
return s;
}
/**获取已开启的所有番外id */
export function getAllStartedBranches(): { startPlot: number, index: number }[] {
const branchRecordKey: string = "BRANCH_INDEX_ENTRY";
let itemArr: { startPlot: number, index: number }[] = [];
let recordStr: string = GameRecord.globalVariables[branchRecordKey] as string;
if (recordStr && "" !== recordStr.trim()) {
itemArr = JSON.parse(recordStr) as { startPlot: number, index: number }[];
}
return itemArr;
}
let branchCompleteRecordKey: string = "branch_complete";
/**设置分支完成 */
export function setBranchComplete(branchId: number) {
let rStr = GameRecord.globalVariables[branchCompleteRecordKey] as string;
let rArr: number[] = [];
if (rStr && "" !== rStr) {
rArr = JSON.parse(rStr) as number[];
}
let exist = rArr.findIndex((v) => v === branchId) !== (-1);
if (!exist) {
rArr.push(branchId);
GameRecord.globalVariables[branchCompleteRecordKey] = JSON.stringify(rArr);
GameRecord.saveRecord();
}
}
/**检测分支是否完成 */
export function checkBranchIsComplete(branchId: number): boolean {
let rStr = GameRecord.globalVariables[branchCompleteRecordKey] as string;
let rArr: number[] = [];
if (rStr && "" !== rStr) {
rArr = JSON.parse(rStr) as number[];
}
let exist = rArr.findIndex((v) => v === branchId) !== (-1);
return exist;
}
let branchInProgressRecordKey: string = "branch_InProgress";
/**设置分支完成 */
export function setBranchInProgress(branchId: number) {
let rStr = GameRecord.globalVariables[branchInProgressRecordKey] as string;
let rArr: number[] = [];
if (rStr && "" !== rStr) {
rArr = JSON.parse(rStr) as number[];
}
let exist = rArr.findIndex((v) => v === branchId) !== (-1);
if (!exist) {
rArr.push(branchId);
GameRecord.globalVariables[branchInProgressRecordKey] = JSON.stringify(rArr);
GameRecord.saveRecord();
}
}
/**检测分支是否完成 */
export function checkBranchIsInProgress(branchId: number): boolean {
let rStr = GameRecord.globalVariables[branchInProgressRecordKey] as string;
let rArr: number[] = [];
if (rStr && "" !== rStr) {
rArr = JSON.parse(rStr) as number[];
}
let exist = rArr.findIndex((v) => v === branchId) !== (-1);
return exist;
}
export interface EventResourcesState {
eventId: number,
bgm: string,
backgroud: string
}
async function initConfigData() {
await ConfigManager.initConfigData(false);
await initLanguageConfig();
initRoleConfig();
}
export function getI18LanguageTxt(id: number) {
let i18 = ConfigManager.getConfig(i18nConfig, id);
return i18.cn;
}
function initRoleConfig() {
let cfg = ConfigManager.getAllConfig(role);
for (let id in cfg) {
let element = cfg[id] as IRole;
if (element) {
let data = new GameRoleDataModel();
data.setConfig(element);
roleDatasMap.set(element.id, data);
}
}
}
function getLanguagePath() {
return "userdata/language/chinese";
}
async function initLanguageConfig() {
let cfgFile = await ResUtils.loadRes<any>(getLanguagePath(), cc.JsonAsset);
if (cfgFile) {
let lans: Language[] = cfgFile as Language[];
for (let i = 0; i < lans.length; ++i) {
let element = lans[i] as Language;
if (element) {
languagesMap.set(element.id, element.value);
}
}
}
}
export function getLanguageTxt(id: number): string {
if (languagesMap.has(id)) {
return languagesMap.get(id) as string;
} else {
// console.log("current language id is miss " + id);
return "";
}
}
export function getConfigLanguageTxt(id: number): string {
return ConfigManager.getConfig(i18nConfig, id).cn;
}
export function getItemConfig(id: number) {
return ConfigManager.getConfig(itemConfig, id);
}
export function getItemConfigs() {
return ConfigManager.getAllConfig(itemConfig);
}
export function getRoleData(id: number) {
if (!roleDatasMap.has(id)) {
return undefined;
}
return roleDatasMap.get(id);
}
export function getPlayerData() {
return GameModelManager.getRoleData(GameConstData.GAME_CONST_PLAYER_ROLE_VALUE)!;
}
let disposable: CompositeDisposable;
export async function init(onProgress?: Function) {
await initConfigData();
if (onProgress) onProgress(0.92);
tipAddGracePlots = [];
phoneCallIndex = GameRecord.recordVariables["gm.pci"] as number;
unlockGift = !!GameRecord.recordVariables["gm.unlockGift"];
if (phoneCallIndex === undefined) phoneCallIndex = -1;
let initRet: Promise<any>[] = [];
{ // init message models
let ids = GameRecord.recordVariables["gm.ms"] as any;
if (ids !== undefined) {
messageScenes = [];
messageScenes = ids.map((id: number) => new MessageSceneModel(id));
initRet.push(...messageScenes!.map((s) => s.initFromRecords()));
} else {
messageScenes = [];
}
}
{ // init main dating models
let ids = GameRecord.recordVariables["gm.md"] as any;
if (ids !== undefined) {
mainDatingScenes = [];
mainDatingScenes = ids.map((id: number) => new DatingEventSceneModel(id));
initRet.push(...mainDatingScenes!.map((s) => s.initFromRecords()));
} else {
mainDatingScenes = [];
}
}
{//init application
cc.game.on(cc.game.EVENT_HIDE, () => {
// console.log("enter game background");
AudioManager.pauseMusic();
});
cc.game.on(cc.game.EVENT_SHOW, () => {
// console.log("enter game force");
AudioManager.resumeMusic();
});
}
if (initRet.length) {
await Promise.all(initRet);
}
if (onProgress) onProgress(0.94);
if (!disposable) {
disposable = new CompositeDisposable;
disposable.add(PlotManager.PlotWillStart.on(handlePlotWillStart));
disposable.add(EditorEvents.UNLOCK_ITEM.on(onUnlockItem));
disposable.add(EditorEvents.UNLOCK_SPECIAL_PLOT.on(onUnlockSpecialPlot));
disposable.add(EditorEvents.DEAD_EVENT.on(onDeadEvevt));
disposable.add(EditorEvents.SPECIAL_TOAST.on(onSpecialToast));
}
initPlots();
if (onProgress) onProgress(0.96);
for (let scene of mainDatingScenes!) { // 检查主线剧情状态
if (currPlots![0].plotSceneType !== PlotSceneType.DatingEvent ||
(scene.id !== currPlots![0].plotSceneTypeId && scene.status !== DatingEventStatus.Completed)) {
scene.status = DatingEventStatus.Completed;
}
}
if (onProgress) onProgress(0.98);
}
function onUnlockItem(itemId: string) {
let s = itemId;
if (s && "" !== s.trim()) {
let n = parseInt(s);
UnlockItem.emit(n);
}
}
function onDeadEvevt(pid: string) {
let s = pid;
if (s && "" !== s.trim()) {
let n = parseInt(s);
DeadEvent.emit(n);
}
}
function onSpecialToast(type: string) {
let s = type;
if (s && "" !== s.trim()) {
let n = parseInt(s) as SpecialToastType;
SpecialToast.emit(n);
}
}
export function onUnlockSpecialPlot(specialPlotId: string) {
let s = specialPlotId;
if (s && "" !== s.trim()) {
let n = parseInt(s);
UnlockSpecialPlotModelManager.saveUnlockedSpecialPlotIdByItemIdToGameRecord(n);
}
}
/**
* set main tab guide record value
* @param index
* @param record
*/
export function setGuideMainTabRecord(index: number, record: GuideState) {
let r = GameRecord.globalVariables["guide_main_tab" + index] as number;
if (r && record <= r) {
return;
}
GameRecord.globalVariables["guide_main_tab" + index] = record;
GameRecord.saveRecord();
}
/**
* get main tab guide index
*/
export function getMainTabGuideIndex(): number {
let index = -1;
const MAX = 4;
for (let i = 0; i < MAX; i++) {
let r = GameRecord.globalVariables["guide_main_tab" + i] as number;
r = r === undefined ? GuideState.close : r;
if (r === GuideState.Open) {
index = i;
}
}
return index;
}
/**
* set event item guide record value
* @param itemKey
* @param record
*/
export function setGuideEventItemRecord(itemKey: string, record: GuideState) {
let r = GameRecord.globalVariables["guide_evt_item"] as number;
r = r === undefined ? GuideState.close : r;
if (record <= r) {
return;
}
GameRecord.globalVariables["guide_evt_item_key"] = itemKey;
GameRecord.globalVariables["guide_evt_item"] = record;
GameRecord.saveRecord();
}
/**
* get event item guide key
*/
export function getEventItemGuideKey(): string {
let key: string = "";
let r = GameRecord.globalVariables["guide_evt_item"] as number;
r = r === undefined ? GuideState.close : r;
let k = GameRecord.globalVariables["guide_evt_item_key"] as string;
if (r && r === GuideState.Open) {
key = k;
}
return key;
}
/**
* set msg guide item record value
* @param itemKey
* @param record
*/
export function setGuideMsgItemRecord(itemKey: string, record: GuideState) {
let r = GameRecord.globalVariables["guide_msg_item"] as number;
r = r === undefined ? GuideState.close : r;
if (record <= r) {
return;
}
GameRecord.globalVariables["guide_msg_item_key"] = itemKey;
GameRecord.globalVariables["guide_msg_item"] = record;
GameRecord.saveRecord();
}
/**
* get msg item guide key
*/
export function getMsgItemGuideKey(): string {
let key: string = "";
let r = GameRecord.globalVariables["guide_msg_item"] as number;
r = r === undefined ? GuideState.close : r;
let k = GameRecord.globalVariables["guide_msg_item_key"] as string;
if (r && r === GuideState.Open) {
key = k;
}
return key;
}
function save() {
let oldValue = GameRecord.recordVariables["gm.ms"];
let newValue = messageScenes!.map(v => v.id) as any;
if (!shallowEqual(oldValue, newValue)) {
GameRecord.recordVariables["gm.ms"] = newValue;
}
oldValue = GameRecord.recordVariables["gm.md"];
newValue = mainDatingScenes!.map(v => v.id) as any;
if (!shallowEqual(oldValue, newValue)) {
GameRecord.recordVariables["gm.md"] = newValue;
}
}
function savePhoneCall() {
GameRecord.recordVariables["gm.pci"] = phoneCallIndex;
GameRecord.saveRecord();
}
async function initPlots() {
let plots = PlotManager.getCurrentPlots();
if (true) {
currPlots = [...plots];
if (!messageScenes) { // 第一次进游戏,根据剧情初始化数据
messageScenes = [];
}
if (!mainDatingScenes) {
mainDatingScenes = [];
}
for (let i = 0; i < plots.length; i++) {
let plot = plots[i];
if (plot.plotSceneType === PlotSceneType.Message) {
let index = messageScenes.findIndex(v => v.id === plot.plotSceneTypeId);
if (index < 0) {
index = 0;
let model = new MessageSceneModel(plot.plotSceneTypeId);
model.firstPlot = plot;
messageScenes.unshift(model);
}
} else if (plot.plotSceneType === PlotSceneType.DatingEvent) {
let cfg = ConfigManager.getConfig(dateSceneConfig, plot.plotSceneTypeId);
if (cfg.DateType === DateType.Date_Normal) { // 主线约会剧情
if (plots[0] !== plot) { console.error("主线约会剧情应在主线开启"); continue; }
if (mainDatingScenes.findIndex(v => v.id === plot.plotSceneTypeId) < 0) {
let model = new DatingEventSceneModel(plot.plotSceneTypeId);
model.firstPlot = plot;
model.status = DatingEventStatus.New;
mainDatingScenes.push(model);
}
}
}
}
save();
}
}
async function handlePlotWillStart(plot: ReadonlyPlot, branch: number) {
handleNewPlot(currPlots![branch], plot, branch);
currPlots![branch] = plot;
}
async function handleNewPlot(prevPlot: ReadonlyPlot | undefined, plot: ReadonlyPlot, branch: number) {
if (plot.plotSceneType === PlotSceneType.Message) {
let idx = messageScenes!.findIndex(v => v.id === plot.plotSceneTypeId);
if (idx >= 0) { // 原会话中有新消息
let model = messageScenes![idx];
if (idx > 0) {
let reorderIdx = 0;
if (branch > 0 && currPlots && currPlots[0].plotSceneType === PlotSceneType.Message) {
reorderIdx = 1;
}
for (let i = idx; i > reorderIdx; i--) {
messageScenes![i] = messageScenes![i - 1];
}
messageScenes![reorderIdx] = model;
}
} else { // 新会话
let model = new MessageSceneModel(plot.plotSceneTypeId);
model.firstPlot = plot;
messageScenes!.unshift(model);
}
MessageSceneChanged.emit(messageScenes!);
save();
} else if (plot.plotSceneType === PlotSceneType.PhoneCall) {
if (!prevPlot || prevPlot.plotSceneType !== PlotSceneType.PhoneCall) {
phoneCallIndex = GameRecord.getCurrentRecordItems().length; // 当前存档还没生成,不需要减1
savePhoneCall();
}
} else if (plot.plotSceneType === PlotSceneType.DatingEvent) {
let cfg = ConfigManager.getConfig(dateSceneConfig, plot.plotSceneTypeId);
if (cfg.DateType === DateType.Date_Normal) { // 主线约会剧情
if (branch !== 0) { console.error("主线约会剧情应在主线开启"); return; }
let idx = mainDatingScenes!.findIndex(v => v.id === plot.plotSceneTypeId);
if (idx < 0) { // 新开启
let model = new DatingEventSceneModel(plot.plotSceneTypeId);
model.firstPlot = plot;
model.status = DatingEventStatus.New;
mainDatingScenes!.push(model);
MainDatingEventChanged.emit(mainDatingScenes!);
}
save();
}
}
if (prevPlot && prevPlot.plotSceneType === PlotSceneType.PhoneCall && plot.plotSceneType !== PlotSceneType.PhoneCall) {
phoneCallIndex = -1;
savePhoneCall();
}
if (prevPlot && (prevPlot.plotSceneType !== plot.plotSceneType || prevPlot.plotSceneTypeId !== plot.plotSceneTypeId)) { // 切换场景
if (prevPlot.plotSceneType === PlotSceneType.DatingEvent) {
let model = mainDatingScenes!.find(v => v.id === prevPlot.plotSceneTypeId);
if (model) model.status = DatingEventStatus.Completed;
}
}
isChangPlotSceneType = !prevPlot || (prevPlot.plotSceneType !== plot.plotSceneType || prevPlot.plotSceneTypeId !== plot.plotSceneTypeId);
//main plot line progress
if (0 === branch && checkIsDotTutorial()) {
stepMainLinePlotProgress();
}
}
function stepMainLinePlotProgress() {
let r = GameRecord.recordVariables["p_s_t_i_p"] as number;
r = r ? r : 0;
if (isChangPlotSceneType) {
r = 1;
} else {
r++;
}
GameRecord.recordVariables["p_s_t_i_p"] = r;
}
export function dotMainLinePlotStart() {
// main plot line progress and change plot scene (for BI dot);
let plot = PlotManager.getCurrentPlots()[0];
let mainPlotLineSession = GameRecord.globalVariables["m_p_l_s"] as number;//主线总session计数
mainPlotLineSession = mainPlotLineSession ? mainPlotLineSession : 1;
let sKey = "m_l_p_s_started";
let startedSession = GameRecord.globalVariables[sKey] as number;
startedSession = startedSession ? startedSession : 0;
if (startedSession >= mainPlotLineSession) {//max is equal
return;
}
GameRecord.globalVariables["m_p_l_s"] = mainPlotLineSession;
let plotScenTypeSession = GameRecord.globalVariables["p_s_t_s" + plot.plotSceneType] as number;
plotScenTypeSession = plotScenTypeSession ? plotScenTypeSession : 0;
plotScenTypeSession++;
GameRecord.globalVariables["p_s_t_s" + plot.plotSceneType] = plotScenTypeSession;//不同场景类型分别session计数
if (checkIsDotTutorial()) {
GameRecord.recordVariables["p_s_t_i_p"] = 1;//主线剧情中,当前场景类型progress进度计数
}
GameRecord.globalVariables[sKey] = mainPlotLineSession;
GameRecord.saveRecord();
}
/**
* 主线剧情结束打点
*/
export function dotMainLinePlotEnd() {
let mainPlotLineSession = GameRecord.globalVariables["m_p_l_s"] as number;
GameRecord.globalVariables["m_p_l_s"] = mainPlotLineSession + 1;
GameRecord.saveRecord();
}
export function checkFuncUnloced(key: string) {
return GameRecord.recordVariables[key] === FuncStateEnum.locked ? false : true;
}
export function checkRedPot(key: string) {
return GameRecord.globalVariables["red_pot_" + key] === RedPotStateEnum.Show;
}
export function setRedPotState(key: string, state: RedPotStateEnum) {
GameRecord.globalVariables["red_pot_" + key] = state;
GameRecord.autoSave();
}
export function checkVoiceNeedShowAD(vCfg: ICharacterVoiceConfig) {
let ret = false;
if (vCfg) {
if (vCfg.ads === 0) {
return ret;
}
let voiceAdRecord = GameRecord.globalVariables["voice_ad"] as string;
let arr: number[] = [];
if (voiceAdRecord) {
arr = JSON.parse(voiceAdRecord) as number[];
}
let set = new Set(arr);
ret = !set.has(vCfg.id);
}
return ret;
}
export function pushVoiceShowAdToRecord(voiceId: number) {
let voiceAdRecord = GameRecord.globalVariables["voice_ad"] as string;
let arr: number[] = [];
if (voiceAdRecord) {
arr = JSON.parse(voiceAdRecord) as number[];
}
let set = new Set(arr);
if (!set.has(voiceId)) {
arr.push(voiceId);
}
GameRecord.globalVariables["voice_ad"] = JSON.stringify(arr);
GameRecord.autoSave();
}
export function getCurDayStr(): string {
let t = TimeManager.getTime();
let time = new Date(t);
let y = time.getFullYear();
let m = time.getMonth() + 1;
let d = time.getDate();
let timeStr = y + "_" + m + "_" + d;
return timeStr;
}
export function checkIsDotTutorial(): boolean {
let curPlot = PlotManager.getCurrentPlots()[0];
return curPlot && curPlot.chapterId === GameConstData.GAME_CONST_FIRST_CHAPTER_ID;
}
export function getLastFreeTime(): number {
let time: number = 0;
let recordKey: string = "luck_draw_free_time";
let record = GameRecord.globalVariables[recordKey] as number;
time = record ? record : 0;
return time;
}
export function checkOverdue(time: number, refreshhour: number = 4) {//检测是否过期
let checkTime = new Date(time);
let currentTime = new Date(TimeManager.getTime());
let year = checkTime.getFullYear();
let month = checkTime.getMonth() + 1;
let day = checkTime.getDate();
let hour = checkTime.getHours();
if (currentTime.getFullYear() > year) {
return true;
} else if (currentTime.getMonth() + 1 > month) {
return true;
} if (currentTime.getDate() == day) {
if (hour > 0 && hour < refreshhour) {
if (currentTime.getHours() >= refreshhour) {
return true;
}
}
} else if (currentTime.getDate() > day && currentTime.getHours() >= refreshhour) {
return true;
}
return false;
}
export function checkSkinAndGraceCondition(condition: DeepReadonlyObject<ConditionExpression>): boolean {
let ret: boolean = false;
if (condition.groups && condition.groups.length > 0
&& condition.groups[0].items
&& condition.groups[0].items.length > 0
&& condition.groups[0].items[0].target) {
if (condition.groups[0].items[0].target.startsWith("r.like")) {
let roleIdStr = condition.groups[0].items[0].target.replace("r.like", "");
let role = getRoleData(parseInt(roleIdStr));
if (role && role.getRoleLike() >= parseInt(condition.groups[0].items[0].oprand.value)) {
ret = true;
}
}
if (condition.groups[0].items[0].target.startsWith("r.skin")) {
let roleIdStr = condition.groups[0].items[0].target.replace("r.skin", "");
let role = getRoleData(parseInt(roleIdStr));
let v = parseInt(condition.groups[0].items[0].oprand.value);
if (role && role.hasSkin(v) && role.getCurSkin() === v) {
ret = true;
}
}
}
return ret;
}
export function getGraceLevelByGraceValue(value: number): number {
let level = 0;
let cfgs = ConfigManager.getAllConfig(relationLevelConfig);
let gCount = 0;
for (let id in cfgs) {
let cfg = cfgs[id];
gCount += cfg.relation_value;
if (value >= gCount) {
level = cfg.id;
}
}
return level;
}
export function setNotNeedEnterCurDateChapter() {
isNeedEnterCurDateChapter = false;
}
export function registerAutoPopView(viewType: AutoPopViewType) {
if (_autoPopView.length === 0) {
_autoPopView.push(viewType);
} else {
if (_autoPopView.findIndex((v) => v === viewType) === (-1)) {
_autoPopView.push(viewType);
}
}
}
export function checkAutoPopView() {
if (_autoPopView.length === 0) {
return;
}
_autoPopView = _autoPopView.sort((v1: AutoPopViewType, v2: AutoPopViewType) => {
return v1 - v2;
});
let v = _autoPopView.pop();
if (v) {
AutoPopView.emit(v);
}
}
export function checkIsOverPlotLimitTime() {
let isOver: boolean = false;
let timeKeyStr: string = "plot_limit_time";
let recordTime = GameRecord.globalVariables[timeKeyStr] as number;
if (recordTime) {
isOver = checkOverdue(recordTime);
} else {
let timeKeyStr: string = "plot_limit_time";
GameRecord.globalVariables[timeKeyStr] = TimeManager.getTime();
}
return isOver;
}
export async function dealBlockedPlot(isAdForce?: boolean) {
let over = checkIsOverPlotLimitTime();
let curPlot = PlotManager.getCurrentPlots()[0];
if (curPlot && curPlot.plotSceneType === PlotSceneType.BlockPlot) {
if (over || isAdForce) {
await PlotManager.completePlot(curPlot);
let timeKeyStr: string = "plot_limit_time";
GameRecord.globalVariables[timeKeyStr] = TimeManager.getTime();
PlotBlockedChanged.emit();
} else {
ShowPlotBlocked.emit();
}
}
}
export function checkIsPlotBlocked(): boolean {
let blocked: boolean = false;
let curPlot = PlotManager.getCurrentPlots()[0];
if (curPlot && curPlot.plotSceneType === PlotSceneType.BlockPlot) {
blocked = true;
}
return blocked;
}
export function getCurMainLinePlotId(): number {
let p = PlotManager.getCurrentPlots()[0];
return p ? p.id : 0;
}
let tipAddGracePlots: number[] = [];
export function checkPlotTipAddGraceAlready(plotId: number): boolean {
let ret = tipAddGracePlots.findIndex((v) => v === plotId) !== (-1);
return ret;
}
export function pushTipAddGracePlot(plotId: number) {
let exist = tipAddGracePlots.findIndex((v) => v === plotId) !== (-1);
if (!exist) {
tipAddGracePlots.push(plotId);
}
}
/**
* 根据商品类型获得该商品对应的淘宝地址链接
* @param type 商品类型
* @returns 返回值为商品类型对应的商品地址
*/
export function getTaoBaoShopUrlByType(type: number): string {
let link: string = "";
let cfg = ConfigManager.getAllConfig(taoBaoShopUrlConfig);
if (cfg) {
for (const id in cfg) {
if (cfg[id].type == type) {
link = cfg[id].websiteUrl;
}
}
}
return link;
}
/**
* 根据商品类型获得该商品对应的有赞地址链接
* @param type 商品类型
* @returns 返回值为商品类型对应的商品地址
*/
export function getYouZanShopUrlByType(type: number): string {
let link: string = "";
let cfg = ConfigManager.getAllConfig(taoBaoShopUrlConfig);
if (cfg) {
for (const id in cfg) {
if (cfg[id].type == type) {
link = cfg[id].youZanUrl;
}
}
}
return link;
}
/**
* 根据网页链接跳转网页
* @param url 要跳转的网页链接
*/
export function jumpToTaobaoShop(url: string) {
if (channel == "dummy") {
let mUrl = url.replace("taobao:", "https:");
window.open(mUrl);
} else {
let packageName: string = "com.taobao.taobao";
let errorTips: string = "您还没有安装淘宝客户端!";
jsb.reflection.callStaticMethod('org/cocos2dx/javascript/AppActivity', 'jumpToTaobaoShop', "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V", packageName, url, errorTips);
}
}
/**特殊剧情id数组 */
const SpecialPlotIdArr: number[] = [SpecialPlotId.CustomPlotStart, SpecialPlotId.End, SpecialPlotId.ToBeContinued];
/**根据剧情id获取剧情的内容 */
export async function getPlotContent(plotId: number): Promise<IPlotContent | undefined> {
let plotContent: IPlotContent | undefined = undefined;
let isSpecialPlot = SpecialPlotIdArr.findIndex((v) => v === plotId) !== (-1);
if (isSpecialPlot) {
cc.error("can not get special plot content, plotId = ", plotId);
return undefined;
}
try {
let plot = await getPlot(plotId);
if (plot && plot.sentences && plot.sentences.length !== 0) {
const sentence = plot.sentences[0];
const content = sentence.content;
if (content) {
plotContent = {
plotId: plotId,
roleId: sentence.roleId,
content: []
};
if (content.type === SentenceType.TEXT) {
plotContent.content.push(richNodesToCocosString(content.value));
} else if (content.type === SentenceType.SELECT) {
for (let i = 0; i < content.value.length; i++) {
let value = content.value[i];
if (value.content && value.content.type === SentenceType.TEXT) {
plotContent.content.push(richNodesToCocosString(value.content.value));
} else {
plotContent.content.push(value.summary);
}
}
}
} else {
cc.error("plot has no content , plotId = ", plotId);
}
} else {
cc.warn("plot has no sentence or no such plot , plotId = ", plotId);
}
} catch (error) {
cc.error("getPlotContent error plotId = " + plotId + " error info = ", error);
return undefined;
}
return plotContent;
}
/**
* 设置是否自动弹出公告界面
* @param autoShow 是否自动弹出公告界面
*/
export function setAutoShowNotice(autoShow: boolean) {
let autoShowNoticeInfo: AutoShowNoticeInfo = {
time: TimeManager.getTime(),
autoShow: autoShow,
};
GameRecord.globalVariables["AutoShowNoticeInfo"] = autoShowNoticeInfo;
GameRecord.saveRecord();
}
/**
* 获取是否自动弹出公告界面
* @returns 返回值为是否自动弹出公告界面
*/
export function getAutoShowNotice(): boolean {
let autoShowNoticeInfo = GameRecord.globalVariables["AutoShowNoticeInfo"] as AutoShowNoticeInfo;
let autoShow = true;
if (autoShowNoticeInfo == undefined) {
autoShow = true;
} else {
autoShow = autoShowNoticeInfo.autoShow;
let isOver = checkOverdue(autoShowNoticeInfo.time);
if (isOver) {
autoShow = true;
setAutoShowNotice(autoShow);
}
}
return autoShow;
}
}
export interface IPlotContent {
plotId: number;
roleId: number;
content: string[];
}
export interface AutoShowNoticeInfo {
time: number;
autoShow: boolean;
}