zentap_game.dart 12 KB

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