zentap_game.dart 12 KB

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