-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
926 lines (821 loc) · 37.5 KB
/
index.html
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
<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, viewport-fit=cover, user-scalable=no"/>
<!-- Спасибо за установку Advanced Templates -->
<!-- Стой, не спускайся вниз. Залезь мне в сердце, а не в нижние строки код. (feat. Монеточка) -->
<!-- Additional head modules -->
<!-- Yandex Games SDK -->
<script src="https://yandex.ru/games/sdk/v2"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script src="https://unpkg.com/@vkontakte/vk-bridge/dist/browser.min.js"></script>
<script>
function TryShowReward() // функция вызывается из Unity
{
vkBridge.send('VKWebAppCheckNativeAds', { ad_format: 'reward' })
.then((data) => {
if (data.result)
{
console.log('Реклама показана');
myGameInstance.SendMessage('JSBridge', 'SuccesRewardAd');
} else
{
console.log('Ошибка при показе');
myGameInstance.SendMessage('JSBridge', 'FailedRewardAd');
}
})
.catch((error) => { console.log("error: " + error); /* Ошибка */ });
}
function OnGameLoaded()
{
console.log("STARTED INIT ADS");
vkBridge.send('VKWebAppCheckNativeAds', { ad_format: 'reward' })
.then((data) => {
if (data.result)
{
console.log('Рекламные материалы найдены!.');
} else
{
console.log('Рекламные материалы не найдены.');
}
})
.catch((error) => { console.log(error); });
}
jQuery(document).ready(function($) // страница прогружена
{
console.log("STARTED INIT BRIDGE");
vkBridge.send('VKWebAppInit')
.then((data) => {
if (data.result)
{
console.log("Bridge succesfull initialized")
} else
{
console.log("Bridge not initialized")
}
})
.catch((error) => {
// Ошибка
console.log(error);
});
});
</script>
<style>
/* Убираем выделение по нажатию клавиш */
canvas:focus {
outline: none;
}
html, body {
/* Убираем отступы */
padding: 0;
margin: 0;
/* Отключаем скролл и лонгтап на IOS */
overflow: hidden;
-webkit-touch-callout:none;
-webkit-user-select:none;
-khtml-user-select:none;
-moz-user-select:none;
-ms-user-select:none;
user-select:none;
-webkit-tap-highlight-color:rgba(0,0,0,0);
/* Ставим высоту на 100% */
height: 100%;
/* Центрируем, если привязана картинка или творим магию, чтобы можно было использовать градиент */
background-position-x: 50%;
background-repeat: no-repeat;
background-size: cover;
background-attachment: fixed;
}
/* Канвас и загрузочный экран */
#canvas {
position: fixed;
width: 100%;
height: 100%;
}
.loading_bg {
position: fixed;
width: 100%;
height: 100%;
z-index: 1;
/* Центрируем, если привязана картинка или творим магию, чтобы можно было использовать градиент */
background-position-x: 50%;
background-repeat: no-repeat;
background-size: cover;
background-attachment: fixed;
}
.loading {
position: absolute;
/*background-color:red;*/
}
.loading_bar {
position: absolute;
z-index: 6;
transform: translate(-50%, -50%);
}
.loading_bar_fill {
position: absolute;
z-index: 6;
width: 0%;
height: 100%;
top: 0%;
bottom: 0%;
left: 0%;
}
.loading_logo {
position: absolute;
transform: translate(-50%, -50%);
z-index: 6;
pointer-events: none;
background-position: center;
background-repeat: no-repeat;
background-size: contain;
background-attachment: scroll;
}
.spinner {
position: absolute;
border: 5px solid #FFF;
border-bottom-color: transparent;
border-radius: 50%;
box-shadow: 0px 0px 0px 7px rgba(34, 60, 80, 0.2);
margin: auto;
top: 70%;
left: 0;
right: 0;
bottom: 0;
z-index: 6;
animation: spinner-spin 1.1s infinite linear;
}
@keyframes spinner-spin {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
</style>
</head>
<body>
<!-- Additional body modules -->
<canvas id="canvas" class="canvas" tabindex="-1"></canvas>
<div class="loading_bg">
<div class="loading">
<div class="spinner"></div>
<div class="loading_logo"></div>
<div class="loading_bar">
<div class="loading_bar_fill">
</div>
</div>
</div>
<script>
var canvas = document.querySelector("#canvas");
var loading_bg = document.querySelector(".loading_bg");
var loading = document.querySelector(".loading");
var loading_bar = document.querySelector(".loading_bar");
var loading_bar_fill = document.querySelector(".loading_bar_fill");
var loading_logo = document.querySelector(".loading_logo");
const spinner = document.querySelector('.spinner');
// Подключаем ATinstance для связи Unity с браузером
var ATinstance = null;
function ATinstanceEnable(callback) {
const checkNull = () => {
if(ATinstance !== null) {
callback();
} else {
setTimeout(checkNull, 1000);
}
};
checkNull();
}
// Выключаем появление меню при правом клике мыши
document.addEventListener('contextmenu', event => event.preventDefault());
// Проверяем устройство
var isDeviceTouch;
var isDeviceNavigator;
// Определение с помощью тач
if('ontouchstart' in window || navigator.maxTouchPoints > 0 || navigator.msMaxTouchPoints > 0 || /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
isDeviceTouch = true;
} else {
isDeviceTouch = false;
}
// Определение с помощью navigator
if(/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
isDeviceNavigator = true;
} else {
isDeviceNavigator = false;
}
// Возвращаем фокус, если кликнули по экрану
window.addEventListener('pointerdown', () => {
window.focus();
canvas.focus();
});
window.addEventListener('touchstart', () => {
window.focus();
canvas.focus();
});
// Настраиваем лого во время загрузочного экрана
loading_logo.style.display = "none";
// Настраиваем фон полос по бокам
document.body.style.backgroundColor = "black";
// Настраиваем фон загрузочного экрана
loading_bg.style.backgroundColor = "black";
function setLoading(logoPositionTop, logoPositionLeft, logoWidth, logoHeight, positionTop, positionLeft, width, height, barColor, barFillColor, barBorder, barFillBorder, barBorderRadius, barFillBorderRadius, barBackgroundImage, barBackgroundSize) {
// Указываем размер логотипа
loading_logo.style.top = logoPositionTop;
loading_logo.style.left = logoPositionLeft;
loading_logo.style.width = logoWidth;
loading_logo.style.height = logoHeight;
loading_bar.style.top = positionTop;
loading_bar.style.left = positionLeft;
loading_bar.style.width = width;
loading_bar.style.height = height;
loading_bar.style.backgroundColor = barColor;
loading_bar_fill.style.backgroundColor = barFillColor;
loading_bar.style.boxShadow = barBorder;
loading_bar_fill.style.boxShadow = barFillBorder;
loading_bar.style.borderRadius = barBorderRadius;
loading_bar_fill.style.borderRadius = barFillBorderRadius;
loading_bar.style.backgroundImage = loading_bar_fill.style.backgroundImage = barBackgroundImage;
loading_bar.style.backgroundSize = loading_bar_fill.style.backgroundSize = barBackgroundSize;
}
// Фиксация разрешения
function lock(object, aspectRatio) {
if(window.innerWidth / window.innerHeight > aspectRatio) {
object.style.width = window.innerHeight * aspectRatio + "px";
object.style.height = "100%";
} else {
object.style.width = "100%";
object.style.height = window.innerWidth / aspectRatio + "px";
}
// Центрируем
object.style.margin = "auto";
object.style.top = "0";
object.style.left = "0";
object.style.bottom = "0";
object.style.right = "0";
}
// Настраиваем расположение, размер и оформление полосы с лого
var loading_bar_style;
var loadingStyleText = '';
var loadingZeroStrings = ["0"];
var loadingOneStrings = ["1"];
var loadingTwoStrings = ["2"];
var loadingThreeStrings = ["3"];
var loadingFourStrings = ["4"];
if(loadingZeroStrings.some(i => loadingStyleText.includes(i))) {
loading_bar_style = 0;
} else if(loadingOneStrings.some(i => loadingStyleText.includes(i))) {
loading_bar_style = 1;
} else if(loadingTwoStrings.some(i => loadingStyleText.includes(i))) {
loading_bar_style = 2;
} else if(loadingThreeStrings.some(i => loadingStyleText.includes(i))) {
loading_bar_style = 3;
} else if(loadingFourStrings.some(i => loadingStyleText.includes(i))) {
loading_bar_style = 4;
} else {
loading_bar_style = 0;
}
// Вызываем апдейт при входе на страницу и изменений размеров окна браузера
function Update() {
// Фиксируем экран с игрой
var lockCanvasText = 'pc';
var desktopStrings = ["pc", "desktop", "computer", "laptop", "windows", "пк", "компьютер", "виндовс", "оба", "все", "all", "полн"];
var mobileStrings = ["mobile", "phone", "handheld", "android", "телефон", "мобиль", "андроид", "оба", "все", "all", "полн"];
var touchStrings = ["touch", "тач"];
var navigatorStrings = ["nav", "навиг", "userAgent"];
if(touchStrings.some(i => lockCanvasText.includes(i))) {
if(isDeviceTouch) {
if(mobileStrings.some(i => lockCanvasText.includes(i))) {
lock(canvas, 1080 / 2400 );
}
} else {
if(desktopStrings.some(i => lockCanvasText.includes(i))) {
lock(canvas, 1080 / 2400 );
}
}
} else if(navigatorStrings.some(i => lockCanvasText.includes(i))) {
if(isDeviceNavigator) {
if(mobileStrings.some(i => lockCanvasText.includes(i))) {
lock(canvas, 1080 / 2400 );
}
} else {
if(desktopStrings.some(i => lockCanvasText.includes(i))) {
lock(canvas, 1080 / 2400 );
}
}
} else {
if(isDeviceNavigator) {
if(mobileStrings.some(i => lockCanvasText.includes(i))) {
lock(canvas, 1080 / 2400 );
}
} else {
if(desktopStrings.some(i => lockCanvasText.includes(i))) {
lock(canvas, 1080 / 2400 );
}
}
}
if(window.innerWidth < window.innerHeight) {
isPortrait = true;
lock(loading, 9/16);
spinner.style.width = "16%"; spinner.style.height = "9%";
if(loading_bar_style == 0) {
// По умолчанию
setLoading("44%", "50%", "30%", "30%", "55%", "50%", "70%", "2%", "#FFF", "#00dc15", "0px 0px 0px 7px rgba(34, 60, 80, 0.2)", "0", "8px 8px 8px 8px", "8px 8px 8px 8px", "linear-gradient(45deg, rgba(0, 0, 0, 0.25) 25%, transparent 25%, transparent 50%, rgba(0, 0, 0, 0.25) 50%, rgba(0, 0, 0, 0.25) 75%, transparent 75%, transparent)", "15px 15px");
} else if(loading_bar_style == 1) {
// Минимализм со свечением
setLoading("44%", "50%", "30%", "30%", "55%", "50%", "70%", "2%", "rgba(255, 255, 255, 0.1)", "#FFF", "0", "0 0 10px rgba(255, 255, 255, 0.5)", "0", "0", "0", "0");
} else if(loading_bar_style == 2) {
// Нет слов
setLoading("44%", "50%", "30%", "30%", "55%", "50%", "70%", "2%", "0", "white", "0px 0px 0px 4px rgba(34, 60, 80, 0.2)", "0", "8px 8px 8px 8px", "8px 8px 8px 8px", "0", "0");
} else if(loading_bar_style == 3) {
// Без округлений
setLoading("44%", "50%", "30%", "30%", "55%", "50%", "70%", "1%", "#1c2329", "#ffffff", "0", "0", "0", "0", "0", "0");
} else if(loading_bar_style == 4) {
// Округленный и не слишком длинный
setLoading("44%", "50%", "30%", "30%", "55%", "50%", "50%", "2.7%", "#1c2329", "#ffffff", "0", "0", "12px 12px 12px 12px", "12px 12px 12px 12px", "0", "0");
}
} else {
isPortrait = false;
lock(loading, 16/9);
spinner.style.width = "7.9%"; spinner.style.height = "14%";
if(loading_bar_style == 0) {
// По умолчанию
setLoading("40%", "50%", "30%", "30%", "59%", "50%", "70%", "3%", "#FFF", "#00dc15", "0px 0px 0px 7px rgba(34, 60, 80, 0.2)", "0", "12px 12px 12px 12px", "12px 12px 12px 12px", "linear-gradient(45deg, rgba(0, 0, 0, 0.25) 25%, transparent 25%, transparent 50%, rgba(0, 0, 0, 0.25) 50%, rgba(0, 0, 0, 0.25) 75%, transparent 75%, transparent)", "15px 15px");
} else if(loading_bar_style == 1) {
// Минимализм со свечением
setLoading("40%", "50%", "30%", "30%", "59%", "50%", "70%", "3%", "rgba(255, 255, 255, 0.1)", "#FFF", "0", "0 0 10px rgba(255, 255, 255, 0.5)", "0", "0", "0", "0");
} else if(loading_bar_style == 2) {
// Нет слов
setLoading("40%", "50%", "30%", "30%", "59%", "50%", "70%", "3%", "0", "white", "0px 0px 0px 4px rgba(34, 60, 80, 0.2)", "0", "12px 12px 12px 12px", "12px 12px 12px 12px", "0", "0");
} else if(loading_bar_style == 3) {
// Без округлений
setLoading("40%", "50%", "30%", "30%", "59%", "50%", "70%", "2%", "#1c2329", "#ffffff", "0", "0", "0", "0", "0", "0");
} else if(loading_bar_style == 4) {
// Округленный и не слишком длинный
setLoading("40%", "50%", "30%", "30%", "59%", "50%", "30%", "4.4%", "#1c2329", "#ffffff", "0", "0", "16px 16px 16px 16px", "16px 16px 16px 16px", "0", "0");
}
}
}
Update();
window.addEventListener("resize", (event) => {
Update();
});
const buildUrl = "Build";
const loaderUrl = buildUrl + "/Z3.loader.js";
const config = {
dataUrl: buildUrl + "/Z3.data.unityweb",
frameworkUrl: buildUrl + "/Z3.framework.js.unityweb",
codeUrl: buildUrl + "/Z3.wasm.unityweb",
streamingAssetsUrl: "StreamingAssets",
companyName: "DefaultCompany",
productName: "Zombie defense 3d",
productVersion: "1"
};
// Возвращаем фокус, если кликнули по экрану
function FocusGame() {
window.focus();
canvas.focus();
}
window.addEventListener('pointerdown', () => {
FocusGame();
});
window.addEventListener('touchstart', () => {
FocusGame();
});
let StartUnityInstance;
let myGameInstance = null;
let ysdk = null;
let player = null;
let leaderboard;
let payments = null;
let initGame = false;
let nowFullAdOpen = false;
const script = document.createElement("script");
script.src = loaderUrl;
script.onload = () => {
StartUnityInstance = function () {
createUnityInstance(canvas, config, (progress) => {
spinner.style.display = "none";
loading_bar_fill.style.width = `${111.2 * progress}%`;
Update();
}).then((unityInstance) => {
myGameInstance = unityInstance;
ATinstance = unityInstance;
loading_bg.style.display = "none";
Update();
// Настраиваем тени
var boxShadowText = 'medium'.replace(/shadow|;|:|-|box|webkit|moz|""/gi, '').toLowerCase();
var shadowLowTypes = ["low", "small", "first", "one", "перв"];
var shadowMediumTypes = ["medium", "second", "two", "средний", "середина", "втор"];
var shadowHighTypes = ["high", "third", "three", "последний", "трет"];
if(shadowLowTypes.some(i => boxShadowText.includes(i))) {
canvas.style.boxShadow = "0px 0px 10px 4px rgba(34, 60, 80, 0.6)";
} else if(shadowMediumTypes.some(i => boxShadowText.includes(i))) {
canvas.style.boxShadow = "0px 0px 20px 6px rgba(34, 60, 80, 0.7)";
} else if(shadowHighTypes.some(i => boxShadowText.includes(i))) {
canvas.style.boxShadow = "0px 0px 30px 8px rgba(34, 60, 80, 0.8)";
} else {
canvas.style.boxShadow = boxShadowText;
}
}).catch((message) => {
console.error(message);
});
};
if (LocalHost()) // Delete when setting up: Load Game Run
StartUnityInstance_IfUnloaded();
};
function StartUnityInstance_IfUnloaded() {
if (spinner.style.display !== "none")
StartUnityInstance();
}
function LocalHost() {
var host = window.location.hostname;
if(host == "localhost" || host == "127.0.0.1")
return true;
else return false;
}
setTimeout(StartUnityInstance_IfUnloaded, 5000);
InitYSDK();
async function InitYSDK() {
try {
if (LocalHost()) return;
console.log('Init Yandex SDK');
ysdk = await YaGames.init();
InitPayments();
FullAdShow(); // First ad true
// Additional init modules
} catch (e) {
console.error('CRASH Initialization SDK: ', e);
}
StartUnityInstance_IfUnloaded();
}
function InitGame() {
console.log('Init Game Success');
initGame = true;
if(nowFullAdOpen == true && myGameInstance != null) {
myGameInstance.SendMessage('YandexGame', 'OpenFullAd');
}
}
function FullAdShow() {
try {
if (nowFullAdOpen !== true && ysdk !== null) {
ysdk.adv.showFullscreenAdv(
{
callbacks: {
onOpen: () => {
console.log('Open Ad Interstitial');
nowFullAdOpen = true;
if (initGame === true) {
myGameInstance.SendMessage('YandexGame', 'OpenFullAd');
}
},
onClose: (wasShown) => {
nowFullAdOpen = false;
if (initGame === true) {
if (wasShown) {
myGameInstance.SendMessage('YandexGame', 'CloseFullAd', 'true');
}
else {
myGameInstance.SendMessage('YandexGame', 'CloseFullAd', 'false');
}
}
FocusGame();
},
onError: (error) => {
console.error('Error Ad Interstitial', error);
myGameInstance.SendMessage('YandexGame', 'ErrorFullAd');
FocusGame();
}
}
});
}
} catch (e) {
console.error('CRASH FullAd Show: ', e.message);
}
}
function RewardedShow(id) {
try {
ysdk.adv.showRewardedVideo(
{
callbacks:
{
onOpen: () => {
console.log('Opened Video Ad. Id: ' + id);
myGameInstance.SendMessage('YandexGame', 'OpenVideo');
},
onClose: () => {
console.log('Closed Video Ad. Id: ' + id);
myGameInstance.SendMessage('YandexGame', 'CloseVideo');
FocusGame();
},
onRewarded: () => {
console.log('Reward Video Ad. Id: ' + id);
myGameInstance.SendMessage('YandexGame', 'RewardVideo', id);
},
onError: (e) => {
console.error('Error Video Ad. Id: ' + id, e);
myGameInstance.SendMessage('YandexGame', 'ErrorVideo');
}
}
});
} catch (err) {
console.error('CRASH Rewarded Video Ad Show: ', err.message);
}
}
function StickyAdActivity(show) {
try {
ysdk.adv.getBannerAdvStatus().then(({ stickyAdvIsShowing, reason }) => {
if (stickyAdvIsShowing) {
if (!show) {
ysdk.adv.hideBannerAdv();
}
}
else if (reason) {
console.log('Sticky ad are not shown. Reason:', reason);
}
else if (show) {
ysdk.adv.showBannerAdv();
}
})
} catch (e) {
console.error('CRASH Sticky Activity: ', e.message);
}
}
function InitPayments() {
try {
ysdk.getPayments().then(_payments => {
console.log('Purchases are available');
payments = _payments;
return true;
}).catch(e => {
console.log('Purchases are not available', e.message);
})
} catch (e) {
console.error('CRASH Init Payments: ', e.message);
}
}
function BuyPayments(id) {
try {
if (payments != null) {
payments.purchase(id).then(() => {
console.log('Purchase Success');
ConsumePurchase(id);
FocusGame();
}).catch(e => {
console.error('Purchase Failed', e.message);
myGameInstance.SendMessage('YandexGame', 'OnPurchaseFailed', id);
FocusGame();
})
} else {
console.log('Payments == null');
}
} catch (e) {
console.error('CRASH Buy Payments: ', e.message);
FocusGame();
}
}
let callCount_GetPayments = 0;
function GetPayments() {
try {
if (payments != null) {
payments.getCatalog()
.then(products => {
let productID = [];
let title = [];
let description = [];
let imageURI = [];
let priceValue = [];
let consumed = [];
payments.getPurchases().then(purchases => {
for (let i = 0; i < products.length; i++) {
productID[i] = products[i].id;
title[i] = products[i].title;
description[i] = products[i].description;
imageURI[i] = products[i].imageURI;
priceValue[i] = products[i].priceValue;
consumed[i] = true;
for (i2 = 0; i2 < purchases.length; i2++) {
if (purchases[i2].productID === productID[i]) {
consumed[i] = false;
break;
}
}
}
let jsonPayments = {
"id": productID,
"title": title,
"description": description,
"imageURI": imageURI,
"priceValue": priceValue,
"consumed": consumed
};
myGameInstance.SendMessage('YandexGame', 'PaymentsEntries', JSON.stringify(jsonPayments));
});
});
}
else if (callCount_GetPayments < 2) {
getPayments().
then(_payments => {
payments = _payments;
GetPayments();
});
}
} catch (e) {
console.error('CRASH Get Payments: ', e.message);
}
}
function ConsumePurchase(id) {
try {
if (payments != null) {
payments.getPurchases().then(purchases => {
for (i = 0; i < purchases.length; i++) {
if (purchases[i].productID === id) {
payments.consumePurchase(purchases[i].purchaseToken);
myGameInstance.SendMessage('YandexGame', 'OnPurchaseSuccess', id);
}
}
});
}
else console.log('Consume purchase: payments null');
} catch (e) {
console.error('CRASH Consume Purchase: ', e.message);
}
}
function ConsumePurchases() {
try {
if (payments != null) {
payments.getPurchases().then(purchases => {
console.log('Unprocessed purchases: ', purchases.length);
for (i = 0; i < purchases.length; i++) {
payments.consumePurchase(purchases[i].purchaseToken);
myGameInstance.SendMessage('YandexGame', 'OnPurchaseSuccess', purchases[i].productID);
}
});
}
else console.log('Consume purchases: payments null');
} catch (e) {
console.error('CRASH Consume purchases: ', e.message);
}
}
function InitLeaderboard() {
try {
ysdk.getLeaderboards().then(_lb => {
leaderboard = _lb
myGameInstance.SendMessage('YandexGame', 'InitializedLB');
});
} catch (e) {
console.error('CRASH Init Leaderboard: ', e.message);
}
}
function SetLeaderboardScores(_name, score) {
try {
ysdk.getLeaderboards()
.then(leaderboard => {
leaderboard.setLeaderboardScore(_name, score);
});
} catch (e) {
console.error('CRASH Set Leader board Scores: ', e.message);
}
}
function GetLeaderboardScores(nameLB, maxPlayers, quantityTop, quantityAround, photoSize, auth) {
try {
var jsonEntries = {
technoName: '',
isDefault: false,
isInvertSortOrder: false,
decimalOffset: 0,
type: '' // , title: ''
};
ysdk.getLeaderboards()
.then(leaderboard => leaderboard.getLeaderboardDescription(nameLB))
.then(res => {
jsonEntries.technoName = nameLB;
jsonEntries.isDefault = res.default;
jsonEntries.isInvertSortOrder = res.description.invert_sort_order;
jsonEntries.decimalOffset = res.description.score_format.options.decimal_offset;
jsonEntries.type = res.description.type; // Не определяется на момент 18.07.23
//jsonEntries.title = res.title; // Реализуйте по предпочтениям
return leaderboard.getLeaderboardEntries(nameLB, {
quantityTop: quantityTop,
includeUser: auth,
quantityAround: quantityAround
});
})
.then(res => {
let jsonPlayers = EntriesLB(res, maxPlayers, photoSize);
let combinedJson = { ...jsonEntries, ...jsonPlayers };
myGameInstance.SendMessage('YandexGame', 'LeaderboardEntries', JSON.stringify(combinedJson));
})
.catch(error => {
console.error(error);
});
}
catch (e) {
console.error('CRASH Get Leaderboard: ', e.message);
}
}
function EntriesLB(res, maxPlayers, photoSize) {
let LeaderboardEntriesText = '';
let playersCount;
if (res.entries.length < maxPlayers) {
playersCount = res.entries.length;
} else {
playersCount = maxPlayers;
}
let ranks = new Array(playersCount);
let photos = new Array(playersCount);
let mames = new Array(playersCount);
let scores = new Array(playersCount);
let uniqueIDs = new Array(playersCount);
for (i = 0; i < playersCount; i++) {
ranks[i] = res.entries[i].rank;
scores[i] = res.entries[i].score;
uniqueIDs[i] = res.entries[i].player.uniqueID;
if (photoSize === 'nonePhoto' || res.entries[i].player.scopePermissions.avatar !== "allow") {
photos[i] = 'nonePhoto';
} else {
photos[i] = res.entries[i].player.getAvatarSrc(photoSize);
}
if (res.entries[i].player.scopePermissions.public_name !== "allow") {
mames[i] = "anonymous";
} else {
mames[i] = res.entries[i].player.publicName;
}
LeaderboardEntriesText += ranks[i] + '. ' + mames[i] + ": " + scores[i] + '\n';
}
if (playersCount === 0) {
LeaderboardEntriesText = 'no data';
}
let jsonPlayers = {
"entries": LeaderboardEntriesText,
"ranks": ranks,
"photos": photos,
"names": mames,
"scores": scores,
"uniqueIDs": uniqueIDs
};
return jsonPlayers;
}
function Review() {
try {
ysdk.feedback.canReview()
.then(({ value, reason }) => {
if (value) {
ysdk.feedback.requestReview().then(({ feedbackSent }) => {
console.log('feedbackSent ', feedbackSent);
if (feedbackSent) {
myGameInstance.SendMessage('YandexGame', 'ReviewSent', 'true');
console.log('Review left')
}
else {
myGameInstance.SendMessage('YandexGame', 'ReviewSent', 'false');
console.log('Review not left', reason)
}
FocusGame();
})
}
else {
console.log('Review can show = false', reason);
FocusGame();
}
})
} catch (e) {
console.error('CRASH Review: ', e.message);
FocusGame();
}
}
function PromptShow() {
try {
ysdk.shortcut.showPrompt()
.then(result => {
console.log('Shortcut created?:', result);
if (result.outcome === 'accepted') {
console.log('Prompt Success');
myGameInstance.SendMessage('YandexGame', 'OnPromptSuccess');
}
else {
myGameInstance.SendMessage('YandexGame', 'OnPromptFail');
}
FocusGame();
});
} catch (e) {
console.error('CRASH Prompt Show: ', e.message);
FocusGame();
}
}
function PaintRBT(rbt) {
try {
document.getElementById(rbt).style.background = '#ff0000';
} catch (e) {
console.error('CRASH Paint RBT: ', e.message);
}
}
function StaticRBTDeactivate() {
}
// Additional script modules:
document.body.appendChild(script);
</script>
</body>
</html>