zentap_game.dart 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  1. import 'package:flame/components.dart';
  2. import 'package:flame/effects.dart';
  3. import 'package:flame/game.dart';
  4. import 'package:flutter/material.dart';
  5. import 'dart:math';
  6. import '../utils/colors.dart';
  7. import '../utils/score_manager.dart';
  8. import '../utils/settings_manager.dart';
  9. import '../utils/tilt_detector.dart';
  10. import '../utils/google_play_games_manager.dart';
  11. import 'components/bubble.dart';
  12. import 'components/bubble_spawner.dart';
  13. import 'audio/audio_manager.dart';
  14. class ZenTapGame extends FlameGame with HasCollisionDetection {
  15. static const String routeName = '/game';
  16. TextComponent? scoreText;
  17. TextComponent? timerText;
  18. int score = 0;
  19. bool isZenMode = false;
  20. double gameTime = 0.0;
  21. bool gameActive = true;
  22. // Localized strings
  23. String zenModeText = 'Zen Mode';
  24. String relaxationPointsText = 'Relaxation Points';
  25. String timeText = 'Time';
  26. BubbleSpawner? bubbleSpawner;
  27. final AudioManager audioManager = AudioManager();
  28. final TiltDetector _tiltDetector = TiltDetector();
  29. final TiltDetector tiltDetector = TiltDetector();
  30. final GooglePlayGamesManager _gamesManager = GooglePlayGamesManager.instance;
  31. // Google Play Games tracking
  32. int _totalBubblesPopped = 0;
  33. double _sessionStartTime = 0.0;
  34. bool _perfectSession = true; // No missed bubbles
  35. // Performance optimization: cache last displayed second to avoid unnecessary text updates
  36. int _lastDisplayedSecond = -1;
  37. /// Set localized strings for the game
  38. void setLocalizedStrings({
  39. required String zenMode,
  40. required String relaxationPoints,
  41. required String time,
  42. }) {
  43. zenModeText = zenMode;
  44. relaxationPointsText = relaxationPoints;
  45. timeText = time;
  46. }
  47. @override
  48. Color backgroundColor() => Colors.transparent;
  49. @override
  50. Future<void> onLoad() async {
  51. await super.onLoad();
  52. // Initialize Google Play Games
  53. await _gamesManager.initialize();
  54. // Track session start time
  55. _sessionStartTime = DateTime.now().millisecondsSinceEpoch / 1000.0;
  56. // Initialize score manager and audio
  57. await ScoreManager.initialize();
  58. await audioManager.initialize();
  59. // Apply saved audio settings after initialization
  60. audioManager.setMusicEnabled(SettingsManager.isMusicEnabled);
  61. audioManager.setHapticEnabled(SettingsManager.isHapticsEnabled);
  62. audioManager.setBgmVolume(SettingsManager.bgmVolume);
  63. audioManager.setSfxVolume(SettingsManager.sfxVolume);
  64. // Initialize score display
  65. scoreText = TextComponent(
  66. text: isZenMode ? zenModeText : '$relaxationPointsText: $score',
  67. textRenderer: TextPaint(
  68. style: const TextStyle(
  69. color: ZenColors.scoreText,
  70. fontSize: 24,
  71. fontWeight: FontWeight.w500,
  72. ),
  73. ),
  74. position: Vector2(20, 50),
  75. );
  76. add(scoreText!);
  77. // Initialize timer display (only in regular mode)
  78. if (!isZenMode) {
  79. timerText = TextComponent(
  80. text: '$timeText: ${_formatTime(gameTime)}',
  81. textRenderer: TextPaint(
  82. style: const TextStyle(
  83. color: ZenColors.timerText,
  84. fontSize: 18,
  85. ),
  86. ),
  87. position: Vector2(20, 80),
  88. );
  89. add(timerText!);
  90. }
  91. // Add initial game elements
  92. await _initializeGame();
  93. // Start background music after all initialization is complete
  94. await audioManager.playBackgroundMusic();
  95. // Start tilt detection
  96. _initializeTiltDetection();
  97. }
  98. double _lastTiltUpdateTime = 0.0;
  99. static const double tiltUpdateInterval = 0.1; // Update tilt effects max 10 times per second
  100. void _initializeTiltDetection() {
  101. _tiltDetector.startListening(
  102. onTiltChanged: (tiltAngle) {
  103. // Throttle tilt updates to improve performance
  104. final currentTime = DateTime.now().millisecondsSinceEpoch / 1000.0;
  105. if (currentTime - _lastTiltUpdateTime >= tiltUpdateInterval) {
  106. _lastTiltUpdateTime = currentTime;
  107. _applyTiltToAllBubbles(_tiltDetector.normalizedTilt);
  108. }
  109. },
  110. onShakeDetected: () {
  111. handleShake();
  112. },
  113. );
  114. }
  115. void _applyTiltToAllBubbles(double tiltStrength) async {
  116. if (bubbleSpawner == null) return;
  117. // Apply tilt forces asynchronously to avoid blocking main thread
  118. final activeBubbles = bubbleSpawner!.getActiveBubbles();
  119. // Process bubbles in smaller batches to prevent frame drops
  120. const batchSize = 3;
  121. for (int i = 0; i < activeBubbles.length; i += batchSize) {
  122. final endIndex = (i + batchSize).clamp(0, activeBubbles.length);
  123. final batch = activeBubbles.sublist(i, endIndex);
  124. for (final bubble in batch) {
  125. bubble.applyTiltForce(tiltStrength);
  126. }
  127. // Yield control back to the framework between batches
  128. if (endIndex < activeBubbles.length) {
  129. await Future.delayed(Duration.zero);
  130. }
  131. }
  132. }
  133. Future<void> _initializeGame() async {
  134. // Initialize bubble spawner
  135. bubbleSpawner = BubbleSpawner(
  136. onBubblePopped: _onBubblePopped,
  137. );
  138. add(bubbleSpawner!);
  139. // Instruction text removed for cleaner interface
  140. // Background music is now started in onLoad() after all initialization
  141. }
  142. @override
  143. void update(double dt) {
  144. super.update(dt);
  145. if (gameActive && !isZenMode) {
  146. gameTime += dt;
  147. // Performance optimization: only update timer text when the second changes
  148. final currentSecond = gameTime.toInt();
  149. if (currentSecond != _lastDisplayedSecond) {
  150. _lastDisplayedSecond = currentSecond;
  151. _updateTimer();
  152. }
  153. }
  154. }
  155. @override
  156. void onGameResize(Vector2 size) {
  157. super.onGameResize(size);
  158. // Update text positions when screen size changes
  159. if (scoreText != null) {
  160. scoreText!.position = Vector2(20, 50);
  161. }
  162. if (timerText != null) {
  163. timerText!.position = Vector2(20, 80);
  164. }
  165. // Reposition bubbles that might be off-screen
  166. _repositionBubblesInBounds();
  167. }
  168. void _repositionBubblesInBounds() {
  169. if (bubbleSpawner == null) return;
  170. const margin = 120.0;
  171. final minX = margin;
  172. final maxX = size.x - margin;
  173. final minY = margin + 100;
  174. final maxY = size.y - margin;
  175. if (maxX <= minX || maxY <= minY) return;
  176. // Performance optimization: use bubble spawner's cached active bubbles
  177. final activeBubbles = bubbleSpawner!.getActiveBubbles();
  178. for (final bubble in activeBubbles) {
  179. if (!bubble.isPopping) {
  180. bool needsRepositioning = false;
  181. Vector2 newPosition = bubble.position.clone();
  182. if (bubble.position.x < minX) {
  183. newPosition.x = minX;
  184. needsRepositioning = true;
  185. } else if (bubble.position.x > maxX) {
  186. newPosition.x = maxX;
  187. needsRepositioning = true;
  188. }
  189. if (bubble.position.y < minY) {
  190. newPosition.y = minY;
  191. needsRepositioning = true;
  192. } else if (bubble.position.y > maxY) {
  193. newPosition.y = maxY;
  194. needsRepositioning = true;
  195. }
  196. if (needsRepositioning) {
  197. bubble.position = newPosition;
  198. }
  199. }
  200. }
  201. }
  202. void handleTap(Vector2 position) {
  203. if (!gameActive) return;
  204. // Create a bubble at tap position if in zen mode or no bubble was hit
  205. if (isZenMode) {
  206. bubbleSpawner?.spawnBubbleAt(position);
  207. }
  208. // Add visual feedback at tap position
  209. _addTapEffect(position);
  210. }
  211. void _onBubblePopped(Bubble bubble, bool userTriggered) {
  212. // Play pop sound and haptic feedback
  213. audioManager.playBubblePop();
  214. // Track Google Play Games statistics
  215. if (userTriggered) {
  216. _totalBubblesPopped++;
  217. // Check for perfect session achievement after significant bubbles
  218. if (_totalBubblesPopped >= 50 && _perfectSession) {
  219. _gamesManager.unlockAchievement(
  220. GooglePlayGamesManager.achievementPerfectSession
  221. );
  222. }
  223. } else {
  224. // User missed a bubble (it timed out)
  225. _perfectSession = false;
  226. }
  227. if (!isZenMode && userTriggered) {
  228. // Only increment score for user-triggered pops in regular mode
  229. score += 10; // 10 points per bubble
  230. ScoreManager.addScore(10);
  231. _updateScore();
  232. // Check for speed achievements
  233. _gamesManager.checkScoreAchievements(score, gameTime);
  234. }
  235. // Check bubble-based achievements
  236. _gamesManager.checkBubbleAchievements(_totalBubblesPopped);
  237. }
  238. void _updateScore() {
  239. scoreText?.text = '$relaxationPointsText: $score';
  240. }
  241. void _updateTimer() {
  242. timerText?.text = '$timeText: ${_formatTime(gameTime)}';
  243. }
  244. // Helper method to format time as MM:SS
  245. String _formatTime(double seconds) {
  246. final minutes = (seconds / 60).floor();
  247. final remainingSeconds = (seconds % 60).floor();
  248. return '${minutes.toString().padLeft(2, '0')}:${remainingSeconds.toString().padLeft(2, '0')}';
  249. }
  250. void _addTapEffect(Vector2 position) {
  251. // Create a simple tap effect circle with animation
  252. final tapEffect = CircleComponent(
  253. radius: 15,
  254. paint: Paint()
  255. ..color = ZenColors.bubblePopEffect.withValues(alpha: 0.6)
  256. ..style = PaintingStyle.stroke
  257. ..strokeWidth = 2,
  258. position: position,
  259. anchor: Anchor.center,
  260. );
  261. add(tapEffect);
  262. // Add scaling animation
  263. tapEffect.add(
  264. ScaleEffect.to(
  265. Vector2.all(2.0),
  266. EffectController(duration: 0.3),
  267. ),
  268. );
  269. // Add fade animation
  270. tapEffect.add(
  271. OpacityEffect.to(
  272. 0.0,
  273. EffectController(duration: 0.3),
  274. ),
  275. );
  276. // Remove the effect after animation
  277. Future.delayed(const Duration(milliseconds: 300), () {
  278. if (tapEffect.isMounted) {
  279. remove(tapEffect);
  280. }
  281. });
  282. }
  283. void setZenMode(bool zenMode) {
  284. isZenMode = zenMode;
  285. if (scoreText != null) {
  286. if (zenMode) {
  287. scoreText!.text = zenModeText;
  288. score = 0;
  289. // Hide timer in zen mode
  290. timerText?.removeFromParent();
  291. timerText = null;
  292. } else {
  293. scoreText!.text = '$relaxationPointsText: $score';
  294. // Show timer in regular mode
  295. if (timerText == null) {
  296. timerText = TextComponent(
  297. text: '$timeText: ${_formatTime(gameTime)}',
  298. textRenderer: TextPaint(
  299. style: const TextStyle(
  300. color: ZenColors.timerText,
  301. fontSize: 18,
  302. ),
  303. ),
  304. position: Vector2(20, 80),
  305. );
  306. add(timerText!);
  307. }
  308. }
  309. }
  310. // Update bubble spawner behavior
  311. bubbleSpawner?.setActive(!zenMode);
  312. }
  313. void resetGame() {
  314. score = 0;
  315. gameTime = 0.0;
  316. gameActive = true;
  317. _updateScore();
  318. _updateTimer();
  319. // Clear all bubbles
  320. bubbleSpawner?.clearAllBubbles();
  321. }
  322. void pauseGame() {
  323. paused = true;
  324. gameActive = false;
  325. audioManager.pauseBackgroundMusic();
  326. _tiltDetector.stopListening();
  327. }
  328. void resumeGame() {
  329. paused = false;
  330. gameActive = true;
  331. audioManager.resumeBackgroundMusic();
  332. _initializeTiltDetection();
  333. }
  334. /// End the game session and submit results to Google Play Games
  335. Future<void> endGameSession() async {
  336. gameActive = false;
  337. final currentTime = DateTime.now().millisecondsSinceEpoch / 1000.0;
  338. final sessionLength = currentTime - _sessionStartTime;
  339. // Check for zen mode achievements
  340. if (isZenMode) {
  341. await _gamesManager.checkZenModeAchievements(sessionLength);
  342. }
  343. // Submit final results to Google Play Games
  344. await _gamesManager.submitGameResults(
  345. finalScore: score,
  346. isZenMode: isZenMode,
  347. totalBubblesPopped: _totalBubblesPopped,
  348. sessionLength: sessionLength,
  349. );
  350. // Score is already tracked by ScoreManager.addScore() calls during gameplay
  351. }
  352. void handleShake() {
  353. if (!gameActive) return;
  354. // Get existing bubbles before spawning new ones
  355. final existingBubbles = bubbleSpawner?.getActiveBubbles().toList() ?? [];
  356. // Single bubble per shake rule: spawn only ONE bubble per shake
  357. // Find a safe position that doesn't overlap with existing bubbles
  358. final safePosition = _findSafeSpawnPosition();
  359. if (safePosition != null) {
  360. bubbleSpawner?.spawnBubbleAt(safePosition);
  361. }
  362. // Only shake the existing bubbles (not the newly spawned ones)
  363. _shakeExistingBubbles(existingBubbles);
  364. }
  365. void _shakeExistingBubbles(List<Bubble> existingBubbles) {
  366. // Only apply shake effects to bubbles that existed before this shake
  367. for (final bubble in existingBubbles) {
  368. if (!bubble.isPopping) {
  369. bubble.addShakeEffect();
  370. }
  371. }
  372. }
  373. /// Find a safe position to spawn a bubble that doesn't overlap with existing bubbles
  374. Vector2? _findSafeSpawnPosition() {
  375. const margin = 120.0;
  376. const minDistance = 80.0; // Minimum distance from other bubbles
  377. const maxAttempts = 20; // Maximum attempts to find a safe position
  378. final random = Random();
  379. final activeBubbles = bubbleSpawner?.getActiveBubbles() ?? [];
  380. for (int attempt = 0; attempt < maxAttempts; attempt++) {
  381. // Generate random position within bounds
  382. final position = Vector2(
  383. margin + random.nextDouble() * (size.x - 2 * margin),
  384. margin + 100 + random.nextDouble() * (size.y - 2 * margin - 100),
  385. );
  386. // Check if position is safe from all existing bubbles
  387. bool isSafe = true;
  388. for (final bubble in activeBubbles) {
  389. if (!bubble.isPopping) {
  390. final distance = position.distanceTo(bubble.position);
  391. if (distance < minDistance) {
  392. isSafe = false;
  393. break;
  394. }
  395. }
  396. }
  397. if (isSafe) {
  398. return position;
  399. }
  400. }
  401. // If no safe position found, return null (don't spawn)
  402. return null;
  403. }
  404. @override
  405. void onRemove() {
  406. // End the game session and submit results
  407. endGameSession();
  408. audioManager.stopBackgroundMusic();
  409. _tiltDetector.stopListening();
  410. super.onRemove();
  411. }
  412. }