User prompt
Please fix the bug: 'Timeout.tick error: undefined is not an object (evaluating 'garden.goalQueue[i].color')' in or related to this line: 'var goalColor = garden.goalQueue[i].color;' Line Number: 1839
User prompt
Please fix the bug: 'Script error.' in or related to this line: 'display.addChild(createGoalIndicator(goalQueue[0], true));' Line Number: 1782
User prompt
Please fix the bug: 'Script error.' in or related to this line: 'display.addChild(createGoalIndicator(goalQueue[0], true));' Line Number: 1782
User prompt
Replace updateFlowerCounts with this: self.updateFlowerCounts = function() { // Reset ONLY the number counts, not text references Object.keys(garden.currentFlowers).forEach(function(color) { if (typeof garden.currentFlowers[color] === 'number' && !color.includes('Text')) { garden.currentFlowers[color] = 0; } }); // Count all flowers in garden for (var row = 0; row < garden.rows; row++) { for (var col = 0; col < garden.cols; col++) { var item = garden.grid[row][col]; if (item && item.isFlower && !item.isSourceFlower) { garden.currentFlowers[item.color]++; } } } // Update display Object.keys(garden.flowerGoals).forEach(function(color) { if (garden.currentFlowers[color + "Text"]) { var currentCount = garden.currentFlowers[color]; var goalCount = garden.flowerGoals[color]; var text = garden.currentFlowers[color + "Text"]; // Check if goal met if (currentCount >= goalCount) { currentCount = goalCount; // Cap the display at goal amount // Create new green text var newText = new Text2(currentCount + "/" + goalCount, { size: 40, fill: 0x00FF00 }); newText.x = text.x; newText.y = text.y; text.parent.addChild(newText); text.parent.removeChild(text); garden.currentFlowers[color + "Text"] = newText; } else { text.setText(currentCount + "/" + goalCount); } } }); // Check for completed goals and cycle display if (garden.goalQueue && garden.goalQueue.length > 0) { for (var i = garden.goalDisplay.children.length - 1; i >= 0; i--) { var displayedGoal = garden.goalDisplay.children[i]; var goalColor = garden.goalQueue[i].color; if (garden.currentFlowers[goalColor] >= garden.flowerGoals[goalColor]) { // Create closure to capture correct index (function(index, goal) { // Animate out completed goal tween(goal, { alpha: 0, y: goal.y - 50 }, { duration: 500, onFinish: function() { garden.goalDisplay.removeChild(goal); // Remove from queue garden.goalQueue.splice(index, 1); // Add next goal if available if (garden.goalQueue.length > index) { var nextGoal = self.createGoalIndicator(garden.goalQueue[index], index === 0); nextGoal.alpha = 0; garden.goalDisplay.addChild(nextGoal); // Animate in tween(nextGoal, { alpha: 1 }, { duration: 500 }); } } }); })(i, displayedGoal); } } } // Check for spring mode completion var allGoalsMet = Object.keys(garden.flowerGoals).every(function(color) { return garden.currentFlowers[color] >= garden.flowerGoals[color]; }); };
Code edit (1 edits merged)
Please save this source code
User prompt
Move create goal indicator out of the create flower goal display function and make it its own function in season manager.
User prompt
// First make createGoalIndicator accessible to both functions self.createGoalIndicator = function(colorData, isLeft) { var row = new Container(); var flower = new BasicFlower(colorData.color); flower.scale.set(0.3); row.addChild(flower); var text = new Text2("0/" + colorData.goal, { size: 40, fill: 0xFFFFFF }); text.x = 60; text.y = -20; row.addChild(text); // Position based on side row.x = isLeft ? -200 : 200; // Store reference to text for updates garden.currentFlowers[colorData.color + "Text"] = text; return row; };
User prompt
Update as needed: self.createFlowerGoalDisplay = function() { var display = new Container(); // Create array of goals for tracking/cycling var goalQueue = Object.keys(garden.flowerGoals).map(function(color) { return { color: color, goal: garden.flowerGoals[color] }; }); // Function to create individual goal display var createGoalIndicator = function(colorData, isLeft) { var row = new Container(); var flower = new BasicFlower(colorData.color); flower.scale.set(0.3); row.addChild(flower); var text = new Text2("0/" + colorData.goal, { size: 40, fill: 0xFFFFFF }); text.x = 60; text.y = -20; row.addChild(text); // Position based on side row.x = isLeft ? -200 : 200; // Adjust these values as needed // Store reference to text for updates garden.currentFlowers[colorData.color + "Text"] = text; return row; }; // Initial setup - show first two goals if (goalQueue.length > 0) { display.addChild(createGoalIndicator(goalQueue[0], true)); } if (goalQueue.length > 1) { display.addChild(createGoalIndicator(goalQueue[1], false)); } // Position entire display near score display.x = 2048/2; // Center horizontally display.y = 100; // Near top by score // Store queue and display for updates garden.goalQueue = goalQueue; garden.goalDisplay = display; game.addChild(display); // Add directly to game instead of GUI };
User prompt
Update GameTimer as needed: self.updateDisplay = function() { var minutes = Math.floor(self.timeRemaining / 60); var seconds = self.timeRemaining % 60; var timeString = minutes + ":" + (seconds < 10 ? "0" : "") + seconds; // Create new text with appropriate color var newText = new Text2(timeString, { size: 120, fill: (self.timeRemaining <= 10) ? 0xFF0000 : 0xFFFFFF }); newText.anchor.set(0.5, 0); // Replace old text with new self.removeChild(timerText); self.addChild(newText); timerText = newText; };
User prompt
Updaye game timer as needed: self.updateDisplay = function() { var minutes = Math.floor(self.timeRemaining / 60); var seconds = self.timeRemaining % 60; timerText.setText(minutes + ":" + (seconds < 10 ? "0" : "") + seconds); // Since timeRemaining is now in seconds, we can check directly if (self.timeRemaining <= 10 && self.timeRemaining > 0) { // Added check for > 0 timerText.fill = 0xFF0000; } else { timerText.fill = 0xFFFFFF; } };
User prompt
Update GameTimer class with: var GameTimer = Container.expand(function () { var self = Container.call(this); var timerText = new Text2("0:00", { size: 120, fill: 0xFFFFFF }); timerText.anchor.set(0.5, 0); self.addChild(timerText); self.x = 2048/2; self.y = 2732 - 200; self.timeRemaining = 0; self.active = false; self.lastTick = 0; // Add this to track last update self.setTime = function(seconds) { self.timeRemaining = seconds; self.active = true; self.lastTick = LK.ticks; // Initialize lastTick self.updateDisplay(); }; self.updateDisplay = function() { var minutes = Math.floor(self.timeRemaining / 60); var seconds = self.timeRemaining % 60; timerText.setText(minutes + ":" + (seconds < 10 ? "0" : "") + seconds); if (self.timeRemaining <= 10) { timerText.fill = 0xFF0000; } else { timerText.fill = 0xFFFFFF; } }; self.update = function() { if (self.active && self.timeRemaining > 0) { // Only update if 60 ticks have passed since last update if (LK.ticks - self.lastTick >= 60) { self.timeRemaining--; self.lastTick = LK.ticks; self.updateDisplay(); } } }; return self; });
User prompt
Game timer is updating twice a second. Debug
User prompt
Game timer is being updated too frequently. Should only be once a second.
User prompt
Make sure gametimer counts down by 1
User prompt
Update as needed: var timerText = new Text2("0:00", { size: 120, // Increased from 80 fill: 0xFFFFFF }); timerText.anchor.set(0.5, 0); self.addChild(timerText); self.x = 2048/2; self.y = 2732 - 200; // Changed from -300 to -200 to move it lower
User prompt
Update as needed: if (game.gameTimer.timeRemaining <= 0 || fullyPollinated) { // Check if goals are met var goalsMet = Object.keys(garden.flowerGoals).every(function (color) { return garden.currentFlowers[color] >= garden.flowerGoals[color]; }); // ... }
User prompt
/ Remove this cleanup code from startSpringFinale: if (self.springTimerDisplay && self.springTimerDisplay.parent) { self.springTimerDisplay.parent.removeChild(self.springTimerDisplay); }
User prompt
Remove old timer from initspringmode
User prompt
Remove timer update code from spring season update code
Code edit (1 edits merged)
Please save this source code
User prompt
Update as needed: self.initSpringMode = function() { if (!game.gameTimer) { game.gameTimer = new GameTimer(); game.addChild(game.gameTimer); } // Set spring timer game.gameTimer.setTime(60); // 60 seconds
User prompt
Add this: var GameTimer = Container.expand(function () { var self = Container.call(this); var timerText = new Text2("0:00", { size: 80, fill: 0xFFFFFF }); timerText.anchor.set(0.5, 0); self.addChild(timerText); self.x = 2048/2; self.y = 2732 - 300; self.timeRemaining = 0; self.active = false; self.setTime = function(seconds) { self.timeRemaining = seconds; self.active = true; self.updateDisplay(); }; self.updateDisplay = function() { var minutes = Math.floor(self.timeRemaining / 60); var seconds = self.timeRemaining % 60; timerText.setText(minutes + ":" + (seconds < 10 ? "0" : "") + seconds); if (self.timeRemaining <= 10) { timerText.fill = 0xFF0000; } else { timerText.fill = 0xFFFFFF; } }; self.update = function() { if (self.active && self.timeRemaining > 0 && LK.ticks % 60 === 0) { self.timeRemaining--; self.updateDisplay(); } }; return self; });
User prompt
Please fix the bug: 'Script error.' in or related to this line: 'timerText.y = blueFlower.y + 100; // 100 pixels below blue flower' Line Number: 1647
User prompt
Update spring timer as needed: timerText.anchor.set(0.5, 0); timerText.x = 2048/2; timerText.y = blueFlower.y + 100; // 100 pixels below blue flower game.addChild(timerText);
Code edit (1 edits merged)
Please save this source code
/**** 
* Plugins
****/ 
var tween = LK.import("@upit/tween.v1");
/**** 
* Classes
****/ 
var BasicFlower = Container.expand(function (color) {
	var self = Container.call(this);
	// Store flower color
	self.color = color || 'red'; // Default to red if no color specified
	// Map color to asset name
	var assetMap = {
		'red': 'RedFlower',
		'blue': 'BlueFlower',
		'yellow': 'YellowFlower',
		'purple': 'PurpleFlower',
		'green': 'GreenFlower',
		'orange': 'OrangeFlower'
	};
	// Attach bud asset first
	var budGraphics = self.attachAsset('Bud', {
		anchorX: 0.5,
		anchorY: 0.5
	});
	// Use correct asset based on color
	var flowerGraphics = self.attachAsset(assetMap[self.color], {
		anchorX: 0.5,
		anchorY: 0.5
	});
	self.hasActivePollen = false;
	self.fairyParticles = [];
	self.FAIRY_COUNT = 3;
	self.update = function () {
		var scaleFactor = 1 + Math.sin(LK.ticks * 0.1) * 0.05;
		flowerGraphics.scale.x = scaleFactor;
		flowerGraphics.scale.y = scaleFactor;
		flowerGraphics.rotation = Math.sin(LK.ticks * 0.1) * 0.05;
	};
	self.bloom = function () {
		// Scale animation
		self.scale.set(0.3, 0.3);
		tween(self.scale, {
			x: 1,
			y: 1
		}, {
			duration: 1000,
			onFinish: function onFinish() {
				// Set active pollen state before checking matches
				self.hasActivePollen = true;
				self.pollenCollected = false;
				// Find position in grid
				var foundGridPos = false;
				var gridX = 0;
				var gridY = 0;
				for (var y = 0; y < garden.rows; y++) {
					for (var x = 0; x < garden.cols; x++) {
						if (garden.grid[y][x] === self) {
							gridX = x;
							gridY = y;
							foundGridPos = true;
							break;
						}
					}
					if (foundGridPos) {
						break;
					}
				}
				// Check for matches after bloom completes
				if (foundGridPos && game.flowerMatcher) {
					LK.setTimeout(function () {
						game.flowerMatcher.checkForMatches(garden, gridX, gridY);
					}, 100); // Short delay to ensure animation completes
				}
			}
		});
		LK.setTimeout(function () {
			if (game.seasonManager && game.seasonManager.currentSeason === game.seasonManager.SEASONS.SPRING) {
				game.seasonManager.updateFlowerCounts();
			}
		}, 1000); // After bloom animation
		// Create initial burst particles
		self.createPollenBurst(self.x, self.y);
		self.removeFairyParticles = function () {
			self.fairyParticles.forEach(function (fairy) {
				self.removeChild(fairy);
			});
			self.fairyParticles = [];
		};
	};
	self.createPollenBurst = function (x, y) {
		for (var i = 0; i < 12; i++) {
			var particle = new PollenParticle().init('burst');
			var angle = i / 12 * Math.PI * 2;
			particle.x = x;
			particle.y = y;
			particle.vx = Math.cos(angle) * 3;
			particle.vy = Math.sin(angle) * 3;
			if (self.parent) {
				self.parent.addChild(particle);
			}
		}
	};
	// Initialize pollen status
	self.pollenCollected = true; // Set to true so pollen can't be collected
});
var Bee = Container.expand(function () {
	var self = Container.call(this);
	self.currentColor = null; // Add this back
	// Movement properties 
	var beeSprite = self.attachAsset('Bee', {
		anchorX: 0.5,
		anchorY: 0.5
	});
	// Movement properties
	self.state = 'free'; // 'free', 'transit'
	self.targetX = self.x;
	self.targetY = self.y;
	self.transitSpeed = 15; // Set bee transit speed to 15 
	self.arrivalThreshold = 20; // How close we need to be to count as "arrived"
	self.moveSpeed = 0.1; // Adjust this for faster/slower following
	self.isMoving = false;
	// New pollen properties
	self.maxPollen = 14; // Exactly enough for 2 buds (2 * 7 = 14)
	self.currentPollen = 0; // Current amount being carried
	self.pollenTypes = []; // Array to track different pollen colors
	// Format: [{color: 'red', amount: 30}, ...]
	// Add trail property
	self.pollenTrail = new PollenTrail();
	game.addChild(self.pollenTrail); // Add to game so it renders behind bee
	// Pollen collection method
	self.collectPollen = function (flower) {
		if (!flower.isSourceFlower) {
			return;
		} // Only proceed if it's a source flower
		if (flower.isSourceFlower) {
			// Add color mixing check before any other collection logic
			if (self.currentColor && self.currentColor !== flower.color) {
				var mixColor;
				if (self.currentColor === 'red' && flower.color === 'blue' || self.currentColor === 'blue' && flower.color === 'red') {
					mixColor = 'purple';
				} else if (self.currentColor === 'blue' && flower.color === 'yellow' || self.currentColor === 'yellow' && flower.color === 'blue') {
					mixColor = 'green';
				} else if (self.currentColor === 'red' && flower.color === 'yellow' || self.currentColor === 'yellow' && flower.color === 'red') {
					mixColor = 'orange';
				}
				if (mixColor) {
					self.pollenTypes = [{
						color: mixColor,
						amount: 14
					}];
					self.currentPollen = 14;
					self.currentColor = mixColor;
					self.pollenTrail.currentColor = mixColor;
					return;
				}
			} else if (self.currentPollen < self.maxPollen) {
				// Set color first before any other changes
				self.currentColor = flower.color;
				self.pollenTrail.currentColor = flower.color;
				var collectAmount = Math.min(14, self.maxPollen - self.currentPollen);
				self.pollenTypes = [{
					color: flower.color,
					amount: collectAmount
				}];
				self.currentPollen = collectAmount;
			}
			// Only restart trail if we still have pollen
			if (self.currentPollen > 0) {
				if (self.pollenTrail) {
					self.pollenTrail.active = false;
					self.pollenTrail.startTrail(self.x, self.y, garden, self);
				}
			}
		}
	};
	self.checkFlowerCollision = function () {
		if (self.state === 'transit') {
			return;
		} // Skip collision check during transit
		// Convert bee position to garden's local space
		var localPos = garden.toLocal({
			x: self.x,
			y: self.y
		}, game);
		// Check source flowers first
		if (garden.sourceFlowers) {
			garden.sourceFlowers.children.forEach(function (flower) {
				var dx = localPos.x - flower.x;
				var dy = localPos.y - flower.y;
				var distance = Math.sqrt(dx * dx + dy * dy);
				if (distance < garden.cellSize / 2 && !flower.isBeingCollectedFrom) {
					flower.isBeingCollectedFrom = true;
					self.collectPollen(flower);
				} else if (distance >= garden.cellSize / 2) {
					flower.isBeingCollectedFrom = false;
				}
			});
		}
		// Calculate grid position
		var gridX = Math.floor(localPos.x / garden.cellSize);
		var gridY = Math.floor(localPos.y / garden.cellSize);
		// Check if position is within grid bounds
		if (gridX >= 0 && gridX < garden.cols && gridY >= 0 && gridY < garden.rows) {
			var gridItem = garden.grid[gridY][gridX];
			if (gridItem) {
				if (gridItem.isFlower && gridItem.hasActivePollen && gridItem.scale.x >= 1 && gridItem.color === self.currentColor) {
					// Collect pollen from flower
					self.collectPollen(gridItem);
				} else if (gridItem && gridItem.isBud && self.currentPollen > 0) {
					if (gridItem.isBeingPollinated) {
						return;
					}
					gridItem.isBeingPollinated = true;
					var pollenColor = self.usePollen(gridItem);
					if (!pollenColor) {
						gridItem.isBeingPollinated = false;
						return;
					}
					// Double-check the bud is still there
					if (garden.grid[gridY][gridX] === gridItem && gridItem.isBud) {
						// Force remove the bud and clear grid position
						garden.removeChild(gridItem);
						garden.grid[gridY][gridX] = null;
						gridItem.destroy(); // Fully destroy the bud
						// Only create flower if position is clear
						if (!garden.grid[gridY][gridX]) {
							var newFlower = new BasicFlower(pollenColor);
							newFlower.x = gridItem.x;
							newFlower.y = gridItem.y;
							newFlower.isFlower = true;
							garden.grid[gridY][gridX] = newFlower;
							garden.addChild(newFlower);
							newFlower.bloom();
						}
					} else {
						gridItem.isBeingPollinated = false;
					}
				}
			}
		}
	};
	self.checkDestinationInteraction = function () {
		// Convert bee position to garden's local space
		var localPos = garden.toLocal({
			x: self.x,
			y: self.y
		}, game);
		// Check source flowers
		if (garden.sourceFlowers) {
			garden.sourceFlowers.children.forEach(function (flower) {
				var dx = localPos.x - flower.x;
				var dy = localPos.y - flower.y;
				var distance = Math.sqrt(dx * dx + dy * dy);
				if (distance < garden.cellSize / 2) {
					self.collectPollen(flower);
				}
			});
		}
		// Check grid position for buds
		var gridX = Math.floor(localPos.x / garden.cellSize);
		var gridY = Math.floor(localPos.y / garden.cellSize);
		if (gridX >= 0 && gridX < garden.cols && gridY >= 0 && gridY < garden.rows) {
			var gridItem = garden.grid[gridY][gridX];
			if (gridItem && gridItem.isBud && self.currentPollen > 0) {
				self.checkFlowerCollision(); // Use existing collision logic
			}
		}
	};
	self.update = function () {
		if (self.state === 'free' && self.isMoving) {
			// Existing drag behavior
			self.x += (self.targetX - self.x) * self.moveSpeed;
			self.y += (self.targetY - self.y) * self.moveSpeed;
		} else if (self.state === 'transit') {
			var dx = self.targetX - self.x;
			var dy = self.targetY - self.y;
			var distance = Math.sqrt(dx * dx + dy * dy);
			if (distance > self.arrivalThreshold) {
				// Normalize movement vector
				var angle = Math.atan2(dy, dx);
				self.x += Math.cos(angle) * self.transitSpeed;
				self.y += Math.sin(angle) * self.transitSpeed;
			} else {
				// We've arrived - check for interactions
				self.checkDestinationInteraction();
				self.state = 'free';
			}
		}
		// Calculate rotation based on movement direction
		var dx = self.targetX - self.x;
		var dy = self.targetY - self.y;
		var angle = Math.atan2(dy, dx);
		self.rotation = angle + Math.PI / 2;
		// Update trail when carrying pollen
		if (self.currentPollen > 0) {
			// Make sure trail starts if not already active
			if (!self.pollenTrail.active) {
				self.pollenTrail.startTrail(self.x, self.y, garden);
			}
			self.pollenTrail.updateTrail(self.x, self.y);
		}
		// Add collision check
		self.checkFlowerCollision();
	};
	// Pollen usage method
	self.usePollen = function (bud) {
		// Add debug logs
		var pollenUsed = 7;
		if (self.currentPollen > 0 && self.pollenTypes.length > 0) {
			// If we have less than pollenUsed, use remaining pollen
			if (self.currentPollen < pollenUsed) {
				pollenUsed = self.currentPollen;
			}
			// Reduce pollen instead of zeroing it
			self.currentPollen -= pollenUsed;
			// Update pollen types properly
			var pType = self.pollenTypes[0];
			var color = pType.color; // New line to store color
			pType.amount -= pollenUsed;
			if (self.currentPollen <= 0) {
				self.pollenTypes = []; // Clear all pollen types when empty
			}
			// Removed bee UI update call
			// Only clear type if it's empty
			if (pType.amount <= 0) {
				self.pollenTypes.shift();
			}
			// Only end trail if we're actually out of pollen
			if (self.currentPollen <= 0 || self.pollenTypes.length === 0) {
				self.pollenTrail.active = false;
				self.pollenTrail.points = [];
				// Reset bee's pollen state
				self.currentColor = null;
				self.pollenTypes = [];
			}
			return color; // Updated to return color
		}
		return null;
	};
	return self;
});
// Bud class
var Bud = Container.expand(function () {
	var self = Container.call(this);
	var budGraphics = self.attachAsset('Bud', {
		anchorX: 0.5,
		anchorY: 0.5
	});
	// Timer properties
	self.bloomTimer = 5 * 60; // 5 seconds (assuming 60fps)
	self.isBud = true;
	self.isFlower = false;
	self.isBeingReplaced = false; // Add this flag
	// Update now handles timer and auto-bloom
	self.update = function () {
		// Basic animation
		self.rotation = Math.sin(LK.ticks * 0.05) * 0.1;
	};
	self.autoBloom = function () {
		if (!self.isBud || self.isBeingReplaced) {
			return; // Prevent double-blooming or if already being replaced
		}
		self.isBeingReplaced = true;
		// Get garden reference from parent
		var garden = self.parent;
		if (!garden) {
			return;
		}
		// Get grid position directly from garden
		for (var gridY = 0; gridY < garden.rows; gridY++) {
			for (var gridX = 0; gridX < garden.cols; gridX++) {
				if (garden.grid[gridY][gridX] === self) {
					// Create random color flower
					var flowerColors = ['red', 'blue', 'yellow'];
					var randomColor = flowerColors[Math.floor(Math.random() * flowerColors.length)];
					var newFlower = new BasicFlower(randomColor);
					newFlower.x = self.x;
					newFlower.y = self.y;
					newFlower.isFlower = true;
					newFlower.hasActivePollen = false;
					// Update grid
					garden.removeChild(self);
					garden.grid[gridY][gridX] = newFlower;
					garden.addChild(newFlower);
					newFlower.bloom();
					return;
				}
			}
		}
	};
	return self;
});
// Add BudSpawner to handle progressive difficulty
var BudSpawner = Container.expand(function () {
	var self = Container.call(this);
	self.enabled = true;
	self.patterns = {
		single: [[[0, 0]]],
		pairs: [[[0, 0], [0, 1]],
		// horizontal
		[[0, 0], [1, 0]],
		// vertical
		[[0, 0], [1, 1]] // diagonal
		],
		triples: [[[0, 0], [0, 1], [0, 2]],
		// horizontal
		[[0, 0], [1, 0], [2, 0]],
		// vertical
		[[0, 0], [1, 1], [2, 2]],
		// diagonal
		[[0, 0], [0, 1], [1, 0]] // L shape
		]
	};
	self.warningTime = 180; // 3 seconds at 60fps
	self.currentPattern = null;
	self.warningSprites = [];
	self.nextSpawnPosition = null;
	self.createWarning = function (x, y) {
		var warning = new Container();
		var crack = warning.attachAsset('Crack', {
			anchorX: 0.5,
			anchorY: 0.5,
			alpha: 0
		});
		warning.x = x;
		warning.y = y;
		warning.scale.set(0);
		// Create the growing crack animation
		tween(warning.scale, {
			x: 1,
			y: 1
		}, {
			duration: 1000,
			ease: 'elasticOut'
		});
		tween(crack, {
			alpha: 0.8
		}, {
			duration: 500
		});
		// Add rotation animation
		warning.update = function () {
			warning.rotation = Math.sin(LK.ticks * 0.03) * 0.1;
		};
		self.garden.addChild(warning);
		return warning;
	};
	self.updateWarningEffects = function () {
		var timeProgress = (180 - self.warningTime) / 180; // 0 to 1
		var intensity = Math.sin(timeProgress * Math.PI * 4) * 0.5 + 0.5; // Pulsing effect
		self.warningSprites.forEach(function (sprite) {
			// Increase glow and intensity as spawn time approaches
			sprite.children[0].alpha = 0.3 + intensity * 0.7;
			sprite.children[0].scale.set(0.8 + intensity * 0.4);
			// Add subtle shake when close to spawning
			if (self.warningTime < 60) {
				// Last second
				sprite.x += (Math.random() - 0.5) * 2;
				sprite.y += (Math.random() - 0.5) * 2;
			}
		});
	};
	self.garden = null;
	self.gameTime = 0;
	self.init = function (garden) {
		self.garden = garden;
		self.gameTime = 0;
		self.firstBloom = false;
		// Just set the first bloom timer
		self.nextBloomTime = 90; // 1.5 seconds for first bloom
	};
	self.findEmptySpot = function () {
		var validSpots = [];
		// Match flower removal coordinate system [gridY][gridX]
		for (var gridY = 0; gridY < self.garden.rows; gridY++) {
			for (var gridX = 0; gridX < self.garden.cols; gridX++) {
				if (!self.garden.grid[gridY][gridX]) {
					validSpots.push({
						x: gridX,
						y: gridY
					});
				}
			}
		}
		if (validSpots.length > 0) {
			return validSpots[Math.floor(Math.random() * validSpots.length)];
		}
		return null;
	};
	self.selectSpawnPosition = function () {
		// Count empty spaces
		var emptySpaces = 0;
		var emptyPositions = [];
		for (var row = 0; row < self.garden.rows; row++) {
			for (var col = 0; col < self.garden.cols; col++) {
				if (self.garden.grid[row][col] === null) {
					emptySpaces++;
					emptyPositions.push({
						row: row,
						col: col
					});
				}
			}
		}
		// No empty spaces
		if (emptySpaces === 0) {
			return null;
		}
		// Select pattern size based on empty spaces
		var patternPool;
		if (emptySpaces >= 3) {
			patternPool = Math.random() < 0.7 ? self.patterns.triples : self.patterns.pairs;
		} else if (emptySpaces >= 2) {
			patternPool = Math.random() < 0.7 ? self.patterns.pairs : self.patterns.single;
		} else {
			patternPool = self.patterns.single;
		}
		// Find valid positions for selected pattern pool
		var validPositions = [];
		for (var _i = 0, _emptyPositions = emptyPositions; _i < _emptyPositions.length; _i++) {
			var _emptyPositions$_i = _emptyPositions[_i],
				row = _emptyPositions$_i.row,
				col = _emptyPositions$_i.col;
			var _iterator = _createForOfIteratorHelper6(patternPool),
				_step;
			try {
				patternCheck: for (_iterator.s(); !(_step = _iterator.n()).done;) {
					var pattern = _step.value;
					// Check if pattern fits at this position
					var _iterator2 = _createForOfIteratorHelper6(pattern),
						_step2;
					try {
						for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
							var _step2$value = _slicedToArray7(_step2.value, 2),
								drow = _step2$value[0],
								dcol = _step2$value[1];
							var nrow = row + drow;
							var ncol = col + dcol;
							if (nrow >= self.garden.rows || ncol >= self.garden.cols || self.garden.grid[nrow][ncol] !== null) {
								continue patternCheck;
							}
						}
					} catch (err) {
						_iterator2.e(err);
					} finally {
						_iterator2.f();
					}
					validPositions.push({
						row: row,
						col: col,
						pattern: pattern
					});
				}
			} catch (err) {
				_iterator.e(err);
			} finally {
				_iterator.f();
			}
		}
		// If no patterns fit, fall back to single bud
		if (validPositions.length === 0 && emptySpaces > 0) {
			var randomEmpty = emptyPositions[Math.floor(Math.random() * emptyPositions.length)];
			return {
				row: randomEmpty.row,
				col: randomEmpty.col,
				pattern: self.patterns.single[0]
			};
		}
		return validPositions.length > 0 ? validPositions[Math.floor(Math.random() * validPositions.length)] : null;
	};
	self.getSpawnRate = function () {
		// Keep original timing logic
		return 16; // Spawn every frame for immediate filling
	};
	self.update = function () {
		if (!self.enabled) {
			return;
		}
		// Initialize timing trackers
		if (!self.lastSpawnTime) {
			self.lastSpawnTime = LK.ticks;
			self.isFirstSpawn = true;
		}
		// Quick first spawn (2 seconds), then 5 seconds for subsequent spawns
		if (!self.currentPattern) {
			var requiredDelay = self.isFirstSpawn ? 120 : 240; // 2 seconds vs 4 seconds 
			if (LK.ticks - self.lastSpawnTime < requiredDelay) {
				return;
			}
			// Update spawn time and first spawn flag
			self.lastSpawnTime = LK.ticks;
			self.isFirstSpawn = false;
			// Select new spawn position and pattern
			var spawnInfo = self.selectSpawnPosition();
			if (spawnInfo && spawnInfo.row !== undefined && spawnInfo.col !== undefined) {
				self.currentPattern = spawnInfo.pattern;
				self.nextSpawnPosition = {
					row: parseInt(spawnInfo.row),
					col: parseInt(spawnInfo.col)
				};
				self.warningTime = 180; // Reset warning timer
				// Create warning indicators for pattern
				self.warningSprites = [];
				if (self.currentPattern) {
					var _iterator3 = _createForOfIteratorHelper4(self.currentPattern),
						_step3;
					try {
						for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
							var _step3$value = _slicedToArray5(_step3.value, 2),
								dy = _step3$value[0],
								dx = _step3$value[1];
							if (dx !== undefined && dy !== undefined) {
								var targetRow = self.nextSpawnPosition.row + dy;
								var targetCol = self.nextSpawnPosition.col + dx;
								var worldPos = self.garden.gridToWorld(targetCol, targetRow);
								var warning = self.createWarning(worldPos.x - 400 + self.garden.cellSize, worldPos.y - 400 - 50);
								self.warningSprites.push(warning);
							}
						}
					} catch (err) {
						_iterator3.e(err);
					} finally {
						_iterator3.f();
					}
				}
			}
		} else if (self.nextSpawnPosition && self.currentPattern) {
			self.warningTime--;
			self.updateWarningEffects();
			if (self.warningTime <= 0) {
				// Spawn animation
				self.warningSprites.forEach(function (sprite) {
					tween(sprite.scale, {
						x: 1,
						y: 1
					}, {
						duration: 300,
						onFinish: function onFinish() {
							tween(sprite, {
								alpha: 0
							}, {
								duration: 200,
								onFinish: function onFinish() {
									return sprite.destroy();
								}
							});
						}
					});
				});
				// Cache spawn position before clearing
				var spawnRow = self.nextSpawnPosition.row;
				var spawnCol = self.nextSpawnPosition.col;
				var pattern = self.currentPattern;
				// Clear state before spawning to prevent timing issues
				self.warningSprites = [];
				self.currentPattern = null;
				self.nextSpawnPosition = null;
				// Spawn buds with delay between each
				pattern.forEach(function (pos, index) {
					var _pos = _slicedToArray8(pos, 2),
						dy = _pos[0],
						dx = _pos[1];
					LK.setTimeout(function () {
						var targetRow = spawnRow + dy;
						var targetCol = spawnCol + dx;
						if (targetRow >= 0 && targetRow < self.garden.rows && targetCol >= 0 && targetCol < self.garden.cols && !self.garden.grid[targetRow][targetCol]) {
							var newBud = new Bud();
							var worldPos = self.garden.gridToWorld(targetCol, targetRow);
							newBud.x = worldPos.x - 400 + self.garden.cellSize;
							newBud.y = worldPos.y - 400 - 50;
							newBud.scale.set(0);
							self.garden.grid[targetRow][targetCol] = newBud;
							self.garden.addChild(newBud);
							// Only set up auto-bloom for patterns with multiple buds 
							if (pattern.length > 1 && index === 0) {
								LK.setTimeout(function () {
									if (newBud && newBud.parent && newBud.isBud && !newBud.isBeingReplaced) {
										newBud.autoBloom();
										// When first bud blooms, start timer for second bud 
										if (pattern[1]) {
											LK.setTimeout(function () {
												var secondBud = self.garden.grid[spawnRow + pattern[1][0]][spawnCol + pattern[1][1]];
												if (secondBud && secondBud.isBud && !secondBud.isBeingReplaced) {
													secondBud.autoBloom();
													// When second bud blooms, start timer for third bud 
													if (pattern[2]) {
														LK.setTimeout(function () {
															var thirdBud = self.garden.grid[spawnRow + pattern[2][0]][spawnCol + pattern[2][1]];
															if (thirdBud && thirdBud.isBud && !thirdBud.isBeingReplaced) {
																thirdBud.autoBloom();
															}
														}, 6000); // 6 seconds after second bud 
													}
												}
											}, 6000); // 6 seconds after first bud 
										}
									}
								}, 3000); // 3 seconds for first bud 
							}
							// Then do scale animation 
							tween(newBud.scale, {
								x: 1,
								y: 1
							}, {
								duration: 1000,
								ease: 'elasticOut'
							});
						}
					}, index * 200);
				});
			}
		}
	};
});
// Simplified FlowerManager - mainly for flower conversion and management
var FlowerManager = Container.expand(function () {
	var self = Container.call(this);
	// Convert a bud to a flower
	self.convertBudToFlower = function (bud, garden) {
		var gridPos = {
			x: Math.floor((bud.y - garden.y) / garden.cellSize),
			y: Math.floor((bud.x - garden.x) / garden.cellSize)
		};
		var newFlower = new BasicFlower();
		newFlower.x = bud.x;
		newFlower.y = bud.y;
		newFlower.isFlower = true;
		garden.removeChild(bud);
		garden.grid[gridPos.x][gridPos.y] = newFlower;
		garden.addChild(newFlower);
		// When a flower blooms:
		createPollenBurst(newFlower.x, newFlower.y);
		return newFlower;
	};
	// Empty touch handler as we're using the new trail system
	self.handleTouch = function () {};
});
var FlowerMatcher = Container.expand(function () {
	var self = Container.call(this);
	self.checkForMatches = function (garden, x, y) {
		console.log("Checking matches at:", x, y);
		// Only prevent matches in spring if we're not in the matching phase
		if (game.seasonManager && game.seasonManager.currentSeason === game.seasonManager.SEASONS.SPRING && !game.seasonManager.springMatchingEnabled) {
			return false;
		}
		var matches = self.findMatches(garden, x, y);
		if (matches.length >= 3) {
			console.log("Found matches:", matches.length);
			// Immediately clear ALL matched flowers from grid
			matches.forEach(function (match) {
				if (garden.grid[match.y][match.x] === match.flower) {
					garden.grid[match.y][match.x] = null;
				}
			});
			// Pass matches to clearMatches for animation and scoring
			self.clearMatches(garden, matches, true);
			return true;
		}
		return false;
	};
	self.findMatches = function (garden, startX, startY) {
		if (startY < 0 || startY >= garden.rows || startX < 0 || startX >= garden.cols) {
			return [];
		}
		var startFlower = garden.grid[startY][startX];
		if (!startFlower || !startFlower.isFlower) {
			return [];
		}
		var flowerColor = startFlower.color;
		var matches = [];
		var visited = {};
		var _checkFlower = function checkFlower(x, y) {
			if (x < 0 || x >= garden.cols || y < 0 || y >= garden.rows) {
				return;
			}
			var key = x + ',' + y;
			if (visited[key]) {
				return;
			}
			visited[key] = true;
			var flower = garden.grid[y][x];
			if (flower && flower.isFlower && !flower.isSourceFlower && flower.scale.x >= 1 && flower.color === flowerColor) {
				matches.push({
					x: x,
					y: y,
					flower: flower
				});
				_checkFlower(x + 1, y);
				_checkFlower(x - 1, y);
				_checkFlower(x, y + 1);
				_checkFlower(x, y - 1);
			}
		};
		_checkFlower(startX, startY);
		return matches.length >= 3 ? matches : [];
	};
	self.clearMatches = function (garden, matches, startNewChain) {
		if (game.scoreManager && startNewChain) {
			game.scoreManager.addToChain();
		}
		matches.forEach(function (match, index) {
			var flower = match.flower;
			var flowerPoints = game.scoreManager ? game.scoreManager.getFlowerBasePoints(flower.color) : 100;
			var pointText = new Text2("+" + (flowerPoints || 0), {
				size: 100,
				fill: 0xFFFF00
			});
			LK.setTimeout(function () {
				tween(flower.scale, {
					x: 1.5,
					y: 1.5
				}, {
					duration: 300,
					onFinish: function onFinish() {
						tween(flower, {
							alpha: 0
						}, {
							duration: 200,
							onFinish: function onFinish() {
								if (garden.grid[match.y][match.x] === flower) {
									garden.grid[match.y][match.x] = null;
									garden.removeChild(flower);
								}
								// Second: Particles after pop completes
								self.createPetalBurst(match.x, match.y, match.flower.color);
								// Third: Show points for this flower
								var worldPos = garden.gridToWorld(match.x, match.y);
								var pointText = new Text2("+" + flowerPoints, {
									size: 100,
									fill: 0xFFFF00
								});
								pointText.anchor.set(0.5);
								pointText.x = worldPos.x;
								pointText.y = worldPos.y;
								game.addChild(pointText);
								tween(pointText, {
									y: pointText.y - 50,
									alpha: 0
								}, {
									duration: 1000,
									onFinish: function onFinish() {
										pointText.destroy();
									}
								});
							}
						});
					}
				});
			}, index * 150);
		});
		// After all flowers, show total score
		LK.setTimeout(function () {
			if (game.scoreManager) {
				// Calculate total with multipliers
				var totalBase = matches.reduce(function (sum, m) {
					return sum + (game.scoreManager ? game.scoreManager.getFlowerBasePoints(m.flower.color) : 100);
				}, 0);
				var matchMultiplier = game.scoreManager ? game.scoreManager.getMatchMultiplier(matches.length) : 1;
				var chainMultiplier = game.scoreManager ? game.scoreManager.chainMultiplier : 1;
				var finalScore = Math.floor(totalBase * matchMultiplier * chainMultiplier);
				// Show final score floating up
				var totalText = new Text2("+" + finalScore, {
					size: 150,
					fill: 0x00FFFF
				});
				totalText.anchor.set(0.5);
				totalText.x = 2048 / 2;
				totalText.y = 2732 / 2;
				game.addChild(totalText);
				tween(totalText, {
					y: 100,
					alpha: 0
				}, {
					duration: 1500,
					onFinish: function onFinish() {
						totalText.destroy();
						game.scoreManager.addScore(finalScore);
					}
				});
				// First only show match multiplier if it's greater than 1
				if (matchMultiplier > 1) {
					var multiplierText = new Text2("Match x" + matchMultiplier.toFixed(1), {
						size: 120,
						fill: 0x00FFFF
					});
					multiplierText.anchor.set(0.5);
					multiplierText.x = 2048 / 2;
					multiplierText.y = 2732 / 2 + 100;
					game.addChild(multiplierText);
					tween(multiplierText, {
						y: multiplierText.y - 50,
						alpha: 0
					}, {
						duration: 1200,
						onFinish: function onFinish() {
							multiplierText.destroy();
						}
					});
				}
				// Separate chain display only if there's an active chain
				if (game.scoreManager.chainMultiplier > 1) {
					var chainText = new Text2("Chain x" + game.scoreManager.chainMultiplier.toFixed(1), {
						size: 120,
						fill: 0x00FFFF
					});
					chainText.anchor.set(0.5);
					chainText.x = 2048 / 2;
					chainText.y = 2732 / 2 + 150; // Position below match multiplier
					game.addChild(chainText);
					tween(chainText, {
						y: chainText.y - 50,
						alpha: 0
					}, {
						duration: 1200,
						onFinish: function onFinish() {
							chainText.destroy();
						}
					});
				}
			}
		}, matches.length * 150 + 1000);
	};
	self.createPetalBurst = function (x, y, color) {
		var colorTints = {
			'red': 0xFF0000,
			'blue': 0x0000FF,
			'yellow': 0xFFFF00,
			'purple': 0x800080,
			'orange': 0xFFA500,
			'green': 0x00FF00
		};
		var worldPos = garden.gridToWorld(x, y);
		for (var i = 0; i < 12; i++) {
			var particle = new PollenParticle().init('burst');
			var angle = i / 12 * Math.PI * 2;
			particle.x = worldPos.x;
			particle.y = worldPos.y;
			particle.vx = Math.cos(angle) * 8;
			particle.vy = Math.sin(angle) * 8;
			particle.scale.set(0.8);
			particle.tint = colorTints[color];
			game.addChild(particle);
		}
		// Star particles
		for (var i = 0; i < 8; i++) {
			var star = new PollenParticle().init('star');
			var angle = i / 8 * Math.PI * 2;
			star.x = worldPos.x;
			star.y = worldPos.y;
			game.addChild(star);
		}
	};
	return self;
});
var GameTimer = Container.expand(function () {
	var self = Container.call(this);
	var timerText = new Text2("0:00", {
		size: 120,
		fill: 0xFFFFFF
	});
	timerText.anchor.set(0.5, 0);
	self.addChild(timerText);
	self.x = 2048 / 2;
	self.y = 2732 - 200;
	self.timeRemaining = 0;
	self.active = false;
	self.lastTick = 0; // Add this to track last update
	self.setTime = function (seconds) {
		self.timeRemaining = seconds;
		self.active = true;
		self.lastTick = LK.ticks; // Initialize lastTick
		self.updateDisplay();
	};
	self.updateDisplay = function () {
		var minutes = Math.floor(self.timeRemaining / 60);
		var seconds = self.timeRemaining % 60;
		var timeString = minutes + ":" + (seconds < 10 ? "0" : "") + seconds;
		// Create new text with appropriate color
		var newText = new Text2(timeString, {
			size: 120,
			fill: self.timeRemaining <= 10 ? 0xFF0000 : 0xFFFFFF
		});
		newText.anchor.set(0.5, 0);
		// Replace old text with new
		self.removeChild(timerText);
		self.addChild(newText);
		timerText = newText;
	};
	self.update = function () {
		if (self.active && self.timeRemaining > 0) {
			// Only update if 60 ticks have passed since last update
			if (LK.ticks - self.lastTick >= 60) {
				self.timeRemaining--;
				self.lastTick = LK.ticks;
				self.updateDisplay();
			}
		}
	};
	return self;
});
//<Assets used in the game will automatically appear here>
// Garden class to manage the grid of soil
var Garden = Container.expand(function () {
	var self = Container.call(this);
	// Add new helper method for safe grid updates
	self.updateGridPosition = function (row, col, item) {
		if (row >= 0 && row < self.rows && col >= 0 && col < self.cols) {
			// First clear any existing item
			var existingItem = self.grid[row][col];
			if (existingItem && existingItem.parent) {
				existingItem.parent.removeChild(existingItem);
			}
			// Then set new item
			self.grid[row][col] = item;
			return true;
		}
		return false;
	};
	self.grid = [];
	self.rows = 8;
	self.cols = 8;
	self.cellSize = 210;
	self.init = function () {
		var _this = this;
		// Add source flowers
		this.sourceFlowers = new Container();
		this.addChild(this.sourceFlowers);
		// Calculate positions
		var centerX = this.cols * this.cellSize / 2;
		// Blue flower at bottom center
		var blueFlower = new SourceFlower('blue');
		blueFlower.x = centerX + 0.02 * 2048;
		blueFlower.y = self.rows * self.cellSize + self.cellSize * 1.5 - 0.02 * 2732; // Move up by 2% of screen height
		this.sourceFlowers.addChild(blueFlower);
		// Red flower under bottom left bud
		var redFlower = new SourceFlower('red');
		redFlower.x = self.cellSize / 2 + 0.02 * 2048; // Move 2% to the right
		redFlower.y = self.rows * self.cellSize + self.cellSize * 1.5 - 0.02 * 2732; // Move up by 2% of screen height
		this.sourceFlowers.addChild(redFlower);
		// Yellow flower under bottom right bud
		var yellowFlower = new SourceFlower('yellow');
		yellowFlower.x = self.cols * self.cellSize - self.cellSize / 2; // Align with last column's center
		yellowFlower.y = self.rows * self.cellSize + self.cellSize * 1.5 - 0.02 * 2732; // Move up by 2% of screen height
		this.sourceFlowers.addChild(yellowFlower);
		// Center the grid on screen
		self.x = (2048 - self.cols * self.cellSize) / 2;
		self.y = (2732 - self.rows * self.cellSize) / 2 + 2732 * 0.12 - 400;
		// Initialize empty grid
		for (var i = 0; i < self.rows; i++) {
			self.grid[i] = [];
			for (var j = 0; j < self.cols; j++) {
				self.grid[i][j] = null;
			}
		}
	};
	// Helper method to convert grid position to world position
	self.gridToWorld = function (gridX, gridY) {
		if (typeof gridX !== 'number' || typeof gridY !== 'number') {
			console.log('Invalid grid coordinates:', gridX, gridY);
			return {
				x: self.x,
				y: self.y
			}; // Return default position if invalid
		}
		return {
			x: self.x + gridX * self.cellSize + self.cellSize / 2,
			y: self.y + gridY * self.cellSize + self.cellSize / 2
		};
	};
	// Helper method to convert world position to grid position
	self.worldToGrid = function (worldX, worldY) {
		var localX = worldX - self.x;
		var localY = worldY - self.y;
		return {
			x: Math.floor(localX / self.cellSize),
			y: Math.floor(localY / self.cellSize)
		};
	};
});
// GardenBackground class
var GardenBackground = Container.expand(function () {
	var self = Container.call(this);
	var gardenSoil = LK.getAsset('GardenSoil', {
		anchorX: 0.5,
		anchorY: 0.5,
		scaleX: 1.02,
		scaleY: 1.02,
		x: 2048 / 2,
		y: 2732 / 2 - 0.02 * 2732
	});
	self.addChild(gardenSoil);
	var gardenBackground = LK.getAsset('SpringBackground', {
		anchorX: 0.5,
		anchorY: 0.5,
		scaleX: 1.02,
		scaleY: 1.02,
		x: 2048 / 2,
		y: 2732 / 2 - 0.01 * 2732
	});
	self.addChild(gardenBackground);
});
var Hive = Container.expand(function () {
	var self = Container.call(this);
	var hiveSprite = self.attachAsset('Hive', {
		anchorX: 0.5,
		anchorY: 0.5
	});
	self.storedPollen = {
		'red': 0,
		'blue': 0,
		'yellow': 0
	};
	// Add meter above hive
	self.pollenMeter = new PollenMeter();
	self.pollenMeter.y = -200;
	self.addChild(self.pollenMeter);
	// Collection method
	self.collectFromBee = function (bee) {
		if (bee.currentPollen > 0) {
			// Transfer each type of pollen
			bee.pollenTypes.forEach(function (type) {
				// Initialize hive's stored pollen for this color if needed
				if (!self.storedPollen) {
					self.storedPollen = {};
				}
				if (!self.storedPollen[type.color]) {
					self.storedPollen[type.color] = 0;
				}
				// Add to hive's storage
				self.storedPollen[type.color] += type.amount;
				// Removed hive UI update call
			});
			// Create particles spread across the hive's width
			var particleCount = 20;
			var hiveWidth = 300;
			for (var i = 0; i < particleCount; i++) {
				var particle = new PollenParticle().init('transfer');
				particle.x = -hiveWidth / 2 + Math.random() * hiveWidth;
				particle.y = -200;
				particle.vx = (Math.random() - 0.5) * 0.5;
				particle.vy = 1 + Math.random();
				particle.twinkleOffset = Math.random() * Math.PI * 2;
				particle.twinkleSpeed = 0.1 + Math.random() * 0.1;
				particle.scale.set(0.5);
				self.addChild(particle);
			}
			// Clear bee's pollen
			bee.currentPollen = 0;
			bee.pollenTypes = [];
			// Removed bee UI update call
			// End bee's trail
			bee.pollenTrail.active = false;
			bee.pollenTrail.points = [];
		}
	};
	return self;
});
var PollenMeter = Container.expand(function () {
	var self = Container.call(this);
	// Create background bar
	var background = LK.getAsset('marker', {
		anchorX: 0.5,
		anchorY: 0.5,
		scaleX: 1,
		scaleY: 0.1
	});
	self.addChild(background);
	// Create fill bar
	var fill = LK.getAsset('marker', {
		anchorX: 0.5,
		anchorY: 0.5,
		scaleX: 0,
		scaleY: 0.1
	});
	fill.tint = 0xFFFF00; // Yellow for pollen
	self.fillBar = fill;
	self.addChild(fill);
	// Update method to show current pollen
	self.updateMeter = function (current, max) {
		fill.scale.x = current / max;
	};
	return self;
});
// PollenParticle class
var PollenParticle = Container.expand(function () {
	var self = Container.call(this);
	// Particle properties
	self.velocity = {
		x: 0,
		y: 0
	};
	self.lifespan = 1; // Goes from 1 to 0
	self.decayRate = 0.02; // How fast the particle fades
	self.type = 'trail'; // Can be 'trail' or 'burst'
	// Create the visual element
	var assetMap = {
		'trail': 'PollenSparkle',
		'burst': 'Petal',
		'fairy': 'PollenSparkle',
		'transfer': 'PollenSparkle',
		'star': 'StarParticle' // Add this line
	};
	var pollenGraphics;
	// Initialize with random properties for more organic feel
	self.init = function (type) {
		self.type = type || 'trail';
		if (!pollenGraphics) {
			pollenGraphics = self.attachAsset(assetMap[self.type], {
				anchorX: 0.5,
				anchorY: 0.5
			});
		}
		// Set initial scale based on type
		if (self.type === 'trail') {
			self.scale.set(0.7 + Math.random() * 0.3); // Larger for trail
			self.decayRate = 0.03; // Faster decay for trail
			// Slight random velocity for trail movement
			self.velocity = {
				x: (Math.random() - 0.5) * 2,
				y: (Math.random() - 0.5) * 2
			};
		} else if (self.type === 'burst') {
			self.scale.set(0.5 + Math.random() * 0.3); // Smaller initial size for bursts
			self.decayRate = 0.01; // Slower decay for longer travel
			// Radial burst velocity
			var angle = Math.random() * Math.PI * 2;
			var speed = 3 + Math.random() * 5; // Increased speed for further travel
			self.velocity = {
				x: Math.cos(angle) * speed,
				y: Math.sin(angle) * speed
			};
		} else if (self.type === 'fairy') {
			self.lifespan = undefined; // Don't fade out
			self.startAngle = Math.random() * Math.PI * 2; // Random start position
			self.orbitRadius = 20 + Math.random() * 40; // Increase orbit radius variation
			self.orbitSpeed = 0.005 + Math.random() * 0.03; // Increase orbit speed variation
			self.update = function () {
				var time = LK.ticks * self.orbitSpeed;
				// Orbit motion
				self.x = Math.cos(time + self.startAngle) * self.orbitRadius;
				self.y = Math.sin(time + self.startAngle) * self.orbitRadius;
				// Add bobbing
				self.y += Math.sin(time * 2 + self.startAngle) * 10;
			};
		} else if (self.type === 'star') {
			self.scale.set(1 + Math.random() * 0.2);
			self.decayRate = 0.015; // Slower decay for more visible effect
			// Add sparkle rotation
			self.rotationSpeed = (Math.random() - 0.5) * 0.4; // Faster rotation than normal particles
			self.alpha = 1;
			// Add velocity setup like other particle types
			var angle = Math.random() * Math.PI * 2;
			var speed = 12 + Math.random() * 4; // Higher speed for farther travel
			self.velocity = {
				x: Math.cos(angle) * speed,
				y: Math.sin(angle) * speed
			};
		}
		// Random rotation speed
		self.rotationSpeed = (Math.random() - 0.5) * 0.2;
		// Random starting rotation
		self.rotation = Math.random() * Math.PI * 2;
		// Add random rotation speed for dynamic movement
		self.rotationSpeed = (Math.random() - 0.5) * 0.2;
		// Full opacity to start
		self.alpha = 1;
		if (self.type === 'transfer') {
			self.scale.set(0.5);
			self.alpha = 1;
			self.twinkleOffset = 0; // Initialize twinkle offset 
			self.twinkleSpeed = 0.1; // Initialize twinkle speed 
			self.update = function () {
				// Gentle drift down 
				self.x += self.vx;
				self.y += self.vy;
				// Individual twinkle effect 
				self.alpha = 0.6 + Math.sin(LK.ticks * self.twinkleSpeed + self.twinkleOffset) * 0.4;
				// Remove when below hive 
				if (self.y > 100) {
					self.destroy();
				}
			};
		}
		return self;
	};
	self.update = function () {
		// Update position based on velocity
		self.x += self.velocity.x;
		self.y += self.velocity.y;
		// Add rotation
		self.rotation += self.rotationSpeed;
		// Slow down velocity over time
		self.velocity.x *= 0.95;
		self.velocity.y *= 0.95;
		// Update lifespan and alpha
		self.lifespan -= self.decayRate;
		self.alpha = self.lifespan;
		// Scale slightly varies with life
		var scalePulse = 1 + Math.sin(LK.ticks * 0.2) * 0.1;
		pollenGraphics.scale.set(scalePulse * self.scale.x);
		// Remove when lifecycle complete
		if (self.lifespan <= 0) {
			self.destroy();
		}
	};
});
// First, let's add a PollenTrail class to handle the dragging mechanic
var PollenTrail = Container.expand(function () {
	var self = Container.call(this);
	self.points = [];
	self.active = false;
	self.currentGarden = null; // Store reference to garden
	self.MAX_SPEED = 15; // Adjust this value for proper feel
	self.startTrail = function (x, y, garden, bee) {
		self.active = true;
		self.points = [{
			x: x,
			y: y,
			time: Date.now()
		}];
		self.startTime = Date.now();
		self.trailStartTime = Date.now();
		self.currentGarden = garden;
		self.bee = bee; // Store bee reference
		self.lastPoint = {
			x: x,
			y: y
		}; // Initialize lastPoint
		// Force red on first particle to verify bee storage
		var particle = new PollenParticle().init('trail');
		particle.children[0].tint = 0xFF0000;
		particle.x = x;
		particle.y = y;
		game.addChild(particle);
	};
	self.updateTrail = function (x, y) {
		if (!self.active) {
			return;
		}
		// Enforce maximum speed
		var dx = x - self.lastPoint.x;
		var dy = y - self.lastPoint.y;
		var distance = Math.sqrt(dx * dx + dy * dy);
		if (distance > self.MAX_SPEED) {
			var ratio = self.MAX_SPEED / distance;
			x = self.lastPoint.x + dx * ratio;
			y = self.lastPoint.y + dy * ratio;
		}
		self.points.push({
			x: x,
			y: y,
			time: Date.now()
		});
		self.lastPoint = {
			x: x,
			y: y
		};
		// Create particle effect along trail
		var particle = new PollenParticle().init('trail');
		if (self.bee && self.bee.currentColor) {
			var color = self.bee.currentColor;
			if (color === 'red') {
				particle.children[0].tint = 0xFF0000;
			} else if (color === 'blue') {
				particle.children[0].tint = 0x0000FF;
			} else if (color === 'yellow') {
				particle.children[0].tint = 0xFFFF00;
			} else if (color === 'purple') {
				particle.children[0].tint = 0x800080;
			} else if (color === 'green') {
				particle.children[0].tint = 0x00FF00;
			} else if (color === 'orange') {
				particle.children[0].tint = 0xFFA500;
			}
		}
		particle.x = x;
		particle.y = y;
		game.addChild(particle);
	};
	// Add the burst effect function
	self.createPollenBurst = function (x, y) {
		for (var i = 0; i < 12; i++) {
			var particle = new PollenParticle().init('burst');
			var angle = i / 12 * Math.PI * 2;
			var distance = 30;
			particle.x = x + Math.cos(angle) * distance;
			particle.y = y + Math.sin(angle) * distance;
			// Give particles outward velocity
			particle.vx = Math.cos(angle) * 3;
			particle.vy = Math.sin(angle) * 3;
			game.addChild(particle);
		}
	};
	self.endTrail = function () {
		if (!self.active) {
			return;
		}
		var affectedBuds = [];
		var checkedPositions = {};
		self.points.forEach(function (point) {
			var localPos = self.currentGarden.toLocal({
				x: point.x,
				y: point.y
			}, game);
			var gridX = Math.floor(localPos.x / self.currentGarden.cellSize);
			var gridY = Math.floor(localPos.y / self.currentGarden.cellSize);
			var posKey = gridX + ',' + gridY;
			if (!checkedPositions[posKey] && gridX >= 0 && gridX < self.currentGarden.cols && gridY >= 0 && gridY < self.currentGarden.rows) {
				checkedPositions[posKey] = true;
				var gridItem = self.currentGarden.grid[gridY][gridX];
				// Verify it's a valid bud
				if (gridItem && gridItem.isBud === true && gridItem.isFlower === false) {
					affectedBuds.push({
						bud: gridItem,
						gridX: gridX,
						gridY: gridY
					});
				}
			}
		});
		if (affectedBuds.length >= 2) {
			affectedBuds.forEach(function (budInfo) {
				// IMPORTANT: Clear the grid position first
				self.currentGarden.grid[budInfo.gridY][budInfo.gridX] = null;
				// Remove the bud from display list
				self.currentGarden.removeChild(budInfo.bud);
				// Create new flower
				var newFlower = new BasicFlower();
				newFlower.x = budInfo.bud.x;
				newFlower.y = budInfo.bud.y;
				newFlower.isFlower = true;
				// Update grid position and add to display list
				self.currentGarden.grid[budInfo.gridY][budInfo.gridX] = newFlower;
				self.currentGarden.addChild(newFlower);
				// Start bloom animation
				newFlower.bloom();
			});
		}
		self.active = false;
		self.points = [];
	};
	self.update = function () {
		// Just update particles, no time checks
		// Update all children particles
		for (var i = self.children.length - 1; i >= 0; i--) {
			var particle = self.children[i];
			if (particle && particle.update) {
				particle.update();
			}
		}
	};
});
// Add ScoreManager to handle chain reactions and scoring
var ScoreManager = Container.expand(function () {
	var self = Container.call(this);
	// Properties
	self.currentScore = 0;
	self.lastMatchTime = 0; // Add this property
	self.currentChain = 0;
	self.chainMultiplier = 1;
	self.BASIC_FLOWER_POINTS = 100;
	self.HYBRID_FLOWER_POINTS = 200;
	// Methods need to be defined this way in Container.expand
	self.getFlowerBasePoints = function (flowerColor) {
		var hybridColors = ['purple', 'green', 'orange'];
		return hybridColors.includes(flowerColor) ? self.HYBRID_FLOWER_POINTS : self.BASIC_FLOWER_POINTS;
	};
	self.getMatchMultiplier = function (matchSize) {
		if (matchSize <= 3) {
			return 1;
		}
		if (matchSize === 4) {
			return 1.5;
		}
		if (matchSize === 5) {
			return 2;
		}
		return 2.5; // 6 or more
	};
	self.addToChain = function () {
		var currentTime = Date.now();
		// Only increment chain if less than 2 seconds since last match
		if (currentTime - self.lastMatchTime < 2000 && self.lastMatchTime !== 0) {
			self.currentChain++;
			self.chainMultiplier = Math.min(1 + self.currentChain * 0.5, 5);
		} else {
			// Reset chain if it's the first match or too much time has passed
			self.currentChain = 0;
			self.chainMultiplier = 1;
		}
		self.lastMatchTime = currentTime;
	};
	self.resetChain = function () {
		self.currentChain = 0;
		self.chainMultiplier = 1;
	};
	self.addScore = function (points) {
		self.currentScore += Math.floor(points);
		if (game.scoreDisplay) {
			game.scoreDisplay.setText(self.currentScore.toString());
		}
	};
	return self;
});
var SeasonManager = Container.expand(function () {
	var self = Container.call(this);
	self.springMatchingEnabled = false; // New flag for spring matching phase
	// Season constants
	self.SEASONS = {
		SPRING: 'spring',
		SUMMER: 'summer',
		FALL: 'fall',
		WINTER: 'winter'
	};
	self.currentSeason = null;
	self.yearNumber = 1;
	self.totalScore = 0;
	self.seasonStartTime = 0;
	self.init = function () {
		self.yearNumber = 1; // Start at year 1
		return; // Default initialization, no active season set
	};
	self.setActiveSeason = function (season) {
		// Store previous season's score
		if (self.currentSeason && game.scoreDisplay) {
			self.totalScore += parseInt(game.scoreDisplay.text);
		}
		self.currentSeason = season;
		self.transitionToSeason(season);
	};
	self.transitionToSeason = function (season) {
		// Clear existing particles first
		self.clearTransitionEffects();
		// Create transition effects
		self.createSeasonTransition(season);
		// Update game rules and mechanics
		self.updateGameRules(season);
		// Show season text
		self.showSeasonText(season);
	};
	self.clearTransitionEffects = function () {
		// Remove all existing transition particles
		game.children.forEach(function (child) {
			if (child.isTransitionEffect) {
				game.removeChild(child);
			}
		});
	};
	self.createSeasonTransition = function (season) {
		var particleConfig = {
			spring: {
				asset: 'PollenSparkle',
				count: 50,
				tint: 0x88FF88
			},
			summer: {
				asset: 'Petal',
				count: 40,
				tint: 0xFFFF88
			},
			fall: {
				asset: 'Petal',
				count: 30,
				tint: 0xFF8844
			},
			winter: {
				asset: 'PollenSparkle',
				count: 60,
				tint: 0xFFFFFF
			}
		};
		var config = particleConfig[season];
		for (var i = 0; i < config.count; i++) {
			var particle = new TransitionParticle(config.asset);
			particle.children[0].tint = config.tint;
			particle.isTransitionEffect = true;
			game.addChild(particle);
		}
	};
	self.updateGameRules = function (season) {
		// Clear existing timers/rules
		if (garden.budSpawner && typeof garden.budSpawner.reset === 'function') {
			garden.budSpawner.reset();
		}
		switch (season) {
			case self.SEASONS.SPRING:
				self.initSpringMode();
				break;
			case self.SEASONS.SUMMER:
				self.initSummerMode();
				break;
			case self.SEASONS.FALL:
				self.initFallMode();
				break;
			case self.SEASONS.WINTER:
				self.initWinterMode();
				break;
		}
	};
	self.showSeasonText = function (season) {
		var texts = {
			spring: "Spring: Pollinate the garden",
			summer: "Summer: Match the flowers",
			fall: "Fall: Clear the leaves",
			winter: "Winter: Dance to stay warm"
		};
		var seasonText = new Text2(texts[season], {
			size: 120,
			fill: 0xFFFFFF,
			align: 'center'
		});
		seasonText.alpha = 0;
		seasonText.scale.set(0.5);
		seasonText.x = 2048 / 2;
		seasonText.y = 400;
		seasonText.anchor.set(0.5);
		game.addChild(seasonText);
		// Animate in
		tween(seasonText, {
			alpha: 1,
			y: 300
		}, {
			duration: 1000,
			ease: 'backOut'
		});
		tween(seasonText.scale, {
			x: 1,
			y: 1
		}, {
			duration: 1000,
			ease: 'elasticOut'
		});
		// Remove after delay
		LK.setTimeout(function () {
			tween(seasonText, {
				alpha: 0,
				y: 200
			}, {
				duration: 500,
				onFinish: function onFinish() {
					game.removeChild(seasonText);
				}
			});
		}, 2000);
	};
	// Initialize each season's specific mechanics
	self.initSpringMode = function () {
		if (!game.gameTimer) {
			game.gameTimer = new GameTimer();
			game.addChild(game.gameTimer);
		}
		// Set spring timer
		game.gameTimer.setTime(60); // 60 seconds
		// If we're transitioning from a different season to spring, increment the year
		if (self.currentSeason && self.currentSeason !== self.SEASONS.SPRING) {
			self.yearNumber++;
		}
		// Removed old timer setup as GameTimer is now used
		// Disable normal bud spawning
		if (garden.budSpawner) {
			garden.budSpawner.enabled = false;
		}
		// Clear and fully populate garden with buds
		for (var row = 0; row < garden.rows; row++) {
			for (var col = 0; col < garden.cols; col++) {
				if (garden.grid[row][col]) {
					garden.grid[row][col].destroy();
					garden.grid[row][col] = null;
				}
				var bud = new Bud();
				var worldPos = garden.gridToWorld(col, row);
				bud.x = worldPos.x - 400 + garden.cellSize;
				bud.y = worldPos.y - 400 - 50;
				garden.grid[row][col] = bud;
				garden.addChild(bud);
				// Scale in animation
				bud.scale.set(0);
				tween(bud.scale, {
					x: 1,
					y: 1
				}, {
					duration: 500,
					ease: 'backOut'
				});
			}
		}
		// Calculate total flower requirements based on year
		var totalFlowersNeeded = 15 + (self.yearNumber - 1) * 5;
		totalFlowersNeeded = Math.min(totalFlowersNeeded, 64); // Cap at 64 total flowers
		// Set up random distribution of goals
		var primaryGoals = Math.ceil(totalFlowersNeeded * 0.6); // 60% split between red, blue, yellow
		var hybridGoals = totalFlowersNeeded - primaryGoals; // Remaining 40% for hybrid colors
		// Randomly distribute primary colors (should add up to primaryGoals)
		var redGoal = Math.floor(primaryGoals / 3 + (Math.random() - 0.5) * 2);
		var blueGoal = Math.floor((primaryGoals - redGoal) / 2 + (Math.random() - 0.5) * 2);
		var yellowGoal = primaryGoals - redGoal - blueGoal;
		// Randomly distribute hybrid colors (should add up to hybridGoals)
		var purpleGoal = Math.floor(hybridGoals / 3 + (Math.random() - 0.5) * 2);
		var greenGoal = Math.floor((hybridGoals - purpleGoal) / 2 + (Math.random() - 0.5) * 2);
		var orangeGoal = hybridGoals - purpleGoal - greenGoal;
		garden.flowerGoals = {
			red: Math.max(1, redGoal),
			blue: Math.max(1, blueGoal),
			yellow: Math.max(1, yellowGoal),
			purple: Math.max(1, purpleGoal),
			orange: Math.max(1, orangeGoal),
			green: Math.max(1, greenGoal)
		};
		garden.currentFlowers = {
			red: 0,
			blue: 0,
			yellow: 0,
			purple: 0,
			orange: 0,
			green: 0
		};
		// Create flower goal display
		self.createFlowerGoalDisplay();
		// Disable normal bud spawning
	};
	self.createGoalIndicator = function (colorData, isLeft) {
		var row = new Container();
		var flower = new BasicFlower(colorData.color);
		flower.scale.set(0.3);
		row.addChild(flower);
		var text = new Text2("0/" + colorData.goal, {
			size: 40,
			fill: 0xFFFFFF
		});
		text.x = 60;
		text.y = -20;
		row.addChild(text);
		// Position based on side
		row.x = isLeft ? -200 : 200;
		// Store reference to text for updates
		garden.currentFlowers[colorData.color + "Text"] = text;
		return row;
	};
	self.createFlowerGoalDisplay = function () {
		var display = new Container();
		// Create array of goals for tracking/cycling
		var goalQueue = Object.keys(garden.flowerGoals).map(function (color) {
			return {
				color: color,
				goal: garden.flowerGoals[color]
			};
		});
		// Initial setup - show first two goals
		if (goalQueue.length > 0) {
			display.addChild(self.createGoalIndicator(goalQueue[0], true));
		}
		if (goalQueue.length > 1) {
			display.addChild(self.createGoalIndicator(goalQueue[1], false));
		}
		// Position entire display near score
		display.x = 2048 / 2; // Center horizontally
		display.y = 100; // Near top by score
		// Store queue and display for updates
		garden.goalQueue = goalQueue;
		garden.goalDisplay = display;
		game.addChild(display); // Add directly to game instead of GUI
	};
	self.updateFlowerCounts = function () {
		// Reset ONLY the number counts, not text references
		Object.keys(garden.currentFlowers).forEach(function (color) {
			if (typeof garden.currentFlowers[color] === 'number' && !color.includes('Text')) {
				garden.currentFlowers[color] = 0;
			}
		});
		// Count all flowers in garden
		for (var row = 0; row < garden.rows; row++) {
			for (var col = 0; col < garden.cols; col++) {
				var item = garden.grid[row][col];
				if (item && item.isFlower && !item.isSourceFlower) {
					garden.currentFlowers[item.color]++;
				}
			}
		}
		// Update display
		Object.keys(garden.flowerGoals).forEach(function (color) {
			if (garden.currentFlowers[color + "Text"]) {
				var currentCount = garden.currentFlowers[color];
				var goalCount = garden.flowerGoals[color];
				var text = garden.currentFlowers[color + "Text"];
				// Check if goal met
				if (currentCount >= goalCount) {
					currentCount = goalCount; // Cap the display at goal amount
					// Create new green text
					var newText = new Text2(currentCount + "/" + goalCount, {
						size: 40,
						fill: 0x00FF00
					});
					newText.x = text.x;
					newText.y = text.y;
					text.parent.addChild(newText);
					text.parent.removeChild(text);
					garden.currentFlowers[color + "Text"] = newText;
				} else {
					text.setText(currentCount + "/" + goalCount);
				}
			}
		});
		// Check for completed goals and cycle display
		if (garden.goalQueue && garden.goalQueue.length > 0) {
			for (var i = garden.goalDisplay.children.length - 1; i >= 0; i--) {
				var displayedGoal = garden.goalDisplay.children[i];
				if (garden.goalQueue[i]) {
					var goalColor = garden.goalQueue[i].color;
				}
				if (garden.currentFlowers[goalColor] >= garden.flowerGoals[goalColor]) {
					// Create closure to capture correct index
					(function (index, goal) {
						// Animate out completed goal
						tween(goal, {
							alpha: 0,
							y: goal.y - 50
						}, {
							duration: 500,
							onFinish: function onFinish() {
								garden.goalDisplay.removeChild(goal);
								// Remove from queue
								garden.goalQueue.splice(index, 1);
								// Add next goal if available
								if (garden.goalQueue.length > index) {
									var nextGoal = self.createGoalIndicator(garden.goalQueue[index], index === 0);
									nextGoal.alpha = 0;
									garden.goalDisplay.addChild(nextGoal);
									// Animate in
									tween(nextGoal, {
										alpha: 1
									}, {
										duration: 500
									});
								}
							}
						});
					})(i, displayedGoal);
				}
			}
		}
		// Check for spring mode completion
		var allGoalsMet = Object.keys(garden.flowerGoals).every(function (color) {
			return garden.currentFlowers[color] >= garden.flowerGoals[color];
		});
	};
	self.initSummerMode = function () {
		// Current game mode - just enable normal spawning
		garden.budSpawner.enabled = true;
		garden.budSpawner.init(garden);
	};
	self.initFallMode = function () {
		// Add leaf obstacles
		self.addLeafObstacles();
		garden.budSpawner.enabled = false;
	};
	self.initWinterMode = function () {
		garden.warmthMeter = 100;
		garden.patternSystem = new WinterPatternSystem();
		game.addChild(garden.patternSystem);
		garden.budSpawner.enabled = false;
	};
	self.startSpringFinale = function () {
		// Clear all spring-specific UI elements
		// Remove goal display if it exists
		if (garden.goalDisplay && garden.goalDisplay.parent) {
			garden.goalDisplay.parent.removeChild(garden.goalDisplay);
			garden.goalDisplay = null;
		}
		self.springFinaleChaining = false; // Reset the chain state// Show finale transition text
		var finaleText = new Text2("Spring Finale: Chain Reaction!", {
			size: 120,
			fill: 0x00FF00,
			align: 'center'
		});
		finaleText.anchor.set(0.5);
		finaleText.x = 2048 / 2;
		finaleText.y = 400;
		finaleText.alpha = 0;
		game.addChild(finaleText);
		// Animate text
		tween(finaleText, {
			alpha: 1,
			y: 300
		}, {
			duration: 1000,
			ease: 'backOut',
			onFinish: function onFinish() {
				LK.setTimeout(function () {
					tween(finaleText, {
						alpha: 0,
						y: 200
					}, {
						duration: 500,
						onFinish: function onFinish() {
							game.removeChild(finaleText);
							self.initiateSpringMatching();
						}
					});
				}, 1500);
			}
		});
		// Initialize chain bonus tracking
		// Initialize chain bonus tracking
		game.scoreManager = new ScoreManager();
		// Make sure score display exists
		if (!game.scoreDisplay) {
			game.scoreDisplay = new ScoreDisplay();
			game.scoreDisplay.anchor.set(0.5, 0);
			game.scoreDisplay.x = 2048 / 2;
			game.scoreDisplay.y = 50;
			LK.gui.top.addChild(game.scoreDisplay);
		}
		self.springMatchingEnabled = true;
	};
	self.initiateSpringMatching = function () {
		// Start from the bottom row and work up
		var startMatchingFromBottom = function startMatchingFromBottom() {
			var matchFound = false;
			// Start from bottom-right corner
			for (var row = garden.rows - 1; row >= 0; row--) {
				for (var col = garden.cols - 1; col >= 0; col--) {
					var flower = garden.grid[row][col];
					if (flower && flower.isFlower) {
						var matches = game.flowerMatcher.findMatches(garden, col, row);
						if (matches.length >= 3) {
							matchFound = true;
							// Immediately clear grid positions
							matches.forEach(function (match) {
								if (garden.grid[match.y][match.x] === match.flower) {
									garden.grid[match.y][match.x] = null;
								}
							});
							// Handle animation separately
							LK.setTimeout(function () {
								self.handleSpringMatch(matches);
							}, 500);
							return true; // Exit after finding first match
						}
					}
				}
			}
			return matchFound;
		};
		// Set up recursive matching with delays
		var _continueMatching = function continueMatching() {
			if (startMatchingFromBottom()) {
				LK.setTimeout(_continueMatching, 1000);
			} else {
				self.completeSpringPhase();
			}
		};
		_continueMatching();
	};
	self.handleSpringMatch = function (matches) {
		// Start chaining if not already started
		if (!self.springFinaleChaining) {
			self.springFinaleChaining = true;
			game.scoreManager.currentChain = 0;
		}
		// Force chain continuation during finale
		game.scoreManager.currentChain++;
		game.scoreManager.chainMultiplier = Math.min(1 + game.scoreManager.currentChain * 0.5, 5);
		// Use the standard matching system for visuals/scoring
		game.flowerMatcher.clearMatches(garden, matches);
	};
	self.completeSpringPhase = function () {
		// Show completion message
		var completionText = new Text2("Spring Complete!", {
			size: 120,
			fill: 0x00FF00
		});
		completionText.anchor.set(0.5);
		completionText.x = 2048 / 2;
		completionText.y = 2732 / 2;
		completionText.alpha = 0;
		game.addChild(completionText);
		// Animate completion message
		tween(completionText, {
			alpha: 1,
			scaleX: 1.2,
			scaleY: 1.2
		}, {
			duration: 1000,
			onFinish: function onFinish() {
				LK.setTimeout(function () {
					tween(completionText, {
						alpha: 0
					}, {
						duration: 500,
						onFinish: function onFinish() {
							completionText.destroy();
						}
					});
				}, 2000);
			}
		});
	};
	self.update = function () {
		if (!self.currentSeason) {
			return;
		}
		switch (self.currentSeason) {
			case self.SEASONS.SPRING:
				// Timer update
				// Timer update is now handled by GameTimer class
				// Garden check (outside timer check)
				var fullyPollinated = true;
				for (var row = 0; row < garden.rows; row++) {
					for (var col = 0; col < garden.cols; col++) {
						var _garden$grid$row$col;
						if (!((_garden$grid$row$col = garden.grid[row][col]) !== null && _garden$grid$row$col !== void 0 && _garden$grid$row$col.isFlower)) {
							fullyPollinated = false;
							break;
						}
					}
					if (!fullyPollinated) {
						break;
					}
				}
				// Check for end conditions
				if (game.gameTimer.timeRemaining <= 0 || fullyPollinated) {
					// Check if goals are met
					var goalsMet = Object.keys(garden.flowerGoals).every(function (color) {
						return garden.currentFlowers[color] >= garden.flowerGoals[color];
					});
					// Disable any normal matching until finale starts
					self.springMatchingEnabled = false;
					if (goalsMet) {
						// Start the spring finale sequence if not already started
						if (!self.springFinaleStarted) {
							self.springFinaleStarted = true;
							self.startSpringFinale();
						}
					} else {
						// Game Over state
						var gameOverText = new Text2("GAME OVER - Goals not met!", {
							size: 60,
							fill: 0xFF0000
						});
						gameOverText.anchor.set(1, 0);
						gameOverText.x = 400; // Center of screen
						gameOverText.y = 150; // Below timer
						gameOverText.alpha = 0; // Start with alpha 0 for fade-in effect
						LK.gui.top.addChild(gameOverText);
						// Add fade-in animation
						tween(gameOverText, {
							alpha: 1
						}, {
							duration: 1000,
							// 1 second fade-in
							onFinish: function onFinish() {
								// Optionally, add a fade-out after a delay
								LK.setTimeout(function () {
									tween(gameOverText, {
										alpha: 0
									}, {
										duration: 1000,
										// 1 second fade-out
										onFinish: function onFinish() {
											LK.gui.top.removeChild(gameOverText);
										}
									});
								}, 2000); // 2 seconds delay before fade-out
							}
						});
					}
				}
				break;
			case self.SEASONS.SUMMER:
				self.updateSummer();
				break;
			case self.SEASONS.FALL:
				self.updateFall();
				break;
			case self.SEASONS.WINTER:
				self.updateWinter();
				break;
		}
	};
	return self;
});
var SourceFlower = Container.expand(function (color) {
	var self = Container.call(this);
	// Store flower color
	self.color = color;
	self.isSourceFlower = true; // Flag to identify source flowers
	// Map color to asset name
	var assetMap = {
		'red': 'RedFlower',
		'blue': 'BlueFlower',
		'yellow': 'YellowFlower'
	};
	// Create flower sprite
	var flowerGraphics = self.attachAsset(assetMap[self.color], {
		anchorX: 0.5,
		anchorY: 0.5,
		scaleX: 1.5,
		scaleY: 1.5
	});
	// Source flowers always have pollen
	self.hasActivePollen = true;
	self.fairyParticles = [];
	self.FAIRY_COUNT = 3;
	// Initialize fairy particles
	for (var i = 0; i < self.FAIRY_COUNT; i++) {
		var fairy = new PollenParticle().init('fairy');
		fairy.scale.set(0.3 + Math.random() * 0.2);
		fairy.x += (Math.random() - 0.5) * 60;
		fairy.y += (Math.random() - 0.5) * 60;
		fairy.rotation = Math.random() * Math.PI * 2;
		fairy.rotationSpeed = (Math.random() - 0.5) * 0.2;
		self.addChild(fairy);
		self.fairyParticles.push(fairy);
	}
	// Gentle animation
	self.update = function () {
		var scaleFactor = 1.5 + Math.sin(LK.ticks * 0.05) * 0.1; // Adjusted for 1.5x size and increased animation amplitude
		flowerGraphics.scale.x = scaleFactor;
		flowerGraphics.scale.y = scaleFactor;
		flowerGraphics.rotation = Math.sin(LK.ticks * 0.05) * 0.1; // Increased rotation amplitude for larger size
		// Update fairy particles
		self.fairyParticles.forEach(function (fairy) {
			if (fairy && fairy.update) {
				fairy.update();
			}
		});
	};
	// Override collection behavior - source flowers regenerate pollen immediately
	self.pollenCollected = false;
	self.resetPollen = function () {
		self.hasActivePollen = true;
		self.pollenCollected = false;
	};
	self.collectPollen = function () {
		// Reset immediately to allow continuous collection
		self.hasActivePollen = true;
		self.pollenCollected = false;
	};
	return self;
});
var TransitionParticle = Container.expand(function (assetName) {
	var self = Container.call(this);
	var sprite = self.attachAsset(assetName, {
		anchorX: 0.5,
		anchorY: 0.5
	});
	self.x = Math.random() * 2048;
	self.y = -50;
	self.vx = (Math.random() - 0.5) * 5;
	self.vy = 3 + Math.random() * 2;
	self.rotationSpeed = (Math.random() - 0.5) * 0.1;
	self.update = function () {
		self.x += self.vx;
		self.y += self.vy;
		self.rotation += self.rotationSpeed;
		// Remove if off screen
		if (self.y > 2732 + 50) {
			self.destroy();
		}
	};
	return self;
});
// Score display class
var ScoreDisplay = Text2.expand(function () {
	var self = Text2.call(this, '0', {
		size: 150,
		fill: 0xFFFFFF
	});
});
/**** 
* Initialize Game
****/ 
var game = new LK.Game({
	backgroundColor: 0x000000 //Init game with black background 
});
/**** 
* Game Code
****/ 
// Declare and initialize flowerManager in global scope
function _slicedToArray8(r, e) {
	return _arrayWithHoles8(r) || _iterableToArrayLimit8(r, e) || _unsupportedIterableToArray8(r, e) || _nonIterableRest8();
}
function _nonIterableRest8() {
	throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _unsupportedIterableToArray8(r, a) {
	if (r) {
		if ("string" == typeof r) {
			return _arrayLikeToArray8(r, a);
		}
		var t = {}.toString.call(r).slice(8, -1);
		return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray8(r, a) : void 0;
	}
}
function _arrayLikeToArray8(r, a) {
	(null == a || a > r.length) && (a = r.length);
	for (var e = 0, n = Array(a); e < a; e++) {
		n[e] = r[e];
	}
	return n;
}
function _iterableToArrayLimit8(r, l) {
	var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
	if (null != t) {
		var e,
			n,
			i,
			u,
			a = [],
			f = !0,
			o = !1;
		try {
			if (i = (t = t.call(r)).next, 0 === l) {
				if (Object(t) !== t) {
					return;
				}
				f = !1;
			} else {
				for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0) {
					;
				}
			}
		} catch (r) {
			o = !0, n = r;
		} finally {
			try {
				if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) {
					return;
				}
			} finally {
				if (o) {
					throw n;
				}
			}
		}
		return a;
	}
}
function _arrayWithHoles8(r) {
	if (Array.isArray(r)) {
		return r;
	}
}
function _slicedToArray7(r, e) {
	return _arrayWithHoles7(r) || _iterableToArrayLimit7(r, e) || _unsupportedIterableToArray7(r, e) || _nonIterableRest7();
}
function _nonIterableRest7() {
	throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _iterableToArrayLimit7(r, l) {
	var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
	if (null != t) {
		var e,
			n,
			i,
			u,
			a = [],
			f = !0,
			o = !1;
		try {
			if (i = (t = t.call(r)).next, 0 === l) {
				if (Object(t) !== t) {
					return;
				}
				f = !1;
			} else {
				for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0) {
					;
				}
			}
		} catch (r) {
			o = !0, n = r;
		} finally {
			try {
				if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) {
					return;
				}
			} finally {
				if (o) {
					throw n;
				}
			}
		}
		return a;
	}
}
function _arrayWithHoles7(r) {
	if (Array.isArray(r)) {
		return r;
	}
}
function _createForOfIteratorHelper6(r, e) {
	var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
	if (!t) {
		if (Array.isArray(r) || (t = _unsupportedIterableToArray7(r)) || e && r && "number" == typeof r.length) {
			t && (r = t);
			var _n6 = 0,
				F = function F() {};
			return {
				s: F,
				n: function n() {
					return _n6 >= r.length ? {
						done: !0
					} : {
						done: !1,
						value: r[_n6++]
					};
				},
				e: function e(r) {
					throw r;
				},
				f: F
			};
		}
		throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
	}
	var o,
		a = !0,
		u = !1;
	return {
		s: function s() {
			t = t.call(r);
		},
		n: function n() {
			var r = t.next();
			return a = r.done, r;
		},
		e: function e(r) {
			u = !0, o = r;
		},
		f: function f() {
			try {
				a || null == t["return"] || t["return"]();
			} finally {
				if (u) {
					throw o;
				}
			}
		}
	};
}
function _unsupportedIterableToArray7(r, a) {
	if (r) {
		if ("string" == typeof r) {
			return _arrayLikeToArray7(r, a);
		}
		var t = {}.toString.call(r).slice(8, -1);
		return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray7(r, a) : void 0;
	}
}
function _arrayLikeToArray7(r, a) {
	(null == a || a > r.length) && (a = r.length);
	for (var e = 0, n = Array(a); e < a; e++) {
		n[e] = r[e];
	}
	return n;
}
function _slicedToArray6(r, e) {
	return _arrayWithHoles6(r) || _iterableToArrayLimit6(r, e) || _unsupportedIterableToArray6(r, e) || _nonIterableRest6();
}
function _nonIterableRest6() {
	throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _iterableToArrayLimit6(r, l) {
	var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
	if (null != t) {
		var e,
			n,
			i,
			u,
			a = [],
			f = !0,
			o = !1;
		try {
			if (i = (t = t.call(r)).next, 0 === l) {
				if (Object(t) !== t) {
					return;
				}
				f = !1;
			} else {
				for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0) {
					;
				}
			}
		} catch (r) {
			o = !0, n = r;
		} finally {
			try {
				if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) {
					return;
				}
			} finally {
				if (o) {
					throw n;
				}
			}
		}
		return a;
	}
}
function _arrayWithHoles6(r) {
	if (Array.isArray(r)) {
		return r;
	}
}
function _createForOfIteratorHelper5(r, e) {
	var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
	if (!t) {
		if (Array.isArray(r) || (t = _unsupportedIterableToArray6(r)) || e && r && "number" == typeof r.length) {
			t && (r = t);
			var _n5 = 0,
				F = function F() {};
			return {
				s: F,
				n: function n() {
					return _n5 >= r.length ? {
						done: !0
					} : {
						done: !1,
						value: r[_n5++]
					};
				},
				e: function e(r) {
					throw r;
				},
				f: F
			};
		}
		throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
	}
	var o,
		a = !0,
		u = !1;
	return {
		s: function s() {
			t = t.call(r);
		},
		n: function n() {
			var r = t.next();
			return a = r.done, r;
		},
		e: function e(r) {
			u = !0, o = r;
		},
		f: function f() {
			try {
				a || null == t["return"] || t["return"]();
			} finally {
				if (u) {
					throw o;
				}
			}
		}
	};
}
function _unsupportedIterableToArray6(r, a) {
	if (r) {
		if ("string" == typeof r) {
			return _arrayLikeToArray6(r, a);
		}
		var t = {}.toString.call(r).slice(8, -1);
		return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray6(r, a) : void 0;
	}
}
function _arrayLikeToArray6(r, a) {
	(null == a || a > r.length) && (a = r.length);
	for (var e = 0, n = Array(a); e < a; e++) {
		n[e] = r[e];
	}
	return n;
}
function _slicedToArray5(r, e) {
	return _arrayWithHoles5(r) || _iterableToArrayLimit5(r, e) || _unsupportedIterableToArray5(r, e) || _nonIterableRest5();
}
function _nonIterableRest5() {
	throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _iterableToArrayLimit5(r, l) {
	var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
	if (null != t) {
		var e,
			n,
			i,
			u,
			a = [],
			f = !0,
			o = !1;
		try {
			if (i = (t = t.call(r)).next, 0 === l) {
				if (Object(t) !== t) {
					return;
				}
				f = !1;
			} else {
				for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0) {
					;
				}
			}
		} catch (r) {
			o = !0, n = r;
		} finally {
			try {
				if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) {
					return;
				}
			} finally {
				if (o) {
					throw n;
				}
			}
		}
		return a;
	}
}
function _arrayWithHoles5(r) {
	if (Array.isArray(r)) {
		return r;
	}
}
function _createForOfIteratorHelper4(r, e) {
	var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
	if (!t) {
		if (Array.isArray(r) || (t = _unsupportedIterableToArray5(r)) || e && r && "number" == typeof r.length) {
			t && (r = t);
			var _n4 = 0,
				F = function F() {};
			return {
				s: F,
				n: function n() {
					return _n4 >= r.length ? {
						done: !0
					} : {
						done: !1,
						value: r[_n4++]
					};
				},
				e: function e(r) {
					throw r;
				},
				f: F
			};
		}
		throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
	}
	var o,
		a = !0,
		u = !1;
	return {
		s: function s() {
			t = t.call(r);
		},
		n: function n() {
			var r = t.next();
			return a = r.done, r;
		},
		e: function e(r) {
			u = !0, o = r;
		},
		f: function f() {
			try {
				a || null == t["return"] || t["return"]();
			} finally {
				if (u) {
					throw o;
				}
			}
		}
	};
}
function _unsupportedIterableToArray5(r, a) {
	if (r) {
		if ("string" == typeof r) {
			return _arrayLikeToArray5(r, a);
		}
		var t = {}.toString.call(r).slice(8, -1);
		return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray5(r, a) : void 0;
	}
}
function _arrayLikeToArray5(r, a) {
	(null == a || a > r.length) && (a = r.length);
	for (var e = 0, n = Array(a); e < a; e++) {
		n[e] = r[e];
	}
	return n;
}
function _slicedToArray4(r, e) {
	return _arrayWithHoles4(r) || _iterableToArrayLimit4(r, e) || _unsupportedIterableToArray4(r, e) || _nonIterableRest4();
}
function _nonIterableRest4() {
	throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _unsupportedIterableToArray4(r, a) {
	if (r) {
		if ("string" == typeof r) {
			return _arrayLikeToArray4(r, a);
		}
		var t = {}.toString.call(r).slice(8, -1);
		return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray4(r, a) : void 0;
	}
}
function _arrayLikeToArray4(r, a) {
	(null == a || a > r.length) && (a = r.length);
	for (var e = 0, n = Array(a); e < a; e++) {
		n[e] = r[e];
	}
	return n;
}
function _iterableToArrayLimit4(r, l) {
	var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
	if (null != t) {
		var e,
			n,
			i,
			u,
			a = [],
			f = !0,
			o = !1;
		try {
			if (i = (t = t.call(r)).next, 0 === l) {
				if (Object(t) !== t) {
					return;
				}
				f = !1;
			} else {
				for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0) {
					;
				}
			}
		} catch (r) {
			o = !0, n = r;
		} finally {
			try {
				if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) {
					return;
				}
			} finally {
				if (o) {
					throw n;
				}
			}
		}
		return a;
	}
}
function _arrayWithHoles4(r) {
	if (Array.isArray(r)) {
		return r;
	}
}
function _slicedToArray3(r, e) {
	return _arrayWithHoles3(r) || _iterableToArrayLimit3(r, e) || _unsupportedIterableToArray3(r, e) || _nonIterableRest3();
}
function _nonIterableRest3() {
	throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _iterableToArrayLimit3(r, l) {
	var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
	if (null != t) {
		var e,
			n,
			i,
			u,
			a = [],
			f = !0,
			o = !1;
		try {
			if (i = (t = t.call(r)).next, 0 === l) {
				if (Object(t) !== t) {
					return;
				}
				f = !1;
			} else {
				for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0) {
					;
				}
			}
		} catch (r) {
			o = !0, n = r;
		} finally {
			try {
				if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) {
					return;
				}
			} finally {
				if (o) {
					throw n;
				}
			}
		}
		return a;
	}
}
function _arrayWithHoles3(r) {
	if (Array.isArray(r)) {
		return r;
	}
}
function _createForOfIteratorHelper3(r, e) {
	var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
	if (!t) {
		if (Array.isArray(r) || (t = _unsupportedIterableToArray3(r)) || e && r && "number" == typeof r.length) {
			t && (r = t);
			var _n3 = 0,
				F = function F() {};
			return {
				s: F,
				n: function n() {
					return _n3 >= r.length ? {
						done: !0
					} : {
						done: !1,
						value: r[_n3++]
					};
				},
				e: function e(r) {
					throw r;
				},
				f: F
			};
		}
		throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
	}
	var o,
		a = !0,
		u = !1;
	return {
		s: function s() {
			t = t.call(r);
		},
		n: function n() {
			var r = t.next();
			return a = r.done, r;
		},
		e: function e(r) {
			u = !0, o = r;
		},
		f: function f() {
			try {
				a || null == t["return"] || t["return"]();
			} finally {
				if (u) {
					throw o;
				}
			}
		}
	};
}
function _unsupportedIterableToArray3(r, a) {
	if (r) {
		if ("string" == typeof r) {
			return _arrayLikeToArray3(r, a);
		}
		var t = {}.toString.call(r).slice(8, -1);
		return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray3(r, a) : void 0;
	}
}
function _arrayLikeToArray3(r, a) {
	(null == a || a > r.length) && (a = r.length);
	for (var e = 0, n = Array(a); e < a; e++) {
		n[e] = r[e];
	}
	return n;
}
function _slicedToArray2(r, e) {
	return _arrayWithHoles2(r) || _iterableToArrayLimit2(r, e) || _unsupportedIterableToArray2(r, e) || _nonIterableRest2();
}
function _nonIterableRest2() {
	throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _iterableToArrayLimit2(r, l) {
	var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
	if (null != t) {
		var e,
			n,
			i,
			u,
			a = [],
			f = !0,
			o = !1;
		try {
			if (i = (t = t.call(r)).next, 0 === l) {
				if (Object(t) !== t) {
					return;
				}
				f = !1;
			} else {
				for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0) {
					;
				}
			}
		} catch (r) {
			o = !0, n = r;
		} finally {
			try {
				if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) {
					return;
				}
			} finally {
				if (o) {
					throw n;
				}
			}
		}
		return a;
	}
}
function _arrayWithHoles2(r) {
	if (Array.isArray(r)) {
		return r;
	}
}
function _createForOfIteratorHelper2(r, e) {
	var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
	if (!t) {
		if (Array.isArray(r) || (t = _unsupportedIterableToArray2(r)) || e && r && "number" == typeof r.length) {
			t && (r = t);
			var _n2 = 0,
				F = function F() {};
			return {
				s: F,
				n: function n() {
					return _n2 >= r.length ? {
						done: !0
					} : {
						done: !1,
						value: r[_n2++]
					};
				},
				e: function e(r) {
					throw r;
				},
				f: F
			};
		}
		throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
	}
	var o,
		a = !0,
		u = !1;
	return {
		s: function s() {
			t = t.call(r);
		},
		n: function n() {
			var r = t.next();
			return a = r.done, r;
		},
		e: function e(r) {
			u = !0, o = r;
		},
		f: function f() {
			try {
				a || null == t["return"] || t["return"]();
			} finally {
				if (u) {
					throw o;
				}
			}
		}
	};
}
function _unsupportedIterableToArray2(r, a) {
	if (r) {
		if ("string" == typeof r) {
			return _arrayLikeToArray2(r, a);
		}
		var t = {}.toString.call(r).slice(8, -1);
		return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray2(r, a) : void 0;
	}
}
function _arrayLikeToArray2(r, a) {
	(null == a || a > r.length) && (a = r.length);
	for (var e = 0, n = Array(a); e < a; e++) {
		n[e] = r[e];
	}
	return n;
}
function _slicedToArray(r, e) {
	return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest();
}
function _nonIterableRest() {
	throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _iterableToArrayLimit(r, l) {
	var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
	if (null != t) {
		var e,
			n,
			i,
			u,
			a = [],
			f = !0,
			o = !1;
		try {
			if (i = (t = t.call(r)).next, 0 === l) {
				if (Object(t) !== t) {
					return;
				}
				f = !1;
			} else {
				for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0) {
					;
				}
			}
		} catch (r) {
			o = !0, n = r;
		} finally {
			try {
				if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) {
					return;
				}
			} finally {
				if (o) {
					throw n;
				}
			}
		}
		return a;
	}
}
function _arrayWithHoles(r) {
	if (Array.isArray(r)) {
		return r;
	}
}
function _createForOfIteratorHelper(r, e) {
	var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
	if (!t) {
		if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) {
			t && (r = t);
			var _n = 0,
				F = function F() {};
			return {
				s: F,
				n: function n() {
					return _n >= r.length ? {
						done: !0
					} : {
						done: !1,
						value: r[_n++]
					};
				},
				e: function e(r) {
					throw r;
				},
				f: F
			};
		}
		throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
	}
	var o,
		a = !0,
		u = !1;
	return {
		s: function s() {
			t = t.call(r);
		},
		n: function n() {
			var r = t.next();
			return a = r.done, r;
		},
		e: function e(r) {
			u = !0, o = r;
		},
		f: function f() {
			try {
				a || null == t["return"] || t["return"]();
			} finally {
				if (u) {
					throw o;
				}
			}
		}
	};
}
function _unsupportedIterableToArray(r, a) {
	if (r) {
		if ("string" == typeof r) {
			return _arrayLikeToArray(r, a);
		}
		var t = {}.toString.call(r).slice(8, -1);
		return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0;
	}
}
function _arrayLikeToArray(r, a) {
	(null == a || a > r.length) && (a = r.length);
	for (var e = 0, n = Array(a); e < a; e++) {
		n[e] = r[e];
	}
	return n;
}
var flowerManager = new FlowerManager();
var titleScreen = new Container();
var background = LK.getAsset('titlebackground', {
	anchorX: 0.5,
	anchorY: 0.5,
	x: 2048 / 2,
	y: 2732 / 2
});
titleScreen.addChild(background);
var logo = LK.getAsset('logo', {
	anchorX: 0.5,
	anchorY: 0.5,
	x: 2048 / 2,
	y: 2732 / 2
});
titleScreen.addChild(logo);
var playButton = LK.getAsset('playButton', {
	anchorX: 0.5,
	anchorY: 0.5,
	x: 2048 / 2,
	y: 2732 / 2 + 200
});
titleScreen.addChild(playButton);
var tutorialButton = LK.getAsset('tutorialButton', {
	anchorX: 0.5,
	anchorY: 0.5,
	x: 2048 / 2,
	y: 2732 / 2 + 400
});
titleScreen.addChild(tutorialButton);
game.addChild(titleScreen);
playButton.down = function (x, y, obj) {
	game.removeChild(titleScreen);
	var gardenBackground = new GardenBackground();
	game.addChild(gardenBackground);
	garden = new Garden();
	garden.init();
	game.addChild(garden);
	var flowerManager = new FlowerManager();
	// Initialize score manager
	game.scoreManager = new ScoreManager();
	game.addChild(game.scoreManager);
	game.seasonManager = new SeasonManager();
	game.seasonManager.init();
	game.flowerMatcher = new FlowerMatcher();
	game.addChild(game.flowerMatcher);
	var pollenTrail = new PollenTrail();
	game.addChild(pollenTrail);
	// Create bee and position above hive
	var bee = new Bee();
	bee.x = 2048 / 2;
	bee.y = 2732 / 2;
	game.addChild(bee);
	// Ensure pollen particles are rendered on top by adding them last
	game.setChildIndex(pollenTrail, game.children.length - 1);
	// Initialize bud spawner
	garden.budSpawner = new BudSpawner();
	garden.budSpawner.init(garden);
	game.addChild(garden.budSpawner);
	// Touch handlers
	game.down = function (x, y, obj) {
		function showDebugText(message, color) {
			var debugText = new Text2(message, {
				size: 120,
				fill: color
			});
			// Start with no anchor adjustment
			debugText.anchor.set(1, 0);
			// Try positioning at 0,0 first just to see where it appears
			debugText.x = 400;
			debugText.y = 400;
			LK.gui.top.addChild(debugText);
			tween(debugText, {
				alpha: 0
			}, {
				duration: 1000,
				onFinish: function onFinish() {
					LK.gui.top.removeChild(debugText);
				}
			});
		}
		// Debug zones same as before
		if (x > 824 && x < 1224 && y < 200) {
			showDebugText("SPRING MODE", 0x00FF00);
			game.seasonManager.setActiveSeason(game.seasonManager.SEASONS.SPRING);
			return;
		}
		if (x > 1848 && y < 200) {
			showDebugText("SUMMER MODE", 0xFFFF00);
			return;
		}
		if (x < 200 && y > 2532) {
			showDebugText("FALL MODE", 0xFF6600);
			return;
		}
		if (x > 1848 && y > 2532) {
			showDebugText("WINTER MODE", 0x00FFFF);
			return;
		}
		// Convert touch position to world space
		var touchPos = game.toLocal({
			x: x,
			y: y
		}, LK.stage);
		// Check if touch is on bee
		var dx = touchPos.x - bee.x;
		var dy = touchPos.y - bee.y;
		var distance = Math.sqrt(dx * dx + dy * dy);
		if (distance < 100) {
			// Increased from 50 to 100 
			// Adjust radius as needed
			bee.state = 'free';
			bee.isMoving = true;
			// Set initial target to current position to prevent jumping
			bee.targetX = bee.x;
			bee.targetY = bee.y;
			// Then update target to the current touch position
			bee.targetX = touchPos.x;
			bee.targetY = touchPos.y;
		} else {
			bee.state = 'transit';
			bee.targetX = touchPos.x;
			bee.targetY = touchPos.y;
		}
	};
	game.move = function (x, y, obj) {
		if (bee.isMoving) {
			bee.targetX = x;
			bee.targetY = y - 200;
		}
	};
	game.up = function (x, y, obj) {
		bee.isMoving = false;
	};
	// Initialize score display
	var scoreDisplay = new ScoreDisplay();
	scoreDisplay.anchor.set(0.5, 0);
	LK.gui.top.addChild(scoreDisplay);
	game.scoreDisplay = scoreDisplay;
	// Add the main update loop
	game.update = function () {
		// Update spawning system
		if (game.budSpawner) {
			game.budSpawner.update();
		}
		// Update trail system
		if (pollenTrail) {
			pollenTrail.update();
		}
		// Update garden elements
		if (garden) {
			// Update all flowers and buds in the grid
			for (var i = 0; i < garden.rows; i++) {
				for (var j = 0; j < garden.cols; j++) {
					var gridItem = garden.grid[i][j];
					if (gridItem && gridItem.update) {
						gridItem.update();
					}
				}
			}
		}
		// Update all children that have update methods
		for (var i = 0; i < game.children.length; i++) {
			var child = game.children[i];
			if (child && child.update) {
				child.update();
			}
		}
		// Update bee
		if (bee && bee.update) {
			bee.update();
		}
		if (game.seasonManager) {
			game.seasonManager.update();
		}
	};
};
tutorialButton.down = function (x, y, obj) {
	// Open tutorial
};
// Removed duplicate playPollenPatternAnimation method ===================================================================
--- original.js
+++ change.js
@@ -1805,9 +1805,11 @@
 		// Check for completed goals and cycle display
 		if (garden.goalQueue && garden.goalQueue.length > 0) {
 			for (var i = garden.goalDisplay.children.length - 1; i >= 0; i--) {
 				var displayedGoal = garden.goalDisplay.children[i];
-				var goalColor = garden.goalQueue[i].color;
+				if (garden.goalQueue[i]) {
+					var goalColor = garden.goalQueue[i].color;
+				}
 				if (garden.currentFlowers[goalColor] >= garden.flowerGoals[goalColor]) {
 					// Create closure to capture correct index
 					(function (index, goal) {
 						// Animate out completed goal
 
 
 
 
 
 
 
 
 A background image for a puzzle video game depicting the season of summer. Cartoon. Single Game Texture. In-Game asset. 2d. Blank background. High contrast. No shadows.
 A background image for a puzzle video game depicting the season of fall. Cartoon. Single Game Texture. In-Game asset. 2d. Blank background. High contrast. No shadows.
 A background image for a puzzle video game depicting the season of winter. Cartoon. Single Game Texture. In-Game asset. 2d. Blank background. High contrast. No shadows.
 
 
 
 
 
 
 
 
 Multiple stylized texts with phrases that include “Hurry!” “Time’s up!” Cartoon style.. Single Game Texture. In-Game asset. 2d. Blank background. High contrast. No shadows.
 
 Create a SVG text design in bold cartoon style: "SPRING" in chunky rounded letters with floral accents and vines. Use spring pastels.. Single Game Texture. In-Game asset. 2d. Blank background. High contrast. No shadows.
 Create an SVG text design for "SUMMER" in bold cartoon style with chunky rounded letters. Add sun rays and small flower details in warm, vibrant colors.. Single Game Texture. In-Game asset. 2d. Blank background. High contrast. No shadows.
 Create an SVG text design for "FALL" in bold cartoon style with chunky rounded letters. Add small falling leaves and acorn accents in warm autumn colors.. Single Game Texture. In-Game asset. 2d. Blank background. High contrast. No shadows.
 Create an SVG text design for "WINTER" in bold cartoon style with chunky rounded letters. Add small snowflake accents and icy details in cool, frosty blues and white.. Single Game Texture. In-Game asset. 2d. Blank background. High contrast. No shadows.
 Create a SVG text design in bold cartoon style: “Bloom the garden" in chunky rounded letters with floral accents and vines. Use spring pastels.. Single Game Texture. In-Game asset. 2d. Blank background. High contrast. No shadows.
 Create an SVG text design for "Match the blooms" in bold cartoon style with chunky rounded letters. Add sun rays and small flower details in warm, vibrant colors.. Single Game Texture. In-Game asset. 2d. Blank background. High contrast. No shadows.
 Create an SVG text design for "Match to clear leaves" in bold cartoon style with chunky rounded letters. Add small falling leaves and acorn accents in warm autumn colors.. Single Game Texture. In-Game asset. 2d. Blank background. High contrast. No shadows.
 Create an SVG text design for "DANCE TO STAY WARM" in bold cartoon style with chunky rounded letters. Add small snowflake accents and icy details in cool, frosty blues and white.. Single Game Texture. In-Game asset. 2d. Blank background. High contrast. No shadows.
 
 
 
 
 
 
 
 Create a SVG text design in bold cartoon style: "SEASON COMPLETE!" in chunky rounded letters with stars around it . Single Game Texture. In-Game asset. 2d. Blank background. High contrast. No shadows.