-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgame.js
More file actions
1423 lines (1205 loc) · 41.5 KB
/
Copy pathgame.js
File metadata and controls
1423 lines (1205 loc) · 41.5 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
/* game.js — traversable gaps + rare "springs" */
// Fixed game dimensions for stable mechanics
const W = 375;
const H = 667;
const PLW=68,PLH=14;
const JUMP=-12, GRAV=0.40;
const MAX_VGAP = Math.floor((JUMP*JUMP)/(2*GRAV)) - 10; // upper gap
const HDIST=180, MIN_SEP=30; // decrease horizontal spread, increase minimum distance
const DIFF=60; // decrease difficulty progression speed to 60 points
const BASE={gapMin:60, gapMax:110, maxPl:15}; // decrease minimum vertical distance
const $=id=>document.getElementById(id),
g=$('game'),p=$('player'),ui=$('ui'),ov=$('overlay'),
bgm=$('bgm'),jmp=$('jump'),
soundToggle = $('sound-toggle'),
leaderboardBtn = $('leaderboardBtn'),
leaderboardModal = $('leaderboard-modal'),
closeLeaderboardBtn = $('close-leaderboard'),
transactionModal = $('transaction-modal'),
transactionTitle = $('transaction-title'),
transactionMessage = $('transaction-message'),
transactionHash = $('transaction-hash'),
transactionClose = $('transaction-close'),
success = $('success'),
fall = $('fall');
// Create element for spring sound using built-in sound
const springSound = new Audio();
springSound.id = 'spring-sound';
springSound.volume = 0.8;
springSound.src = 'spring.mp3';
// Mobile device detection
const isMobile = /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);
console.log("Device is mobile:", isMobile); // debug
// Check sound file availability
let soundsAvailable = true;
let buttonSoundsAvailable = true;
// Disable complex sound loading via Web Audio API
let jumpSoundInitialized = true;
// Preload sounds for mobile devices
const preloadedSounds = {};
// Function to preload sounds
function preloadSound(id, src) {
try {
const audio = new Audio();
audio.src = src;
audio.preload = 'auto';
// Add to cache
preloadedSounds[id] = audio;
console.log(`Preloaded sound: ${id}`);
// On iOS, preliminary playback is needed
if (isMobile) {
// Try to play and immediately stop for initialization
const playPromise = audio.play();
if (playPromise !== undefined) {
playPromise.then(() => {
audio.pause();
audio.currentTime = 0;
console.log(`Sound ${id} successfully initialized`);
}).catch(e => {
console.log(`Error initializing sound ${id}:`, e);
});
}
}
return audio;
} catch(e) {
console.log(`Error preloading sound ${id}:`, e);
return null;
}
}
// Preload sounds
preloadSound('jump', 'jump.mp3');
preloadSound('spring', 'spring.mp3');
preloadSound('fall', 'fall.mp3');
preloadSound('click', 'click.mp3');
// Function to create and play a simple sound
function playSimpleSound(source, volume = 0.8) {
if (!soundEnabled) return;
try {
// Create a new audio element for each playback
const audio = new Audio();
audio.volume = soundSettings.master * volume;
audio.src = source;
// Try to play the sound
const playPromise = audio.play();
if (playPromise !== undefined) {
playPromise.catch(e => {
console.log('Error playing sound:', e);
});
}
} catch (e) {
console.log('Error creating sound:', e);
}
}
// Create element for button click sound
const clickSound = new Audio();
clickSound.id = 'click-sound';
clickSound.preload = 'auto';
try {
clickSound.src = 'click.mp3';
} catch(e) {
buttonSoundsAvailable = false;
}
document.body.appendChild(clickSound);
// Function to play click sound
function playClickSound() {
if (!soundEnabled) return;
try {
// Use preloaded sound if available
if (preloadedSounds['click']) {
const cachedSound = preloadedSounds['click'];
cachedSound.volume = soundSettings.master * 0.5; // Reduced volume for click
cachedSound.currentTime = 0;
// Play
cachedSound.play().catch(e => {
console.error('Error playing preloaded click sound:', e);
// Fallback option
fallbackPlaySound('click.mp3', soundSettings.master * 0.5);
});
} else {
// Fallback option
fallbackPlaySound('click.mp3', soundSettings.master * 0.5);
}
} catch(e) {
console.error('Error playing click sound:', e);
}
}
// Add click sound to all buttons
function addClickSoundToButton(button) {
if (button) {
const originalOnClick = button.onclick;
button.onclick = function(e) {
playClickSound();
if (originalOnClick) originalOnClick.call(this, e);
};
}
}
// Sound state flag, sound is enabled by default
let soundEnabled = true;
let px,py,vy,tilt=0,keyL=0,keyR=0,score=0,run=0,lastPlat,plats=[];
let isTouching = false; // Flag for tracking touch
let touchX = 0; // Touch position on X
/* preview animation */
let previewDoodle = null;
let previewVy = JUMP/1.5;
let previewPy = 0;
let previewAnimId = null;
let previewBaseY = 0; // Base Y-coordinate for animation
let previewRotation = 0; // Character rotation angle
let previewJumpTimer = 0; // Timer for controlling jump sounds
// initialize preview when page loads
window.addEventListener('DOMContentLoaded', () => {
previewDoodle = $('preview-doodle');
if (previewDoodle) {
// Save initial position for reference
const computedStyle = window.getComputedStyle(previewDoodle);
previewBaseY = parseInt(computedStyle.bottom, 10) || 120;
// Start animation in preview
previewAnimId = requestAnimationFrame(previewLoop);
}
});
// Preview jump animation
function previewLoop() {
if (!previewDoodle) return;
// Update vertical velocity and position
previewVy += GRAV/1.5;
previewPy += previewVy;
// Update rotation (more when flying up, less when falling)
previewRotation += previewVy < 0 ? 2 : 0.5;
if (previewRotation > 360) previewRotation -= 360;
// Scaling effect (larger at the top of jump)
const jumpHeight = -previewVy * 5; // Relative jump height
const scale = 1 + Math.max(0, -previewVy / 20); // Scale increases when moving up
// Update shadow intensity depending on height
const shadowOpacity = Math.max(0.1, Math.min(0.5, 0.5 - (-previewVy / 20)));
// Update position style with rotation and scaling
previewDoodle.style.transform = `translateY(${-previewPy}px) rotate(${previewRotation}deg) scale(${scale})`;
previewDoodle.style.filter = `drop-shadow(0 ${-previewVy * 0.5}px ${Math.abs(previewVy)}px rgba(0,0,0,${shadowOpacity}))`;
// Check collision with platform
if (previewVy > 0 && previewPy > 20) { // Give a small buffer for "spring" effect
// When character drops below platform, make it jump again
previewVy = JUMP/1.5;
previewJumpTimer++;
// Play jump sound, only if sound is enabled
if (soundEnabled && previewJumpTimer % 3 === 0) {
const jmp = preloadedSounds['jump'];
jmp.volume = soundSettings.master * soundSettings.jump; // Apply volume settings
jmp.currentTime = 0;
jmp.play().catch(e => {
console.error('Error playing jump sound in preview:', e);
});
}
}
// Continue animation
previewAnimId = requestAnimationFrame(previewLoop);
}
/* остановка анимации предпросмотра при запуске игры */
function stopPreviewAnimation() {
if (previewAnimId) {
cancelAnimationFrame(previewAnimId);
previewAnimId = null;
}
}
/* input */
addEventListener('deviceorientation',e=>tilt=e.gamma/3);
onkeydown=e=>{if(e.key==='ArrowLeft') keyL=1; if(e.key==='ArrowRight')keyR=1};
onkeyup =e=>{if(e.key==='ArrowLeft') keyL=0; if(e.key==='ArrowRight')keyR=0};
/* Мобильное управление касанием экрана */
const handleTouch = (e) => {
e.preventDefault();
// Получаем позицию касания
const touch = e.touches[0];
// Получаем размеры игрового экрана и его позицию
const gameRect = g.getBoundingClientRect();
// Устанавливаем флаг касания
isTouching = true;
// Рассчитываем позицию в игровых координатах
// Учитываем смещение игрового поля и масштабирование
touchX = ((touch.clientX - gameRect.left) / gameRect.width) * W;
// Центрируем персонажа по пальцу (учитываем ширину персонажа 32px)
touchX = touchX - 16;
};
const handleTouchEnd = () => {
isTouching = false;
keyL = 0;
keyR = 0;
};
document.addEventListener('touchstart', handleTouch);
document.addEventListener('touchmove', handleTouch);
document.addEventListener('touchend', handleTouchEnd);
document.addEventListener('touchcancel', handleTouchEnd);
/* utils */
const rnd=(a,b)=>a+Math.random()*(b-a);
const clamp=(v,a,b)=>v<a?a:v>b?b:v;
const place =pl=>pl.d.style.transform=`translate(${pl.x}px,${pl.y}px)`;
const placeP=()=>p.style.transform =`translate(${px}px,${py}px)`;
/* === blockchain config === */
const CONTRACT="0x20e860e9a1b42d3e949207f02f29844e0870ad3c";
const ABI=[
{
"inputs": [
{
"internalType": "uint256",
"name": "_score",
"type": "uint256"
}
],
"name": "saveScore",
"outputs": [],
"stateMutability": "payable",
"type": "function"
},
{
"inputs": [],
"name": "withdraw",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [],
"name": "entryFee",
"outputs": [
{
"internalType": "uint256",
"name": "",
"type": "uint256"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "getFullLeaderboard",
"outputs": [
{
"components": [
{
"internalType": "address",
"name": "wallet",
"type": "address"
},
{
"internalType": "uint256",
"name": "score",
"type": "uint256"
}
],
"internalType": "struct Leaderboard.Player[]",
"name": "",
"type": "tuple[]"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [
{
"internalType": "uint256",
"name": "_topN",
"type": "uint256"
}
],
"name": "getTopPlayers",
"outputs": [
{
"components": [
{
"internalType": "address",
"name": "wallet",
"type": "address"
},
{
"internalType": "uint256",
"name": "score",
"type": "uint256"
}
],
"internalType": "struct Leaderboard.Player[]",
"name": "",
"type": "tuple[]"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [
{
"internalType": "uint256",
"name": "",
"type": "uint256"
}
],
"name": "leaderboard",
"outputs": [
{
"internalType": "address",
"name": "wallet",
"type": "address"
},
{
"internalType": "uint256",
"name": "score",
"type": "uint256"
}
],
"stateMutability": "view",
"type": "function"
}
];
// Определяем параметры сети Monad
const MONAD_CHAIN_ID = "0x279f"; // Chain ID from Zerion
const MONAD_RPC_URL = "https://testnet-rpc2.monad.xyz/52227f026fa8fac9e2014c58fbf5643369b3bfc6";
const MONAD_NAME = "Monad Testnet";
const MONAD_SYMBOL = "MON";
const MONAD_EXPLORER = "https://testnet.monadexplorer.com/";
// Функция для переключения на сеть Monad Testnet
async function switchToMonadNetwork() {
if (!window.ethereum) return false;
try {
// Try to switch to existing Monad network
await window.ethereum.request({
method: 'wallet_switchEthereumChain',
params: [{ chainId: MONAD_CHAIN_ID }],
});
return true;
} catch (switchError) {
// Code 4902 means network is not added to wallet
if (switchError.code === 4902) {
try {
// Add Monad network to wallet
await window.ethereum.request({
method: 'wallet_addEthereumChain',
params: [
{
chainId: MONAD_CHAIN_ID,
chainName: MONAD_NAME,
nativeCurrency: {
name: MONAD_NAME,
symbol: MONAD_SYMBOL,
decimals: 18
},
rpcUrls: [MONAD_RPC_URL],
blockExplorerUrls: [MONAD_EXPLORER]
},
],
});
// Try switching again
await window.ethereum.request({
method: 'wallet_switchEthereumChain',
params: [{ chainId: MONAD_CHAIN_ID }],
});
return true;
} catch (addError) {
console.error('Error adding Monad network to wallet:', addError);
return false;
}
} else {
console.error('Error switching to Monad network:', switchError);
return false;
}
}
}
// Функция для отображения стилизованного уведомления о транзакции
function showTransactionNotification(title, message, txHash = null) {
// Set title and message
transactionTitle.textContent = title || 'Transaction Complete';
transactionMessage.textContent = message || 'Your transaction was completed successfully.';
// If there's a transaction hash, show it and add link to block explorer
if (txHash) {
transactionHash.textContent = `Transaction: ${txHash}`;
transactionHash.dataset.url = `${MONAD_EXPLORER}/tx/${txHash}`;
transactionHash.style.display = 'block';
} else {
transactionHash.style.display = 'none';
}
// Add close handler
transactionClose.onclick = () => {
playClickSound();
transactionModal.style.display = 'none';
};
// Play success sound if enabled
if (soundEnabled && success) {
success.currentTime = 0;
success.volume = 0.7;
success.play().catch(e => console.log('Error playing success sound:', e));
}
// Show modal
transactionModal.style.display = 'flex';
}
async function saveScoreOnChain(score){
try {
console.log("Starting saveScoreOnChain function...");
// Check provider availability
if (!window.ethereum) {
console.error("No wallet provider found");
showTransactionNotification('Wallet Not Found', 'Please install MetaMask or open this game in Warpcast to save your score');
return;
}
// Explicitly request wallet connection
try {
await window.ethereum.request({ method: 'eth_requestAccounts' });
} catch (connectionError) {
console.error("Failed to connect wallet:", connectionError);
showTransactionNotification('Connection Failed', 'Could not connect to wallet. Please try again.');
return;
}
// Switch to Monad network
console.log("Switching to Monad network...");
const switched = await switchToMonadNetwork();
if (!switched) {
showTransactionNotification('Network Error', 'Please switch to Monad Testnet network to save your score');
return;
}
// Create provider and connect
const provider = new ethers.providers.Web3Provider(window.ethereum);
const signer = provider.getSigner();
// Get current user address
const address = await signer.getAddress();
console.log("Connected address:", address);
// Get current network
const network = await provider.getNetwork();
console.log("Current network:", network);
// Check if we're in the right network
if (network.chainId !== 10143) { // 0x279f = 10143 in decimal format
showTransactionNotification('Wrong Network', `Please switch to Monad Testnet (ChainID: 10143). Current: ${network.chainId}`);
return;
}
// Fixed recording cost (0.1 MON = 0.1 * 10^18 wei)
const entryFee = ethers.utils.parseEther("0.1");
console.log("Using fixed entry fee:", entryFee.toString());
// Create contract instance
const game = new ethers.Contract(CONTRACT, ABI, signer);
// Send transaction directly through method and parameters
console.log("Sending transaction to save score:", score);
const tx = await game.saveScore(score, {
value: entryFee,
gasLimit: 200000 // Set gas reserve
});
console.log("Transaction sent:", tx.hash);
// Wait for confirmation
console.log("Waiting for transaction confirmation...");
await tx.wait();
console.log("Transaction confirmed!");
// Show styled notification instead of alert
showTransactionNotification(
'Score Saved Successfully!',
`Your score of ${score} has been recorded on the blockchain.`,
tx.hash
);
} catch (e) {
console.error("Error saving score:", e);
// Check for specific errors
let errorTitle = 'Error';
let errorMessage = "Failed to save score. ";
if (e.code === 4001) {
errorTitle = 'Transaction Rejected';
errorMessage = "You rejected the transaction. Please try again.";
} else if (e.message && e.message.includes("insufficient funds")) {
errorTitle = 'Insufficient Funds';
errorMessage = "You need 0.1 MON to save your score.";
} else if (e.message) {
errorMessage += e.message;
}
showTransactionNotification(errorTitle, errorMessage);
}
}
/* dynamics of difficulty */
function diff(){
const lvl=Math.floor(score/DIFF);
return{
gapMin: BASE.gapMin+lvl*3, // slower gap growth
gapMax: Math.min(BASE.gapMax+lvl*5, MAX_VGAP),
maxPl : BASE.maxPl + Math.floor(lvl/2), // slower platform increase
movSpd: 1.2 + lvl*.15, // slower moving platforms
movCh : clamp(.25+lvl*.04,.25,.6), // reduced chance of moving platforms
fragCh: clamp(.15+lvl*.03,.15,.4) // reduced chance of fragile platforms
};
}
/* ---------- platform creation ---------- */
function addPlat(prevY,prevX){
const d=diff();
const y=prevY-rnd(d.gapMin,d.gapMax);
/* chaotic but achievable X */
let tryCnt=0,x;
// Generate diverse paths
const pathType = Math.random();
if (pathType < 0.3) {
// Create platform in random part of screen (30% of cases)
x = rnd(0, W-PLW);
}
else if (pathType < 0.6) {
// Create platform in opposite part from previous (30% of cases)
x = prevX < W/2 ?
rnd(W/2, W-PLW) : // If previous is left, new one right
rnd(0, W/2-PLW); // If previous is right, new one left
}
else {
// Standard logic with improved distribution (40% of cases)
while(true){
// Larger spread for more unpredictable platforms
x = clamp(prevX + rnd(-HDIST,HDIST), 0, W-PLW);
const dx = Math.abs(x-prevX);
// Check that platform is reachable
if(dx>=MIN_SEP && dx<=HDIST) break;
// If position can't be found, place on opposite side
if(++tryCnt>8){
x = (prevX<W/2)? W-PLW-MIN_SEP : MIN_SEP;
break;
}
}
}
/* type */
const r=Math.random();
let type='static';
if(r<d.fragCh) type='frag';
else if(r<d.fragCh+d.movCh) type='mov';
// Springs with 6.3% probability (reduced by 30% from 9%)
if(Math.random() < 0.063) type='spring';
/* DOM */
const el=document.createElement('div');
el.className=`plat ${type}`; g.appendChild(el);
// Increase movement range for moving platforms
const seg=rnd(100,180),
leftB=clamp(x-seg/2,0,W-PLW),
rightB=leftB+seg,
vx=type==='mov'?(Math.random()<.5?-d.movSpd:d.movSpd):0;
plats.push({x,y,d:el,type,vx,leftB,rightB,hidden:0,scored:false});
place(plats.at(-1));
// Chance to create additional platform at same level (for forks)
if(Math.random() < 0.2 && plats.length < d.maxPl) {
const offsetX = x < W/2 ? rnd(W/2, W-PLW) : rnd(0, W/2-PLW);
const extraEl = document.createElement('div');
let extraType = 'static';
if(Math.random() < 0.2) extraType = 'spring';
else if(Math.random() < 0.4) extraType = 'mov';
extraEl.className = `plat ${extraType}`;
g.appendChild(extraEl);
const extraVx = extraType==='mov'?(Math.random()<.5?-d.movSpd:d.movSpd):0;
const extraSeg = rnd(80,120);
const extraLeftB = clamp(offsetX-extraSeg/2,0,W-PLW);
const extraRightB = extraLeftB+extraSeg;
plats.push({x:offsetX, y:y, d:extraEl, type:extraType, vx:extraVx,
leftB:extraLeftB, rightB:extraRightB, hidden:0, scored:false});
place(plats.at(-1));
}
}
/* ---------- reset ---------- */
function reset(){
plats.forEach(pl=>pl.d.remove()); plats=[];
let y=H-40,x=rnd(0,W-PLW);
for(let i=0;i<8;i++){ addPlat(y,x); ({y,x}={y:y-BASE.gapMin,x:plats.at(-1).x}); }
px=W/2-16; py=H-120; vy=JUMP;
/* starting platform */
const el=document.createElement('div');
el.className='plat static'; g.appendChild(el);
const start={x:px,y:py+60,d:el,type:'static',vx:0,leftB:px,rightB:px+PLW,hidden:0,scored:false};
plats.push(start); place(start);
score=0; ui.textContent='0'; lastPlat=start; placeP();
}
/* ---------- loop ---------- */
function loop(){
if(!run) return;
const d=diff();
/* movements */
plats.forEach(pl=>{
if(pl.vx){ pl.x+=pl.vx; if(pl.x<pl.leftB||pl.x>pl.rightB)pl.vx*=-1; place(pl); }
});
// If there's active touch, use finger position
if (isTouching) {
px = touchX;
} else {
// Otherwise use keyboard/accelerometer
px += keyL ? -4 : keyR ? 4 : tilt;
}
// Check for moving beyond screen boundaries
if(px < -32) px = W;
if(px > W) px = -32;
vy += GRAV;
py += vy;
/* landing - optimized collision check */
let didLand = false;
if(vy>0){
// Sort platforms by Y to check only the closest ones
const nearbyPlats = plats.filter(pl =>
py+32 >= pl.y-10 && py+32 <= pl.y+PLH+10 &&
px+32 > pl.x && px < pl.x+PLW
);
for(const pl of nearbyPlats){
if((pl.type!=='frag'||!pl.hidden) &&
py+32 > pl.y && py+32 < pl.y+PLH+4){
didLand = true;
// If this is a spring - add compression animation
if (pl.type === 'spring') {
pl.d.classList.add('active');
setTimeout(() => pl.d.classList.remove('active'), 300);
vy = JUMP*1.8; // Strong jump
// Play spring sound instead of regular jump
playJumpSound(true);
} else {
vy = JUMP; // Regular jump
// Play regular jump sound
playJumpSound(false);
}
// Award points only if platform hasn't been used for scoring yet
if(!pl.scored){
pl.scored = true; // Mark that this platform has already given points
ui.textContent = ++score;
}
lastPlat = pl; // Update last platform regardless of point awarding
if(pl.type==='frag'){
pl.hidden=1; pl.d.classList.add('hide');
setTimeout(()=>{pl.hidden=0;pl.d.classList.remove('hide');},2000);
}
break; // Break the loop as we've already landed
}
}
}
/* camera */
if(py < H*.4){ const dy=H*.4-py; py=H*.4; plats.forEach(pl=>{pl.y+=dy; place(pl);}); }
/* recreation */
plats.filter(pl=>pl.y>H).forEach(pl=>{pl.d.remove(); plats.splice(plats.indexOf(pl),1);});
while(plats.length<d.maxPl){
const top=plats.reduce((m,p)=>p.y<m.y?p:m);
addPlat(top.y, top.x);
}
/* death */
if(py>H){
run=0;
// Play fall sound
playFallSound();
ov.innerHTML=`
<h2>Score: ${score}</h2>
<button id="restart">Restart</button>
<button id="saveBtn">Save on-chain</button>
<button id="menuBtn">Menu</button>
`;
const restartBtn = $('restart');
const saveBtn = $('saveBtn');
const menuBtn = $('menuBtn');
// Add click sound to new buttons - immediate reaction
restartBtn.onclick = function() {
playClickSound();
start();
};
// Improved handler for save button - immediate reaction
saveBtn.onclick = function() {
playClickSound();
console.log("Save button clicked, score:", score);
saveScoreOnChain(score);
};
menuBtn.onclick = function() {
playClickSound();
showMainMenu();
};
ov.style.display = 'flex';
return;
}
placeP(); requestAnimationFrame(loop);
}
/* start */
function start(){
playClickSound();
stopPreviewAnimation(); // stop preview animation
ov.style.display='none';
// Воспроизводим фоновую музыку
playBackgroundMusic();
run=1;
reset();
requestAnimationFrame(loop);
}
$('startBtn').onclick=start;
/* Возврат в главное меню */
function showMainMenu() {
// Не останавливаем фоновую музыку при возврате в главное меню
// Музыка должна продолжать играть
// Обновляем оверлей с главным меню
ov.innerHTML = `
<img src="preview.png" class="preview" alt="preview">
<button id="startBtn">Start</button>
<button id="leaderboardBtn">Leaderboard</button>
<!-- Превью-анимация дудла (в правом нижнем углу) -->
<div id="preview-container">
<div class="preview-plat"></div>
<img id="preview-doodle" src="doodle.png" alt="">
</div>
`;
// Восстанавливаем обработчики для кнопок
const startBtn = $('startBtn');
const leaderboardBtn = $('leaderboardBtn');
startBtn.onclick = function() {
playClickSound();
start();
};
leaderboardBtn.addEventListener('click', () => {
playClickSound();
console.log("Leaderboard button clicked from main menu");
const modal = $('leaderboard-modal');
if (modal) {
console.log("Loading leaderboard data from main menu...");
loadLeaderboardData();
modal.style.display = 'flex';
} else {
console.error("Leaderboard modal not found");
}
});
// Сбрасываем счет
score = 0;
ui.textContent = '0';
// Удаляем все платформы
plats.forEach(pl => pl.d.remove());
plats = [];
// Показываем меню
ov.style.display = 'flex';
// Запускаем анимацию превью снова
previewDoodle = $('preview-doodle');
if (previewDoodle) {
const computedStyle = window.getComputedStyle(previewDoodle);
previewBaseY = parseInt(computedStyle.bottom, 10) || 150;
previewPy = 0;
previewVy = JUMP/1.5;
previewAnimId = requestAnimationFrame(previewLoop);
}
// Проверяем, играет ли фоновая музыка, если нет - запускаем
if (bgm && bgm.paused && soundEnabled && soundSettings.bgmEnabled) {
playBackgroundMusic();
}
}
// Функция для загрузки данных лидерборда
async function loadLeaderboardData() {
const scoresBody = $('scores-body');
if (!scoresBody) return;
scoresBody.innerHTML = '<tr><td colspan="2" style="text-align: center;">Loading scores...</td></tr>';
try {
// Create provider without wallet, just for reading
console.log("Creating provider for leaderboard");
const provider = new ethers.providers.JsonRpcProvider(MONAD_RPC_URL);
// Check network connection
try {
const network = await provider.getNetwork();
console.log("Connected to network:", network);
} catch (networkError) {
console.error("Network connection error:", networkError);
scoresBody.innerHTML = '<tr><td colspan="2" style="text-align: center;">Error connecting to network</td></tr>';
return;
}
// Explicitly specify contract address and ABI
console.log("Creating contract instance with address:", CONTRACT);
const contract = new ethers.Contract(CONTRACT, ABI, provider);
// Check function availability
if (!contract.getTopPlayers) {
console.error("getTopPlayers function not found in contract");
scoresBody.innerHTML = '<tr><td colspan="2" style="text-align: center;">Contract API mismatch</td></tr>';
return;
}
// Get top-10 players from leaderboard
console.log("Fetching top players");
const players = await contract.getTopPlayers(10);
console.log("Received players data:", players);
// If no data
if (players.length === 0) {
scoresBody.innerHTML = '<tr><td colspan="2" style="text-align: center;">No scores found</td></tr>';
return;
}
// Format and display data
scoresBody.innerHTML = players.map(player => {
// Check data validity
if (!player || !player.wallet) {
return '<tr><td colspan="2">Invalid player data</td></tr>';
}
// Shorten address
const shortAddress = `${player.wallet.substring(0, 6)}...${player.wallet.substring(38)}`;
return `<tr><td>${shortAddress}</td><td>${player.score}</td></tr>`;
}).join('');
} catch (error) {
console.error('Error loading leaderboard data:', error);
scoresBody.innerHTML = `<tr><td colspan="2" style="text-align: center;">Error: ${error.message || 'Unknown error'}</td></tr>`;
}
}
// Обновляем функцию воспроизведения фоновой музыки
function playBackgroundMusic() {
if (!soundEnabled || !soundSettings.bgmEnabled) return;
if (bgm) {
try {
bgm.volume = soundSettings.master * soundSettings.bgm;
// Check if music is already playing
if (bgm.paused) {
console.log('Starting background music...');
const playPromise = bgm.play();
if (playPromise !== undefined) {
playPromise.catch(e => {
console.log('Background music error:', e);
// If we got an error, try to start later on interaction
if (!window.bgmErrorHandled) {
window.bgmErrorHandled = true;
const startBgmOnInteraction = () => {
if (bgm.paused) {
bgm.play().catch(err => console.log('Repeated background music error:', err));
}
document.removeEventListener('click', startBgmOnInteraction);
document.removeEventListener('touchstart', startBgmOnInteraction);
};
document.addEventListener('click', startBgmOnInteraction);
document.addEventListener('touchstart', startBgmOnInteraction);
}
});