-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApp.js
More file actions
1902 lines (1752 loc) · 81.8 KB
/
App.js
File metadata and controls
1902 lines (1752 loc) · 81.8 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
import { Platform, useWindowDimensions, Linking } from 'react-native';
import {
Canvas,
useImage,
Image,
Group,
Text,
matchFont,
Circle,
rect,
rrect,
ColorMatrix,
Paint,
Skia,
} from '@shopify/react-native-skia';
import {
useSharedValue,
withTiming,
Easing,
withSequence,
withRepeat,
useFrameCallback,
useDerivedValue,
interpolate,
Extrapolation,
useAnimatedReaction,
runOnJS,
cancelAnimation,
} from 'react-native-reanimated';
import { useEffect, useState } from 'react';
import {
GestureHandlerRootView,
GestureDetector,
Gesture,
} from 'react-native-gesture-handler';
import * as Haptics from 'expo-haptics';
import * as ImagePicker from 'expo-image-picker';
import * as FileSystem from 'expo-file-system';
import AsyncStorage from '@react-native-async-storage/async-storage';
const GRAVITY = 1000;
const JUMP_FORCE = -500;
const pipeWidth = 104;
const pipeHeight = 640;
const App = () => {
const { width, height } = useWindowDimensions();
// Responsive scaling based on screen size (reference: 360x800)
const scaleWidth = width / 360;
const scaleHeight = height / 800;
const scale = Math.min(scaleWidth, scaleHeight); // Use minimum to maintain aspect ratio
// Scale pipe dimensions for responsive design
const scaledPipeWidth = pipeWidth * scaleWidth;
const scaledPipeHeight = pipeHeight * scaleHeight;
const [score, setScore] = useState(0);
const [highestScore, setHighestScore] = useState(0);
const [gameState, setGameState] = useState('waiting'); // 'waiting', 'playing', 'gameOver'
const [birdColor, setBirdColor] = useState('yellow'); // 'yellow', 'blue', 'red', 'manas', 'custom0', 'custom1', etc.
const [customImages, setCustomImages] = useState([]); // Array of custom image URIs
const [theme, setTheme] = useState('day'); // 'day', 'night', 'city'
const [currentPage, setCurrentPage] = useState('game'); // 'game', 'customize', 'devteam'
const [hasCustomization, setHasCustomization] = useState(false); // Track if user has saved customization
const [scrollY, setScrollY] = useState(0); // For scrolling the customize page
const bgDay = useImage(require('./assets/sprites/background-day.png'));
const bgNight = useImage(require('./assets/sprites/background-night.png'));
const bgCity = useImage(require('./assets/sprites/nightcity.jpg'));
// Get current background based on theme
const bg = theme === 'night' ? bgNight : theme === 'city' ? bgCity : bgDay;
const yellowBird = useImage(require('./assets/sprites/yellowbird-upflap.png'));
const blueBird = useImage(require('./assets/sprites/bluebird-upflap.png'));
const redBird = useImage(require('./assets/sprites/redbird-upflap.png'));
const manasBird = useImage(require('./assets/sprites/developers/manas.png'));
const pipeBottom = useImage(require('./assets/sprites/pipe-green.png'));
const pipeTop = useImage(require('./assets/sprites/pipe-green-top.png'));
const base = useImage(require('./assets/sprites/base.png'));
const messageImg = useImage(require('./assets/sprites/message.png'));
const gameOverImg = useImage(require('./assets/sprites/gameover.png'));
const restartGameBtn = useImage(require('./assets/sprites/restart_button.png'));
const addIcon = useImage(require('./assets/sprites/add_icon.png'));
const deleteIcon = useImage(require('./assets/sprites/wrong_icon.png'));
// Development team images
const devTeamBtn = useImage(require('./assets/sprites/development_team_button.png'));
const devTeamPt = useImage(require('./assets/sprites/development_team_pt.png'));
const harshaPt = useImage(require('./assets/sprites/developers/harsha.png'));
const manasPt = useImage(require('./assets/sprites/developers/manas.png'));
const mithunPt = useImage(require('./assets/sprites/developers/mithun.png'));
const narenPt = useImage(require('./assets/sprites/developers/naren.png'));
const nevilPt = useImage(require('./assets/sprites/developers/nevil.png'));
// Load custom bird images - using individual hooks to avoid conditional hook calls
const customBird0 = useImage(customImages[0]);
const customBird1 = useImage(customImages[1]);
const customBird2 = useImage(customImages[2]);
const customBird3 = useImage(customImages[3]);
const customBird4 = useImage(customImages[4]);
const customBird5 = useImage(customImages[5]);
const customBird6 = useImage(customImages[6]);
const customBird7 = useImage(customImages[7]);
const customBird8 = useImage(customImages[8]);
const customBird9 = useImage(customImages[9]);
// Create array of loaded images
const customBirdImages = [
customBird0, customBird1, customBird2, customBird3, customBird4,
customBird5, customBird6, customBird7, customBird8, customBird9
].slice(0, customImages.length);
// Debug: Log when custom images change
useEffect(() => {
console.log('Custom Images array:', customImages);
console.log('Number of custom birds:', customImages.length);
}, [customImages]);
const customizeBtn = useImage(require('./assets/sprites/customize_button.png'));
const saveBtn = useImage(require('./assets/sprites/save_button.png'));
const backBtn = useImage(require('./assets/sprites/back_button.png'));
const bestScoreImg = useImage(require('./assets/sprites/best_score.png'));
// Text images
const customizePt = useImage(require('./assets/sprites/customize_pt.png'));
const selectThemePt = useImage(require('./assets/sprites/select_theme_pt.png'));
const selectCharectorPt = useImage(require('./assets/sprites/select_charector_pt.png'));
const developmentTeamPt = useImage(require('./assets/sprites/development_team_pt.png'));
// Get current bird based on selection
const bird = birdColor.startsWith('custom')
? customBirdImages[parseInt(birdColor.replace('custom', ''))] || yellowBird
: birdColor === 'blue' ? blueBird :
birdColor === 'red' ? redBird :
yellowBird;
// Debug log
useEffect(() => {
console.log('Bird Color:', birdColor);
console.log('Manas Bird loaded:', !!manasBird);
console.log('Current bird:', !!bird);
}, [birdColor, manasBird, bird]);
const gameOver = useSharedValue(false);
const pipeX = useSharedValue(width);
const birdY = useSharedValue(height / 3);
const birdX = width / 4;
const birdYVelocity = useSharedValue(0);
const pipeOffset = useSharedValue(Math.random() * 400 * scaleHeight - 200 * scaleHeight); // Random initial gap position (scaled)
const topPipeY = useDerivedValue(() => pipeOffset.value - 350 * scaleHeight);
const bottomPipeY = useDerivedValue(() => height - 300 * scaleHeight + pipeOffset.value);
const pipesSpeed = useDerivedValue(() => {
return interpolate(score, [0, 20], [1, 2]);
});
const obstacles = useDerivedValue(() => [
// bottom pipe
{
x: pipeX.value,
y: bottomPipeY.value,
h: scaledPipeHeight,
w: scaledPipeWidth,
},
// top pipe
{
x: pipeX.value,
y: topPipeY.value,
h: scaledPipeHeight,
w: scaledPipeWidth,
},
]);
// No audio setup needed - using Web Audio API directly
// No image processing - use original image directly
// Load saved preferences on app start
useEffect(() => {
const loadPreferences = async () => {
try {
const savedTheme = await AsyncStorage.getItem('theme');
const savedBirdColor = await AsyncStorage.getItem('birdColor');
const savedCustomImages = await AsyncStorage.getItem('customImages');
const savedHighestScore = await AsyncStorage.getItem('highestScore');
if (savedTheme) setTheme(savedTheme);
if (savedBirdColor) setBirdColor(savedBirdColor);
if (savedHighestScore) setHighestScore(parseInt(savedHighestScore));
if (savedCustomImages) {
const parsedImages = JSON.parse(savedCustomImages);
// Convert from old object format to array if needed
if (Array.isArray(parsedImages)) {
setCustomImages(parsedImages);
} else {
// Migrate old format
const imageArray = [];
if (parsedImages.custom1) imageArray.push(parsedImages.custom1);
if (parsedImages.custom2) imageArray.push(parsedImages.custom2);
if (parsedImages.custom3) imageArray.push(parsedImages.custom3);
setCustomImages(imageArray);
}
}
// Check if user has any saved customization
if (savedTheme || savedBirdColor || savedCustomImages) {
setHasCustomization(true);
}
} catch (error) {
console.log('Error loading preferences:', error);
}
};
loadPreferences();
}, []);
// Save preferences
const savePreferences = async () => {
try {
await AsyncStorage.setItem('theme', theme);
await AsyncStorage.setItem('birdColor', birdColor);
await AsyncStorage.setItem('customImages', JSON.stringify(customImages));
setHasCustomization(true);
playJumpSound();
setCurrentPage('game'); // Return to game after saving
} catch (error) {
console.log('Error saving preferences:', error);
}
};
// Pick custom image - adds to array and auto-selects
const pickImage = async () => {
try {
// Request permission
const { status } = await ImagePicker.requestMediaLibraryPermissionsAsync();
if (status !== 'granted') {
console.log('Permission denied');
return;
}
const result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.Images,
allowsEditing: true,
aspect: [1, 1],
quality: 1,
});
console.log('Image picker result:', result);
if (!result.canceled && result.assets && result.assets[0]) {
const sourceUri = result.assets[0].uri;
const newIndex = customImages.length;
console.log('Selected image URI:', sourceUri, 'adding as custom' + newIndex);
// Add new image to array
setCustomImages(prev => [...prev, sourceUri]);
setBirdColor(`custom${newIndex}`);
playJumpSound();
console.log('Custom image added successfully at index', newIndex);
}
} catch (error) {
console.log('Error picking image:', error);
console.error('Full error:', error);
}
};
// Delete custom bird
const deleteCustomBird = async (index) => {
try {
// Remove the image from array
const newImages = customImages.filter((_, i) => i !== index);
setCustomImages(newImages);
// If the deleted bird was selected, switch to yellow bird
if (birdColor === `custom${index}`) {
setBirdColor('yellow');
} else if (birdColor.startsWith('custom')) {
// Update bird color index if it's after the deleted one
const currentIndex = parseInt(birdColor.replace('custom', ''));
if (currentIndex > index) {
setBirdColor(`custom${currentIndex - 1}`);
}
}
// Save to AsyncStorage
await AsyncStorage.setItem('customImages', JSON.stringify(newImages));
playJumpSound();
} catch (error) {
console.log('Error deleting custom bird:', error);
}
};
// Open Instagram profile
const openInstagram = async (username) => {
try {
const instagramUrl = `https://www.instagram.com/${username}/`;
const supported = await Linking.canOpenURL(instagramUrl);
if (supported) {
await Linking.openURL(instagramUrl);
} else {
console.log("Can't open Instagram URL");
}
} catch (error) {
console.log('Error opening Instagram:', error);
}
};
// Sound effect functions using Web Audio API
const playJumpSound = () => {
try {
const audioContext = new (window.AudioContext || window.webkitAudioContext)();
// Wing flap sound - quick swoosh
const oscillator1 = audioContext.createOscillator();
const gainNode1 = audioContext.createGain();
oscillator1.connect(gainNode1);
gainNode1.connect(audioContext.destination);
oscillator1.frequency.value = 200;
oscillator1.type = 'sine';
gainNode1.gain.setValueAtTime(0.15, audioContext.currentTime);
gainNode1.gain.exponentialRampToValueAtTime(0.01, audioContext.currentTime + 0.05);
oscillator1.start(audioContext.currentTime);
oscillator1.stop(audioContext.currentTime + 0.05);
// Jump beep - chirp sound
const oscillator2 = audioContext.createOscillator();
const gainNode2 = audioContext.createGain();
oscillator2.connect(gainNode2);
gainNode2.connect(audioContext.destination);
oscillator2.frequency.value = 600;
oscillator2.type = 'square';
gainNode2.gain.setValueAtTime(0.2, audioContext.currentTime);
gainNode2.gain.exponentialRampToValueAtTime(0.01, audioContext.currentTime + 0.08);
oscillator2.start(audioContext.currentTime);
oscillator2.stop(audioContext.currentTime + 0.08);
// Strong vibration
Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Heavy).catch(() => {});
} catch (error) {
Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Heavy).catch(() => {});
}
};
const playScoreSound = () => {
try {
const audioContext = new (window.AudioContext || window.webkitAudioContext)();
const oscillator = audioContext.createOscillator();
const gainNode = audioContext.createGain();
oscillator.connect(gainNode);
gainNode.connect(audioContext.destination);
oscillator.frequency.value = 800;
oscillator.type = 'sine';
gainNode.gain.setValueAtTime(0.3, audioContext.currentTime);
gainNode.gain.exponentialRampToValueAtTime(0.01, audioContext.currentTime + 0.2);
oscillator.start(audioContext.currentTime);
oscillator.stop(audioContext.currentTime + 0.2);
// Second tone for musical effect
const osc2 = audioContext.createOscillator();
const gain2 = audioContext.createGain();
osc2.connect(gain2);
gain2.connect(audioContext.destination);
osc2.frequency.value = 1000;
osc2.type = 'sine';
gain2.gain.setValueAtTime(0.2, audioContext.currentTime + 0.1);
gain2.gain.exponentialRampToValueAtTime(0.01, audioContext.currentTime + 0.3);
osc2.start(audioContext.currentTime + 0.1);
osc2.stop(audioContext.currentTime + 0.3);
// Double vibration pulse for score
Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Heavy).catch(() => {});
setTimeout(() => {
Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Heavy).catch(() => {});
}, 100);
} catch (error) {
Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Heavy).catch(() => {});
}
};
const playHitSound = () => {
try {
const audioContext = new (window.AudioContext || window.webkitAudioContext)();
// Impact bass - deep thud
const oscillator1 = audioContext.createOscillator();
const gainNode1 = audioContext.createGain();
oscillator1.connect(gainNode1);
gainNode1.connect(audioContext.destination);
oscillator1.frequency.value = 80;
oscillator1.type = 'sawtooth';
gainNode1.gain.setValueAtTime(0.6, audioContext.currentTime);
gainNode1.gain.exponentialRampToValueAtTime(0.01, audioContext.currentTime + 0.4);
oscillator1.start(audioContext.currentTime);
oscillator1.stop(audioContext.currentTime + 0.4);
// Crash noise - harsh overtone
const oscillator2 = audioContext.createOscillator();
const gainNode2 = audioContext.createGain();
oscillator2.connect(gainNode2);
gainNode2.connect(audioContext.destination);
oscillator2.frequency.value = 300;
oscillator2.type = 'square';
gainNode2.gain.setValueAtTime(0.4, audioContext.currentTime);
gainNode2.gain.exponentialRampToValueAtTime(0.01, audioContext.currentTime + 0.2);
oscillator2.start(audioContext.currentTime);
oscillator2.stop(audioContext.currentTime + 0.2);
// Triple STRONG vibration burst for collision
Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Heavy).catch(() => {});
setTimeout(() => {
Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Heavy).catch(() => {});
}, 80);
setTimeout(() => {
Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Heavy).catch(() => {});
}, 160);
} catch (error) {
Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Heavy).catch(() => {});
}
};
useEffect(() => {
if (gameState === 'playing') {
moveTheMap();
}
}, [gameState]);
const moveTheMap = () => {
pipeX.value = withSequence(
withTiming(width, { duration: 0 }),
withTiming(-150, {
duration: 3000 / pipesSpeed.value,
easing: Easing.linear,
}),
withTiming(width, { duration: 0 })
);
};
// Scoring system
useAnimatedReaction(
() => pipeX.value,
(currentValue, previousValue) => {
const middle = birdX;
// change offset for the position of the next gap
if (previousValue && currentValue < -100 && previousValue > -100) {
pipeOffset.value = Math.random() * 400 * scaleHeight - 200 * scaleHeight;
cancelAnimation(pipeX);
runOnJS(moveTheMap)();
}
if (
currentValue !== previousValue &&
previousValue &&
currentValue <= middle &&
previousValue > middle
) {
// Score point with sound
runOnJS(setScore)(score + 1);
runOnJS(playScoreSound)();
}
}
);
const isPointCollidingWithRect = (point, rect) => {
'worklet';
return (
point.x >= rect.x && // right of the left edge AND
point.x <= rect.x + rect.w && // left of the right edge AND
point.y >= rect.y && // below the top AND
point.y <= rect.y + rect.h // above the bottom
);
};
// Collision detection
useAnimatedReaction(
() => birdY.value,
(currentValue, previousValue) => {
const center = {
x: birdX + 32,
y: birdY.value + 24,
};
// Ground collision detection (scaled)
if (currentValue > height - 100 * scaleHeight || currentValue < 0) {
gameOver.value = true;
}
const isColliding = obstacles.value.some((rect) =>
isPointCollidingWithRect(center, rect)
);
if (isColliding) {
gameOver.value = true;
}
}
);
// Function to update highest score
const updateHighestScore = async (currentScore) => {
if (currentScore > highestScore) {
setHighestScore(currentScore);
try {
await AsyncStorage.setItem('highestScore', currentScore.toString());
} catch (error) {
console.log('Error saving highest score:', error);
}
}
};
useAnimatedReaction(
() => gameOver.value,
(currentValue, previousValue) => {
if (currentValue && !previousValue) {
cancelAnimation(pipeX);
runOnJS(playHitSound)();
runOnJS(setGameState)('gameOver');
runOnJS(updateHighestScore)(score);
}
}
);
useFrameCallback(({ timeSincePreviousFrame: dt }) => {
if (!dt || gameOver.value || gameState !== 'playing') {
return;
}
birdY.value = birdY.value + (birdYVelocity.value * dt) / 1000;
birdYVelocity.value = birdYVelocity.value + (GRAVITY * dt) / 1000;
});
const restartGame = () => {
'worklet';
birdY.value = height / 3;
birdYVelocity.value = 0;
gameOver.value = false;
pipeX.value = width;
pipeOffset.value = Math.random() * 400 * scaleHeight - 200 * scaleHeight; // Random gap position on restart (scaled)
runOnJS(setScore)(0);
runOnJS(setGameState)('waiting');
};
const gesture = Gesture.Tap().onStart((event) => {
if (gameState === 'waiting') {
const tapX = event.x;
const tapY = event.y;
// Check if tapping on Customize button (checks both possible positions) - SCALED
const btnY1 = height / 2 + 50 * scaleHeight; // Position when hasCustomization is true
const btnY2 = height / 2 + 100 * scaleHeight; // Position when hasCustomization is false
const btnHeight = 107 * scaleHeight;
if (tapX >= width / 2 - 160 * scaleWidth && tapX <= width / 2 + 160 * scaleWidth &&
((tapY >= btnY1 && tapY <= btnY1 + btnHeight) ||
(tapY >= btnY2 && tapY <= btnY2 + btnHeight))) {
runOnJS(setCurrentPage)('customize');
runOnJS(playJumpSound)();
return;
}
// Check if tapping on Development Team button - SCALED
const devBtnY1 = height / 2 + 165 * scaleHeight; // Position when hasCustomization is true
const devBtnY2 = height / 2 + 215 * scaleHeight; // Position when hasCustomization is false
const devBtnHeight = 87 * scaleHeight;
if (tapX >= width / 2 - 130 * scaleWidth && tapX <= width / 2 + 130 * scaleWidth &&
((tapY >= devBtnY1 && tapY <= devBtnY1 + devBtnHeight) ||
(tapY >= devBtnY2 && tapY <= devBtnY2 + devBtnHeight))) {
runOnJS(setCurrentPage)('devteam');
runOnJS(playJumpSound)();
return;
}
// Otherwise start game
runOnJS(setGameState)('playing');
runOnJS(playJumpSound)();
birdYVelocity.value = JUMP_FORCE;
} else if (gameState === 'playing') {
// Jump
runOnJS(playJumpSound)();
birdYVelocity.value = JUMP_FORCE;
} else if (gameState === 'gameOver') {
// Restart
restartGame();
}
});
// Customize page gesture handler
const customizeGesture = Gesture.Tap().onStart((event) => {
'worklet';
const tapX = event.x;
const tapY = event.y;
// Theme buttons - SCALED
const themeY = 250 * scaleHeight;
const themeRadius = 30 * scale;
// Day theme
if (Math.sqrt((tapX - (width / 2 - 80 * scaleWidth)) ** 2 + (tapY - themeY) ** 2) <= themeRadius) {
runOnJS(setTheme)('day');
runOnJS(playJumpSound)();
return;
}
// Night theme
if (Math.sqrt((tapX - (width / 2)) ** 2 + (tapY - themeY) ** 2) <= themeRadius) {
runOnJS(setTheme)('night');
runOnJS(playJumpSound)();
return;
}
// City theme
if (Math.sqrt((tapX - (width / 2 + 80 * scaleWidth)) ** 2 + (tapY - themeY) ** 2) <= themeRadius) {
runOnJS(setTheme)('city');
runOnJS(playJumpSound)();
return;
}
// Bird buttons - SCALED
const birdY = 410 * scaleHeight;
const birdHeight = 52 * scaleHeight;
const birdWidth = 70 * scaleWidth;
// Yellow bird
if (tapX >= 15 * scaleWidth && tapX <= 15 * scaleWidth + birdWidth && tapY >= birdY && tapY <= birdY + birdHeight) {
runOnJS(setBirdColor)('yellow');
runOnJS(playJumpSound)();
return;
}
// Blue bird
if (tapX >= 100 * scaleWidth && tapX <= 100 * scaleWidth + birdWidth && tapY >= birdY && tapY <= birdY + birdHeight) {
runOnJS(setBirdColor)('blue');
runOnJS(playJumpSound)();
return;
}
// Red bird
if (tapX >= 185 * scaleWidth && tapX <= 185 * scaleWidth + birdWidth && tapY >= birdY && tapY <= birdY + birdHeight) {
runOnJS(setBirdColor)('red');
runOnJS(playJumpSound)();
return;
}
// Custom bird buttons - 4 columns with proper spacing - SCALED
const birdSize = 60 * scale;
const totalWidth = width - 20 * scaleWidth;
const spacing = (totalWidth - (4 * birdSize)) / 5;
const customPositions = [
10 * scaleWidth + spacing + birdSize / 2,
10 * scaleWidth + spacing + birdSize + spacing + birdSize / 2,
10 * scaleWidth + spacing + birdSize + spacing + birdSize + spacing + birdSize / 2,
10 * scaleWidth + spacing + birdSize + spacing + birdSize + spacing + birdSize + spacing + birdSize / 2
];
const customBirdStartY = 530 * scaleHeight;
const customBirdRadius = 35 * scale; // Smaller radius for smaller birds
const customBirdRowSpacing = 110 * scaleHeight; // More spacing between rows
const birdsPerRow = 4; // 4 columns with better spacing
// Check each existing custom bird
for (let i = 0; i < customImages.length; i++) {
const col = i % birdsPerRow;
const row = Math.floor(i / birdsPerRow);
const birdX = customPositions[col];
const birdY = customBirdStartY + row * customBirdRowSpacing;
// Check delete button (top-right corner) - SCALED
const deleteX = birdX + 25 * scaleWidth;
const deleteY = birdY - 25 * scaleHeight;
const deleteRadius = 15 * scale;
if (Math.sqrt((tapX - deleteX) ** 2 + (tapY - deleteY) ** 2) <= deleteRadius) {
runOnJS(deleteCustomBird)(i);
return;
}
// Check bird selection (main circle)
if (Math.sqrt((tapX - birdX) ** 2 + (tapY - birdY) ** 2) <= customBirdRadius) {
runOnJS(setBirdColor)(`custom${i}`);
runOnJS(playJumpSound)();
return;
}
}
// Check the "+" add button (always after the last custom bird) - SCALED
const nextIndex = customImages.length;
const nextCol = nextIndex % birdsPerRow;
const nextRow = Math.floor(nextIndex / birdsPerRow);
const nextX = customPositions[nextCol];
const nextY = customBirdStartY + nextRow * customBirdRowSpacing;
if (Math.sqrt((tapX - nextX) ** 2 + (tapY - nextY) ** 2) <= 35 * scale) {
runOnJS(pickImage)();
return;
}
// Calculate dynamic button positions based on custom birds - SCALED
const customBirdRows = Math.ceil((customImages.length + 1) / birdsPerRow); // +1 for the "+" button
const customBirdsBottom = customBirdStartY + (customBirdRows - 1) * customBirdRowSpacing + 70 * scaleHeight; // bottom of last row + padding
const buttonStartY = Math.max(customBirdsBottom + 20 * scaleHeight, 530 * scaleHeight); // At least 20px below custom birds or default position
// Save button - SCALED (left side, moves down with custom birds)
if (tapX >= 5 * scaleWidth && tapX <= 175 * scaleWidth && tapY >= buttonStartY && tapY <= buttonStartY + 100 * scaleHeight) {
runOnJS(savePreferences)();
return;
}
// Back button - SCALED (right side, moves down with custom birds)
if (tapX >= 180 * scaleWidth && tapX <= 355 * scaleWidth && tapY >= buttonStartY && tapY <= buttonStartY + 100 * scaleHeight) {
runOnJS(setCurrentPage)('game');
runOnJS(playJumpSound)();
return;
}
});
const birdTransform = useDerivedValue(() => {
return [
{
rotate: interpolate(
birdYVelocity.value,
[-500, 500],
[-0.5, 0.5],
Extrapolation.CLAMP
),
},
];
});
const birdOrigin = useDerivedValue(() => {
return { x: width / 4 + 32 * scale, y: birdY.value + 24 * scale };
});
// Create circular clip for custom bird
const birdClipPath = useDerivedValue(() => {
return rrect(rect(birdX, birdY.value, 48 * scale, 48 * scale), 24 * scale, 24 * scale);
});
const fontFamily = Platform.select({ ios: 'Helvetica', default: 'serif' });
const pixelFontFamily = Platform.select({ ios: 'Courier', android: 'monospace', default: 'monospace' });
const fontStyle = {
fontFamily,
fontSize: 40,
};
const font = matchFont(fontStyle);
const smallFontStyle = {
fontFamily,
fontSize: 14,
};
const smallFont = matchFont(smallFontStyle);
const mediumFontStyle = {
fontFamily: pixelFontFamily,
fontSize: 18,
fontWeight: 'bold',
};
const mediumFont = matchFont(mediumFontStyle);
const boldPixelFontStyle = {
fontFamily: pixelFontFamily,
fontSize: 24,
fontWeight: 'bold',
};
const boldPixelFont = matchFont(boldPixelFontStyle);
const pixelAvatarFontStyle = {
fontFamily: pixelFontFamily,
fontSize: 32,
fontWeight: 'bold',
};
const pixelAvatarFont = matchFont(pixelAvatarFontStyle);
return (
<GestureHandlerRootView style={{ flex: 1 }}>
{currentPage === 'game' ? (
<GestureDetector gesture={gesture}>
<Canvas style={{ width, height }}>
{/* BG */}
<Image image={bg} width={width} height={height} fit={'cover'} />
{/* Pipes - only show when playing */}
{gameState !== 'waiting' && (
<>
<Image
image={pipeTop}
y={topPipeY}
x={pipeX}
width={scaledPipeWidth}
height={scaledPipeHeight}
/>
<Image
image={pipeBottom}
y={bottomPipeY}
x={pipeX}
width={scaledPipeWidth}
height={scaledPipeHeight}
/>
</>
)}
{/* Base */}
<Image
image={base}
width={width}
height={150 * scaleHeight}
y={height - 75 * scaleHeight}
x={0}
fit={'cover'}
/>
{/* Bird - only show when not in waiting state */}
{bird && gameState !== 'waiting' && (
<Group transform={birdTransform} origin={birdOrigin}>
{birdColor.startsWith('custom') ? (
<Group clip={birdClipPath}>
{/* Circular clipped custom bird with pixel art style and background removal */}
<Image
image={bird}
y={birdY}
x={birdX}
width={48 * scale}
height={48 * scale}
fit="cover"
>
<ColorMatrix
matrix={[
1.2, 0, 0, 0, 0, // Red: boost contrast
0, 1.2, 0, 0, 0, // Green: boost contrast
0, 0, 1.2, 0, 0, // Blue: boost contrast
0, 0, 0, 1.5, -0.3, // Alpha: increase transparency on lighter pixels
]}
/>
</Image>
</Group>
) : (
<Image image={bird} y={birdY} x={birdX} width={64 * scale} height={48 * scale} />
)}
</Group>
)}
{/* Score - only show when playing */}
{gameState === 'playing' && (
<>
{/* Current Score */}
<Text
x={width / 2 - 30 * scaleWidth}
y={100 * scaleHeight}
text={score.toString()}
font={font}
/>
</>
)}
{/* Tap to Play Message - SCALED */}
{gameState === 'waiting' && messageImg && (
<>
{/* Highest Score - Image with number overlay - LEFT ALIGNED & SCALED (same as gameplay) */}
{bestScoreImg && (() => {
const imgWidth = 140 * scaleWidth;
const imgHeight = 140 * scaleHeight;
const imgX = 90 * scaleWidth;
const imgY = 140 * scaleHeight;
// Calculate text position to center the score number inside the image
const scoreText = highestScore.toString();
const charWidth = 12; // Character width in pixels
const textWidth = scoreText.length * charWidth * scaleWidth;
// Center text horizontally in the badge + move much more to the right
const textX = imgX + (imgWidth / 2) - (textWidth / 2) + (80 * scaleWidth);
// Position text vertically in center of badge (50% down + slight adjustment for visual center + 4px down)
const textY = imgY + (imgHeight / 2) + (12 * scaleHeight);
return (
<>
{/* Best Score Image */}
<Image
image={bestScoreImg}
x={imgX}
y={imgY}
width={imgWidth}
height={imgHeight}
fit="contain"
/>
{/* Score number on top of image - with shadow */}
<Text
x={textX + 1.5 * scaleWidth}
y={textY + 1.5 * scaleHeight}
text={scoreText}
font={font}
color="#000000"
/>
<Text
x={textX}
y={textY}
text={scoreText}
font={font}
color="#FFD700"
/>
</>
);
})()}
<Image
image={messageImg}
x={width / 2 - 92 * scaleWidth}
y={height / 2 - 150 * scaleHeight}
width={184 * scaleWidth}
height={267 * scaleHeight}
/>
{/* Customize Button - moves based on whether customization is saved - SCALED */}
{customizeBtn && (
<Image
image={customizeBtn}
x={width / 2 - 145 * scaleWidth}
y={hasCustomization ? height / 2 + 50 * scaleHeight : height / 2 + 100 * scaleHeight}
width={320 * scaleWidth}
height={107 * scaleHeight}
fit="contain"
/>
)}
{/* Development Team Button - SCALED */}
{devTeamBtn && (
<Image
image={devTeamBtn}
x={width / 2 - 130 * scaleWidth}
y={hasCustomization ? height / 2 + 165 * scaleHeight : height / 2 + 215 * scaleHeight}
width={260 * scaleWidth}
height={87 * scaleHeight}
fit="contain"
/>
)}
</>
)}
{/* Game Over Screen - SCALED */}
{gameState === 'gameOver' && (
<>
{/* Game Over Image - SCALED */}
{gameOverImg && (
<Image
image={gameOverImg}
x={width / 2 - 96 * scaleWidth}
y={150 * scaleHeight}
width={192 * scaleWidth}
height={42 * scaleHeight}
/>
)}
{/* Final Score with shadow effect - CENTERED & RESPONSIVE */}
{(() => {
const displayText = `Score: ${score}`;
// More accurate character width estimation: 13px per char scaled
const textWidth = displayText.length * 13 * scaleWidth;
const centerX = (width - textWidth) / 2;
return (
<>
<Text
x={centerX + 2 * scaleWidth}
y={230 * scaleHeight}
text={displayText}
font={font}
color="#000000"
/>
<Text
x={centerX}
y={228 * scaleHeight}
text={displayText}
font={font}
color="#FFD700"
/>
</>
);
})()}
{/* Highest Score - Image or New Record Text - CENTERED & RESPONSIVE */}
{(() => {
const isNewRecord = score > highestScore;
if (isNewRecord) {
// Show "NEW RECORD!" text
const displayText = "* NEW RECORD! *";
const textWidth = displayText.length * 13 * scaleWidth;
const centerX = (width - textWidth) / 2;
return (
<>
<Text
x={centerX + 2 * scaleWidth}
y={282 * scaleHeight}
text={displayText}
font={font}