zentap_game.dart 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  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. void _initializeTiltDetection() {
  79. _tiltDetector.startListening(
  80. onTiltChanged: (tiltAngle) {
  81. _applyTiltToAllBubbles(_tiltDetector.normalizedTilt);
  82. },
  83. );
  84. }
  85. void _applyTiltToAllBubbles(double tiltStrength) {
  86. if (bubbleSpawner == null) return;
  87. final activeBubbles = bubbleSpawner!.getActiveBubbles();
  88. for (final bubble in activeBubbles) {
  89. bubble.applyTiltForce(tiltStrength);
  90. }
  91. }
  92. Future<void> _initializeGame() async {
  93. // Initialize bubble spawner
  94. bubbleSpawner = BubbleSpawner(
  95. onBubblePopped: _onBubblePopped,
  96. );
  97. add(bubbleSpawner!);
  98. // Instruction text removed for cleaner interface
  99. // Background music is now started in onLoad() after all initialization
  100. }
  101. @override
  102. void update(double dt) {
  103. super.update(dt);
  104. if (gameActive && !isZenMode) {
  105. gameTime += dt;
  106. // Performance optimization: only update timer text when the second changes
  107. final currentSecond = gameTime.toInt();
  108. if (currentSecond != _lastDisplayedSecond) {
  109. _lastDisplayedSecond = currentSecond;
  110. _updateTimer();
  111. }
  112. }
  113. }
  114. @override
  115. void onGameResize(Vector2 size) {
  116. super.onGameResize(size);
  117. // Update text positions when screen size changes
  118. if (scoreText != null) {
  119. scoreText!.position = Vector2(20, 50);
  120. }
  121. if (timerText != null) {
  122. timerText!.position = Vector2(20, 80);
  123. }
  124. // Reposition bubbles that might be off-screen
  125. _repositionBubblesInBounds();
  126. }
  127. void _repositionBubblesInBounds() {
  128. if (bubbleSpawner == null) return;
  129. const margin = 120.0;
  130. final minX = margin;
  131. final maxX = size.x - margin;
  132. final minY = margin + 100;
  133. final maxY = size.y - margin;
  134. if (maxX <= minX || maxY <= minY) return;
  135. // Performance optimization: use bubble spawner's cached active bubbles
  136. final activeBubbles = bubbleSpawner!.getActiveBubbles();
  137. for (final bubble in activeBubbles) {
  138. if (!bubble.isPopping) {
  139. bool needsRepositioning = false;
  140. Vector2 newPosition = bubble.position.clone();
  141. if (bubble.position.x < minX) {
  142. newPosition.x = minX;
  143. needsRepositioning = true;
  144. } else if (bubble.position.x > maxX) {
  145. newPosition.x = maxX;
  146. needsRepositioning = true;
  147. }
  148. if (bubble.position.y < minY) {
  149. newPosition.y = minY;
  150. needsRepositioning = true;
  151. } else if (bubble.position.y > maxY) {
  152. newPosition.y = maxY;
  153. needsRepositioning = true;
  154. }
  155. if (needsRepositioning) {
  156. bubble.position = newPosition;
  157. }
  158. }
  159. }
  160. }
  161. void handleTap(Vector2 position) {
  162. if (!gameActive) return;
  163. // Create a bubble at tap position if in zen mode or no bubble was hit
  164. if (isZenMode) {
  165. bubbleSpawner?.spawnBubbleAt(position);
  166. }
  167. // Add visual feedback at tap position
  168. _addTapEffect(position);
  169. }
  170. void _onBubblePopped(Bubble bubble, bool userTriggered) {
  171. // Play pop sound and haptic feedback
  172. audioManager.playBubblePop();
  173. // Track Google Play Games statistics
  174. if (userTriggered) {
  175. _totalBubblesPopped++;
  176. // Check for perfect session achievement after significant bubbles
  177. if (_totalBubblesPopped >= 50 && _perfectSession) {
  178. _gamesManager.unlockAchievement(
  179. GooglePlayGamesManager.achievementPerfectSession
  180. );
  181. }
  182. } else {
  183. // User missed a bubble (it timed out)
  184. _perfectSession = false;
  185. }
  186. if (!isZenMode && userTriggered) {
  187. // Only increment score for user-triggered pops in regular mode
  188. score += 10; // 10 points per bubble
  189. ScoreManager.addScore(10);
  190. _updateScore();
  191. // Check for speed achievements
  192. _gamesManager.checkScoreAchievements(score, gameTime);
  193. }
  194. // Check bubble-based achievements
  195. _gamesManager.checkBubbleAchievements(_totalBubblesPopped);
  196. }
  197. void _updateScore() {
  198. scoreText?.text = 'Relaxation Points: $score';
  199. }
  200. void _updateTimer() {
  201. timerText?.text = 'Time: ${_formatTime(gameTime)}';
  202. }
  203. // Helper method to format time as MM:SS
  204. String _formatTime(double seconds) {
  205. final minutes = (seconds / 60).floor();
  206. final remainingSeconds = (seconds % 60).floor();
  207. return '${minutes.toString().padLeft(2, '0')}:${remainingSeconds.toString().padLeft(2, '0')}';
  208. }
  209. void _addTapEffect(Vector2 position) {
  210. // Create a simple tap effect circle with animation
  211. final tapEffect = CircleComponent(
  212. radius: 15,
  213. paint: Paint()
  214. ..color = ZenColors.bubblePopEffect.withValues(alpha: 0.6)
  215. ..style = PaintingStyle.stroke
  216. ..strokeWidth = 2,
  217. position: position,
  218. anchor: Anchor.center,
  219. );
  220. add(tapEffect);
  221. // Add scaling animation
  222. tapEffect.add(
  223. ScaleEffect.to(
  224. Vector2.all(2.0),
  225. EffectController(duration: 0.3),
  226. ),
  227. );
  228. // Add fade animation
  229. tapEffect.add(
  230. OpacityEffect.to(
  231. 0.0,
  232. EffectController(duration: 0.3),
  233. ),
  234. );
  235. // Remove the effect after animation
  236. Future.delayed(const Duration(milliseconds: 300), () {
  237. if (tapEffect.isMounted) {
  238. remove(tapEffect);
  239. }
  240. });
  241. }
  242. void setZenMode(bool zenMode) {
  243. isZenMode = zenMode;
  244. if (scoreText != null) {
  245. if (zenMode) {
  246. scoreText!.text = 'Zen Mode';
  247. score = 0;
  248. // Hide timer in zen mode
  249. timerText?.removeFromParent();
  250. timerText = null;
  251. } else {
  252. scoreText!.text = 'Relaxation Points: $score';
  253. // Show timer in regular mode
  254. if (timerText == null) {
  255. timerText = TextComponent(
  256. text: 'Time: ${_formatTime(gameTime)}',
  257. textRenderer: TextPaint(
  258. style: const TextStyle(
  259. color: ZenColors.timerText,
  260. fontSize: 18,
  261. ),
  262. ),
  263. position: Vector2(20, 80),
  264. );
  265. add(timerText!);
  266. }
  267. }
  268. }
  269. // Update bubble spawner behavior
  270. bubbleSpawner?.setActive(!zenMode);
  271. }
  272. void resetGame() {
  273. score = 0;
  274. gameTime = 0.0;
  275. gameActive = true;
  276. _updateScore();
  277. _updateTimer();
  278. // Clear all bubbles
  279. bubbleSpawner?.clearAllBubbles();
  280. }
  281. void pauseGame() {
  282. paused = true;
  283. gameActive = false;
  284. audioManager.pauseBackgroundMusic();
  285. _tiltDetector.stopListening();
  286. }
  287. void resumeGame() {
  288. paused = false;
  289. gameActive = true;
  290. audioManager.resumeBackgroundMusic();
  291. _initializeTiltDetection();
  292. }
  293. /// End the game session and submit results to Google Play Games
  294. Future<void> endGameSession() async {
  295. gameActive = false;
  296. final currentTime = DateTime.now().millisecondsSinceEpoch / 1000.0;
  297. final sessionLength = currentTime - _sessionStartTime;
  298. // Check for zen mode achievements
  299. if (isZenMode) {
  300. await _gamesManager.checkZenModeAchievements(sessionLength);
  301. }
  302. // Submit final results to Google Play Games
  303. await _gamesManager.submitGameResults(
  304. finalScore: score,
  305. isZenMode: isZenMode,
  306. totalBubblesPopped: _totalBubblesPopped,
  307. sessionLength: sessionLength,
  308. );
  309. // Score is already tracked by ScoreManager.addScore() calls during gameplay
  310. }
  311. void handleShake() {
  312. if (!gameActive) return;
  313. // Spawn 2-4 extra bubbles on shake
  314. final random = Random();
  315. final bubbleCount = 2 + random.nextInt(3); // 2-4 bubbles
  316. for (int i = 0; i < bubbleCount; i++) {
  317. final position = Vector2(
  318. 50 + random.nextDouble() * (size.x - 100),
  319. 100 + random.nextDouble() * (size.y - 200),
  320. );
  321. bubbleSpawner?.spawnBubbleAt(position);
  322. }
  323. // Shake all existing bubbles
  324. _shakeAllBubbles();
  325. }
  326. void _shakeAllBubbles() {
  327. // Performance optimization: use bubble spawner's cached active bubbles
  328. if (bubbleSpawner == null) return;
  329. final activeBubbles = bubbleSpawner!.getActiveBubbles();
  330. for (final bubble in activeBubbles) {
  331. if (!bubble.isPopping) {
  332. bubble.addShakeEffect();
  333. }
  334. }
  335. }
  336. @override
  337. void onRemove() {
  338. // End the game session and submit results
  339. endGameSession();
  340. audioManager.stopBackgroundMusic();
  341. _tiltDetector.stopListening();
  342. super.onRemove();
  343. }
  344. }