/**** 
* Plugins
****/ 
var tween = LK.import("@upit/tween.v1");
var storage = LK.import("@upit/storage.v1");
/**** 
* Classes
****/ 
var AirBlock = Container.expand(function () {
	var self = Container.call(this);
	var airBlockGraphics = self.attachAsset('AirBlockAsset', {
		anchorX: 0.5,
		anchorY: 0.5,
		scaleX: 1.0,
		scaleY: 1.0,
		smooth: true,
		filterQuality: 1
	});
	self.speed = level === 5 ? 18 : 12; // Increased speed for AirBlocks in Level 5
	self.update = function () {
		self.y -= self.speed;
	};
	return self;
});
var Airblockasset1 = Container.expand(function () {
	var self = Container.call(this);
	var airblock1Graphics = self.attachAsset('Airblockasset1', {
		anchorX: 0.5,
		anchorY: 0.5,
		scaleX: 1.0,
		scaleY: 1.0,
		smooth: true,
		filterQuality: 1
	});
	self.speed = level === 5 ? 18 : 12;
	// Start continuous rotation to the right
	self.startRotation = function () {
		function rotateRight() {
			if (self && !self.destroyed) {
				tween(self, {
					rotation: self.rotation + Math.PI * 2
				}, {
					duration: 2000,
					easing: tween.linear,
					onFinish: rotateRight
				});
			}
		}
		rotateRight();
	};
	self.update = function () {
		self.y -= self.speed;
	};
	return self;
});
var Airblockasset2 = Container.expand(function () {
	var self = Container.call(this);
	var airblock2Graphics = self.attachAsset('Airblockasset2', {
		anchorX: 0.5,
		anchorY: 0.5,
		scaleX: 1.0,
		scaleY: 1.0,
		smooth: true,
		filterQuality: 1
	});
	self.speed = level === 5 ? 18 : 12;
	// Start continuous flipping from right to left
	self.startFlipping = function () {
		function flipRightLeft() {
			if (self && !self.destroyed) {
				tween(airblock2Graphics, {
					scaleX: -1.0
				}, {
					duration: 1000,
					easing: tween.linear,
					onFinish: function onFinish() {
						if (self && !self.destroyed) {
							tween(airblock2Graphics, {
								scaleX: 1.0
							}, {
								duration: 1000,
								easing: tween.linear,
								onFinish: flipRightLeft
							});
						}
					}
				});
			}
		}
		flipRightLeft();
	};
	self.update = function () {
		self.y -= self.speed;
	};
	return self;
});
//<Assets used in the game will automatically appear here>
//<Write imports for supported plugins here>
// Dragon class to represent the player character
var Dragon = Container.expand(function () {
	var self = Container.call(this);
	// Function to get the appropriate dragon asset based on level
	self.getDragonAsset = function () {
		if (level === 2) {
			return 'Lavadragon';
		}
		if (level === 3) {
			return 'Snowdragon';
		}
		if (level === 4) {
			return 'Stonedragon';
		}
		if (level === 5) {
			return 'Airdragon';
		}
		return 'dragon'; // Default for level 1
	};
	var dragonGraphics = self.attachAsset(self.getDragonAsset(), {
		anchorX: 0.5,
		anchorY: 0.5,
		scaleX: 2.0,
		scaleY: 2.0,
		smooth: true,
		filterQuality: 2
	});
	self.speed = 20; // Further increase the speed of the dragon
	self.currentLevel = level; // Track current level for asset changes
	// Function to update dragon asset when level changes
	self.updateDragonAsset = function () {
		if (self.currentLevel !== level) {
			self.currentLevel = level;
			// Remove old graphics
			dragonGraphics.destroy();
			// Create new graphics with appropriate asset
			dragonGraphics = self.attachAsset(self.getDragonAsset(), {
				anchorX: 0.5,
				anchorY: 0.5,
				scaleX: self.x < 2048 / 2 ? -2.0 : 2.0,
				scaleY: 2.0,
				smooth: true,
				filterQuality: 2
			});
		}
	};
	self.update = function () {
		// Update dragon asset if level changed
		self.updateDragonAsset();
		// Update logic for the dragon to flip based on movement direction
		if (self.x < 2048 / 2) {
			dragonGraphics.scaleX = -2.0; // Flip horizontally when on the left side of the screen
		} else {
			dragonGraphics.scaleX = 2.0; // Normal orientation when on the right side of the screen
		}
		// Removed unnecessary variable to optimize performance
	};
	return self;
});
// Fireball class to represent the fireballs that the dragon shoots
var Fireball = Container.expand(function (assetId) {
	var self = Container.call(this);
	var fireballGraphics = self.attachAsset(assetId, {
		anchorX: 0.5,
		anchorY: 0.5,
		scaleX: 0.6,
		scaleY: 0.9,
		smooth: true,
		filterQuality: 1
	});
	self.speed = 15; // Increase the speed of the fireballs
	self.update = function () {
		self.y += self.speed;
	};
});
// HealthBar class to represent the player's health
var HealthBar = Container.expand(function () {
	var self = Container.call(this);
	var healthBarGraphics = self.attachAsset('healthBar', {
		anchorX: 0.2,
		anchorY: 0.0,
		scaleX: 3800 / 1000,
		// Scale to fit the game width
		scaleY: 0.1
	});
	self.maxHealth = 500;
	self.currentHealth = self.maxHealth;
	self.update = function () {
		healthBarGraphics.scaleX = self.currentHealth / self.maxHealth;
		healthBarGraphics.scaleY = 0.05; // Resize the health bar to fit the top of the screen
	};
});
var Icerocks = Container.expand(function () {
	var self = Container.call(this);
	var icerocksGraphics = self.attachAsset('Icerocks', {
		anchorX: 0.5,
		anchorY: 0.5,
		scaleX: level === 3 ? 1.5 : 1.0,
		scaleY: level === 3 ? 1.5 : 1.0,
		smooth: true,
		filterQuality: 1
	});
	self.speed = level === 3 ? 15 : 5; // Further increase speed for level 3
	self.update = function () {
		self.y -= self.speed;
	};
});
var Icerocks1 = Container.expand(function () {
	var self = Container.call(this);
	var icerocks1Graphics = self.attachAsset('Icerocks1', {
		anchorX: 0.5,
		anchorY: 0.5,
		scaleX: level === 3 ? 1.5 : 1.0,
		scaleY: level === 3 ? 1.5 : 1.0,
		smooth: true,
		filterQuality: 1
	});
	self.speed = level === 3 ? 15 : 5; // Further increase speed for level 3
	self.update = function () {
		// Move the icerocks upwards
		self.y -= self.speed;
	};
});
var Icerocks2 = Container.expand(function () {
	var self = Container.call(this);
	var icerocks2Graphics = self.attachAsset('Icerocks2', {
		anchorX: 0.5,
		anchorY: 0.5,
		scaleX: level === 3 ? 1.5 : 1.0,
		scaleY: level === 3 ? 1.5 : 1.0,
		smooth: true,
		filterQuality: 1
	});
	self.speed = level === 3 ? 15 : 5; // Further increase speed for level 3
	self.update = function () {
		// Move the icerocks upwards
		self.y -= self.speed;
	};
});
var Land01 = Container.expand(function () {
	var self = Container.call(this);
	var land01Graphics = self.attachAsset('Land01', {
		anchorX: 0.5,
		anchorY: 0.5,
		scaleX: 1.0,
		scaleY: 1.0,
		smooth: true,
		filterQuality: 1
	});
	self.speed = 15; // Further increase the speed of the Land01
	self.update = function () {
		self.y -= self.speed;
	};
	return self;
});
var Lavarocks = Container.expand(function () {
	var self = Container.call(this);
	var lavarocksGraphics = self.attachAsset('Lavarocks', {
		anchorX: 0.5,
		anchorY: 0.5,
		scaleX: level === 2 ? 1.5 : 1.0,
		scaleY: level === 2 ? 1.5 : 1.0,
		smooth: true,
		filterQuality: 1
	});
	self.speed = level === 2 ? 20 : 5; // Maximum increase speed for level 2
	self.update = function () {
		self.y -= self.speed;
	};
});
var Lavarocks1 = Container.expand(function () {
	var self = Container.call(this);
	var lavarocks1Graphics = self.attachAsset('Lavarocks1', {
		anchorX: 0.5,
		anchorY: 0.5,
		scaleX: level === 2 ? 1.5 : 1.0,
		scaleY: level === 2 ? 1.5 : 1.0,
		smooth: true,
		filterQuality: 1
	});
	self.speed = level === 2 ? 20 : 5; // Maximum increase speed for level 2
	self.update = function () {
		// Move the lavarocks1 upwards
		self.y -= self.speed;
	};
});
var Lavarocks2 = Container.expand(function () {
	var self = Container.call(this);
	var lavarocks2Graphics = self.attachAsset('Lavarocks2', {
		anchorX: 0.5,
		anchorY: 0.5,
		scaleX: level === 2 ? 1.5 : 1.0,
		scaleY: level === 2 ? 1.5 : 1.0,
		smooth: true,
		filterQuality: 1
	});
	self.speed = level === 2 ? 20 : 5; // Maximum increase speed for level 2
	self.update = function () {
		// Move the lavarocks2 upwards
		self.y -= self.speed;
	};
});
var Stone = Container.expand(function () {
	var self = Container.call(this);
	var stoneGraphics = self.attachAsset('Stone', {
		anchorX: 0.5,
		anchorY: 0.5,
		scaleX: 0.3,
		scaleY: 0.3,
		smooth: true,
		filterQuality: 1
	});
	self.speed = level === 4 ? 15 : 10; // Further increase speed for Stone objects in level 4
	self.update = function () {
		self.y -= self.speed;
	};
});
var StoneCircle = Container.expand(function () {
	var self = Container.call(this);
	var stoneCircleGraphics = self.attachAsset('StoneCircle', {
		anchorX: 0.5,
		anchorY: 0.5,
		scaleX: 0.5,
		scaleY: 0.5,
		smooth: true,
		filterQuality: 1
	});
	self.speed = level === 4 ? 15 : 10; // Further increase speed for StoneCircle objects in level 4
	self.update = function () {
		// Move the stones upwards
		self.y -= self.speed;
	};
});
var StoneSquare = Container.expand(function () {
	var self = Container.call(this);
	var stoneSquareGraphics = self.attachAsset('StoneSquare', {
		anchorX: 0.5,
		anchorY: 0.5,
		scaleX: 0.5,
		scaleY: 0.5,
		smooth: true,
		filterQuality: 1
	});
	self.speed = level === 4 ? 15 : 10; // Further increase speed for StoneSquare objects in level 4
	self.update = function () {
		// Move the stones upwards
		self.y -= self.speed;
	};
});
/**** 
* Initialize Game
****/ 
var game = new LK.Game({
	backgroundColor: 0x000000,
	//Init game with black background
	height: 3000 // Increase the game screen height
});
/**** 
* Game Code
****/ 
// or via static code analysis based on their usage in the code.
// Function to show the level text once
function showLevelTextOnce() {
	// Make sure levelTxtOrange is defined and visible
	if (levelTxtOrange) {
		levelTxtOrange.setText('Level: ' + level); // Update text content
		levelTxtOrange.visible = true;
		LK.setTimeout(function () {
			if (levelTxtOrange) {
				levelTxtOrange.visible = false;
			}
			// Start respawning objects after the text has hidden
			// This ensures objects for the new level start appearing after the level announcement
			startRespawningObjects();
		}, 1500); // Show text for 1.5 seconds
	} else {
		// Fallback or error logging if levelTxtOrange is not ready
		console.log("Error: levelTxtOrange not initialized before showLevelTextOnce call.");
		startRespawningObjects(); // Still try to start respawning
	}
}
function startRespawningObjects() {
	// Logic to start respawning objects based on the current level
	if (level === 1) {
		// Respawn Explosions randomly in level 1
		if (!LK.gameOver && LK.ticks % 60 == 0 && levelTxtOrange.visible === false) {
			var newExplosion;
			for (var i = 0; i < spheres.length; i++) {
				if (spheres[i] instanceof Explosion && spheres[i].y < -200) {
					newExplosion = spheres[i];
					break;
				}
			}
			if (!newExplosion) {
				newExplosion = new Explosion();
				spheres.push(newExplosion);
				game.addChild(newExplosion);
			}
			newExplosion.x = Math.random() * (2048 - newExplosion.width) + newExplosion.width / 2;
			newExplosion.y = 2732;
		}
	} else if (level === 2) {
		// Respawn Lavarocks, Lavarocks1, and Lavarocks2 randomly in level 2
		if (!LK.gameOver && LK.ticks % 70 == 0) {
			var newLavarock;
			for (var i = 0; i < spheres.length; i++) {
				if ((spheres[i] instanceof Lavarocks || spheres[i] instanceof Lavarocks1 || spheres[i] instanceof Lavarocks2) && spheres[i].y < -200) {
					newLavarock = spheres[i];
					break;
				}
			}
			if (!newLavarock) {
				var randomType = Math.floor(Math.random() * 5);
				if (randomType === 0) {
					newLavarock = new Lavarocks();
				} else if (randomType === 1) {
					newLavarock = new Lavarocks1();
				} else {
					newLavarock = new Lavarocks2();
				}
				spheres.push(newLavarock);
				game.addChild(newLavarock);
			}
			newLavarock.x = Math.random() * (2048 - newLavarock.width) + newLavarock.width / 2;
			newLavarock.y = 2732;
			var randomScale = 1.0 + Math.random() * 1.0; // Random scale between 1.0 and 2.0
			newLavarock.scaleX = randomScale;
			newLavarock.scaleY = randomScale;
		}
	} else if (level === 3) {
		// Respawn Icerocks randomly in level 3
		if (!LK.gameOver && LK.ticks % 80 == 0) {
			var newIcerock;
			for (var i = 0; i < spheres.length; i++) {
				if ((spheres[i] instanceof Icerocks || spheres[i] instanceof Icerocks1 || spheres[i] instanceof Icerocks2) && spheres[i].y < -200) {
					newIcerock = spheres[i];
					break;
				}
			}
			if (!newIcerock) {
				var randomType = Math.floor(Math.random() * 3);
				if (randomType === 0) {
					newIcerock = new Icerocks();
				} else if (randomType === 1) {
					newIcerock = new Icerocks1();
				} else {
					newIcerock = new Icerocks2();
				}
				spheres.push(newIcerock);
				game.addChild(newIcerock);
			}
			newIcerock.x = Math.random() * (2048 - newIcerock.width) + newIcerock.width / 2;
			newIcerock.y = 2732;
			var randomScaleX = 1.0 + Math.random() * 1.0; // Random scale between 1.0 and 2.0 for width
			var randomScaleY = 1.0 + Math.random() * 1.5; // Random scale between 1.0 and 2.5 for height
			newIcerock.scaleX = randomScaleX;
			newIcerock.scaleY = randomScaleY;
		}
	} else if (level === 5) {
		// Respawn AirBlocks randomly in level 5
		if (!LK.gameOver && LK.ticks % 100 == 0) {
			// Retaining tick condition for consistency
			var newAirBlock;
			for (var i = 0; i < spheres.length; i++) {
				if ((spheres[i] instanceof AirBlock || spheres[i] instanceof Airblockasset1 || spheres[i] instanceof Airblockasset2) && spheres[i].y < -200) {
					newAirBlock = spheres[i];
					break;
				}
			}
			if (!newAirBlock) {
				var randomType = Math.floor(Math.random() * 3);
				if (randomType === 0) {
					newAirBlock = new AirBlock();
				} else if (randomType === 1) {
					newAirBlock = new Airblockasset1();
					if (newAirBlock.startRotation) {
						newAirBlock.startRotation();
					}
				} else {
					newAirBlock = new Airblockasset2();
					if (newAirBlock.startFlipping) {
						newAirBlock.startFlipping();
					}
				}
				spheres.push(newAirBlock);
				game.addChild(newAirBlock);
			}
			newAirBlock.x = Math.random() * (2048 - newAirBlock.width) + newAirBlock.width / 2;
			newAirBlock.y = 2732;
			var randomScaleAir = 1.0 + Math.random() * 1.0;
			newAirBlock.scaleX = randomScaleAir;
			newAirBlock.scaleY = randomScaleAir;
			// Add continuous rotation animation to the right for original AirBlock
			if (newAirBlock instanceof AirBlock) {
				tween(newAirBlock, {
					rotation: Math.PI * 2
				}, {
					duration: 2000,
					easing: tween.linear,
					onFinish: function onFinish() {
						// Start the animation again for continuous rotation
						function rotateAirBlock() {
							if (newAirBlock && !newAirBlock.destroyed) {
								tween(newAirBlock, {
									rotation: newAirBlock.rotation + Math.PI * 2
								}, {
									duration: 2000,
									easing: tween.linear,
									onFinish: rotateAirBlock
								});
							}
						}
						rotateAirBlock();
					}
				});
			}
		}
	}
}
// Function to show the level text twice
function showLevelTextTwice() {
	levelTxtOrange.fill = 0x0000ff; // Blue color
	levelTxtOrange.visible = true;
	LK.setTimeout(function () {
		levelTxtOrange.visible = false;
		LK.setTimeout(function () {
			levelTxtOrange.visible = true;
			LK.setTimeout(function () {
				levelTxtOrange.visible = false;
				// Start respawning objects after the text has shown and hidden for the last time
				startRespawningObjects();
			}, 500);
		}, 500);
	}, 500);
}
// Add background image for level 4
var backgroundLevel4 = LK.getAsset('Stone_lands', {
	anchorX: 0.0,
	anchorY: 0.0
});
backgroundLevel4.smooth = true;
backgroundLevel4.filterQuality = 0; // Further increase the filter quality for better clarity
backgroundLevel4.scale.set(2048 / 800, 2732 / 800);
backgroundLevel4.smooth = true; // Enable smoothing to remove pixelation
backgroundLevel4.filterQuality = 0; // Adjust filter quality for better clarity
backgroundLevel4.visible = false; // Initially hidden
game.addChild(backgroundLevel4);
// Add background image for level 5
var backgroundLevel5 = LK.getAsset('SkyBackground', {
	anchorX: 0.0,
	anchorY: 0.0
});
backgroundLevel5.smooth = true;
backgroundLevel5.filterQuality = 0;
backgroundLevel5.scale.set(2048 / 800, 2732 / 800);
backgroundLevel5.visible = false; // Initially hidden
game.addChild(backgroundLevel5);
// Initialize game variables
var dragon;
var spheres = [];
var fireballs = []; // Initialize fireballs array
var score = 0; // Initialize score to 0
var scoreTxt;
var level = 1; // Initialize level to 1
var introBackground,
	startButton,
	gameStarted = false;
var healthBar; // Declare healthBar globally, will be initialized in setupActiveGame
var healthTxt; // Declare healthTxt globally for health text display
var nextHealthRestoreScore = 1000; // Track the next score milestone for health restoration
// Add background image to the game for level 1
var backgroundLevel1 = LK.getAsset('Green_lands', {
	anchorX: 0.0,
	anchorY: 0.0
});
backgroundLevel1.smooth = true; // Enable smoothing to remove pixelation
backgroundLevel1.filterQuality = 0; // Adjust filter quality for better clarity
backgroundLevel1.scale.set(2048 / 800, 2732 / 800); // Scale the background to fit the screen 
backgroundLevel1.smooth = true; // Enable smoothing to remove pixelation
backgroundLevel1.filterQuality = 0; // Further increase the filter quality for better clarity
backgroundLevel1.visible = true; // Initially visible
game.addChild(backgroundLevel1);
// Add background image for level 2
var backgroundLevel2 = LK.getAsset('Lava_lands', {
	anchorX: 0.0,
	anchorY: 0.0
});
backgroundLevel2.smooth = true;
backgroundLevel2.filterQuality = 0; // Further increase the filter quality for better clarity
backgroundLevel2.scale.set(2048 / 800, 2732 / 800);
backgroundLevel2.smooth = true; // Enable smoothing to remove pixelation
backgroundLevel2.filterQuality = 2; // Increase filter quality for better clarity
backgroundLevel2.visible = false; // Initially hidden
game.addChild(backgroundLevel2);
// Add background image for level 3
var backgroundLevel3 = LK.getAsset('Ice_lands', {
	anchorX: 0.0,
	anchorY: 0.0
});
backgroundLevel3.smooth = true;
backgroundLevel3.filterQuality = 2; // Increase filter quality for better clarity
backgroundLevel3.scale.set(2048 / 800, 2732 / 800); // Scale the background to fit the screen
backgroundLevel3.smooth = true; // Enable smoothing to remove pixelation
backgroundLevel3.filterQuality = 2; // Further increase the filter quality for better clarity
backgroundLevel3.visible = false; // Initially hidden
game.addChild(backgroundLevel3);
// Refresh the background to be clearer & fit to screen every 60 ticks
game.update = function () {
	backgroundLevel1.x = 2048 / 2; // Center the background horizontally
	backgroundLevel1.y = 2732 / 2; // Center the background vertically
	if (backgroundLevel1.y >= 2732) {
		backgroundLevel1.y = -2732;
	}
};
// Function to handle game updates
game.update = function () {
	if (!gameStarted) {
		// Game has not started, do nothing in the main update loop.
		// If intro elements had animations, they could be updated here.
		return;
	}
	// Reuse off-screen stones or spawn new ones if necessary
	if (level === 4 && !LK.gameOver && LK.ticks % 90 == 0) {
		var newStone;
		for (var i = 0; i < spheres.length; i++) {
			if ((spheres[i] instanceof Stone || spheres[i] instanceof StoneCircle || spheres[i] instanceof StoneSquare) && spheres[i].y < -200) {
				newStone = spheres[i];
				break;
			}
		}
		if (!newStone) {
			var randomType = Math.floor(Math.random() * 3);
			if (randomType === 0) {
				newStone = new Stone();
			} else if (randomType === 1) {
				newStone = new StoneCircle();
			} else {
				newStone = new StoneSquare();
			}
			spheres.push(newStone);
			game.addChild(newStone);
		}
		var randomScale = 1.0 + Math.random() * 1.0; // Random scale between 1.0 and 2.0
		newStone.scaleX = randomScale;
		newStone.scaleY = randomScale;
		newStone.x = Math.random() * (2048 - newStone.width) + newStone.width / 2;
		newStone.y = 2732;
	}
	// Check for collisions between fireballs and stones
	for (var i = fireballs.length - 1; i >= 0; i--) {
		if (fireballs[i].y > 2732) {
			fireballs[i].destroy();
			fireballs.splice(i, 1);
			continue;
		}
		for (var j = spheres.length - 1; j >= 0; j--) {
			if (fireballs[i].intersects(spheres[j]) && (spheres[j] instanceof Stone || spheres[j] instanceof StoneCircle || spheres[j] instanceof StoneSquare)) {
				var explosion4 = LK.getAsset('Explosion4', {
					anchorX: 0.5,
					anchorY: 0.5,
					scaleX: spheres[j].scaleX,
					scaleY: spheres[j].scaleY
				});
				explosion4.x = spheres[j].x;
				explosion4.y = spheres[j].y;
				game.addChild(explosion4);
				tween(explosion4, {
					alpha: 0
				}, {
					duration: 1000,
					onFinish: function onFinish() {
						explosion4.destroy();
					}
				});
				// Add random points from 0-40 when the dragon shoots the stones
				var points = Math.floor(Math.random() * 41);
				score += points;
				// Remove the fireball and the object from the game
				fireballs[i].destroy();
				fireballs.splice(i, 1);
				spheres[j].destroy();
				spheres.splice(j, 1);
				break;
			}
		}
	}
	// Check for collisions between dragon and stones
	for (var j = spheres.length - 1; j >= 0; j--) {
		if (dragon.intersects(spheres[j]) && (spheres[j] instanceof Stone || spheres[j] instanceof StoneCircle || spheres[j] instanceof StoneSquare)) {
			var explosion4 = LK.getAsset('Explosion4', {
				anchorX: 0.5,
				anchorY: 0.5,
				scaleX: spheres[j].scaleX,
				scaleY: spheres[j].scaleY
			});
			explosion4.x = spheres[j].x;
			explosion4.y = spheres[j].y;
			game.addChild(explosion4);
			tween(explosion4, {
				alpha: 0
			}, {
				duration: 1000,
				onFinish: function onFinish() {
					explosion4.destroy();
				}
			});
			// Decrease the dragon's health
			healthBar.currentHealth -= 20; // Consistent damage taken by the dragon from all objects in level 4
			// Remove the stone from the game
			spheres[j].destroy();
			spheres.splice(j, 1);
			break;
		}
	}
	if (!LK.gameOver && dragNode && dragNode.global) {
		dragNode.x = game.toLocal(dragNode.global).x;
	}
	// Reuse off-screen land01 or spawn new ones if necessary
	if (level === 1 && !LK.gameOver && LK.ticks % 60 == 0) {
		// Further reduce the interval for spawning land01 to add more land01 objects
		// Reduce the interval for spawning land01
		var newLand01;
		for (var i = 0; i < spheres.length; i++) {
			if (spheres[i] instanceof Land01 && spheres[i].y < -200) {
				// Check if the land01 is off-screen
				newLand01 = spheres[i];
				break;
			}
		}
		if (!newLand01) {
			newLand01 = new Land01();
			spheres.push(newLand01);
			game.addChild(newLand01);
		}
		var randomScale = 1.0 + Math.random() * 1.0; // Random scale between 1.0 and 2.0
		newLand01.scaleX = randomScale;
		newLand01.scaleY = randomScale;
		newLand01.x = Math.random() * (2048 - newLand01.width) + newLand01.width / 2;
		newLand01.y = 2732;
	}
	// Check for collisions between fireballs and land01 or Lavarocks
	for (var i = fireballs.length - 1; i >= 0; i--) {
		if (fireballs[i].y > 2732) {
			fireballs[i].destroy();
			fireballs.splice(i, 1);
			continue;
		}
		for (var j = spheres.length - 1; j >= 0; j--) {
			if (fireballs[i].intersects(spheres[j])) {
				if (spheres[j] instanceof Land01) {
					var explosion = LK.getAsset('explosion', {
						anchorX: 0.5,
						anchorY: 0.5,
						scaleX: spheres[j].scaleX,
						// Match the scale of the Land01 object
						scaleY: spheres[j].scaleY // Match the scale of the Land01 object
					});
					explosion.x = spheres[j].x;
					explosion.y = spheres[j].y;
					game.addChild(explosion);
					tween(explosion, {
						alpha: 0
					}, {
						duration: 1000,
						onFinish: function onFinish() {
							explosion.destroy();
						}
					});
				} else if (spheres[j] instanceof Lavarocks || spheres[j] instanceof Lavarocks1 || spheres[j] instanceof Lavarocks2) {
					var explosion2 = LK.getAsset('Explosion2', {
						anchorX: 0.5,
						anchorY: 0.5,
						scaleX: spheres[j].scaleX,
						// Match the scale of the Lavarocks object
						scaleY: spheres[j].scaleY // Match the scale of the Lavarocks object
					});
					explosion2.x = spheres[j].x;
					explosion2.y = spheres[j].y;
					game.addChild(explosion2);
					tween(explosion2, {
						alpha: 0
					}, {
						duration: 1000,
						onFinish: function onFinish() {
							explosion2.destroy();
						}
					});
				} else if (spheres[j] instanceof Icerocks || spheres[j] instanceof Icerocks1 || spheres[j] instanceof Icerocks2) {
					var explosion3 = LK.getAsset('Explosion3', {
						anchorX: 0.5,
						anchorY: 0.5,
						scaleX: spheres[j].scaleX,
						// Match the scale of the Icerocks object
						scaleY: spheres[j].scaleY // Match the scale of the Icerocks object
					});
					explosion3.x = spheres[j].x;
					explosion3.y = spheres[j].y;
					game.addChild(explosion3);
					tween(explosion3, {
						alpha: 0
					}, {
						duration: 1000,
						onFinish: function onFinish() {
							explosion3.destroy();
						}
					});
				} else if (spheres[j] instanceof AirBlock || spheres[j] instanceof Airblockasset1 || spheres[j] instanceof Airblockasset2) {
					var explosion5 = LK.getAsset('Explosion5', {
						anchorX: 0.5,
						anchorY: 0.5,
						scaleX: spheres[j].scaleX,
						scaleY: spheres[j].scaleY
					});
					explosion5.x = spheres[j].x;
					explosion5.y = spheres[j].y;
					game.addChild(explosion5);
					tween(explosion5, {
						alpha: 0
					}, {
						duration: 1000,
						onFinish: function onFinish() {
							explosion5.destroy();
						}
					});
				}
				// Add random points from 0-40 when the dragon shoots the land01 or Lavarocks
				var points = Math.floor(Math.random() * 41);
				score += points;
				// Remove the fireball and the object from the game
				fireballs[i].destroy();
				fireballs.splice(i, 1);
				spheres[j].destroy();
				spheres.splice(j, 1);
				break;
			}
		}
	}
	// Check for collisions between dragon and rocks
	for (var j = spheres.length - 1; j >= 0; j--) {
		if (dragon.intersects(spheres[j])) {
			if (spheres[j] instanceof Land01) {
				var explosion = LK.getAsset('explosion', {
					anchorX: 0.5,
					anchorY: 0.5,
					scaleX: spheres[j].scaleX,
					// Match the scale of the Land01 object
					scaleY: spheres[j].scaleY // Match the scale of the Land01 object
				});
				explosion.x = spheres[j].x;
				explosion.y = spheres[j].y;
				game.addChild(explosion);
				tween(explosion, {
					alpha: 0
				}, {
					duration: 1000,
					onFinish: function onFinish() {
						explosion.destroy();
					}
				});
			} else if (spheres[j] instanceof Lavarocks || spheres[j] instanceof Lavarocks1 || spheres[j] instanceof Lavarocks2) {
				var explosion2 = LK.getAsset('Explosion2', {
					anchorX: 0.5,
					anchorY: 0.5,
					scaleX: spheres[j].scaleX,
					// Match the scale of the Lavarocks object
					scaleY: spheres[j].scaleY // Match the scale of the Lavarocks object
				});
				explosion2.x = spheres[j].x;
				explosion2.y = spheres[j].y;
				game.addChild(explosion2);
				tween(explosion2, {
					alpha: 0
				}, {
					duration: 1000,
					onFinish: function onFinish() {
						explosion2.destroy();
					}
				});
			} else if (spheres[j] instanceof Icerocks || spheres[j] instanceof Icerocks1 || spheres[j] instanceof Icerocks2) {
				var explosion3 = LK.getAsset('Explosion3', {
					anchorX: 0.5,
					anchorY: 0.5,
					scaleX: spheres[j].scaleX,
					// Match the scale of the Icerocks object
					scaleY: spheres[j].scaleY // Match the scale of the Icerocks object
				});
				explosion3.x = spheres[j].x;
				explosion3.y = spheres[j].y;
				game.addChild(explosion3);
				tween(explosion3, {
					alpha: 0
				}, {
					duration: 1000,
					onFinish: function onFinish() {
						explosion3.destroy();
					}
				});
			} else if (spheres[j] instanceof AirBlock || spheres[j] instanceof Airblockasset1 || spheres[j] instanceof Airblockasset2) {
				var explosion5 = LK.getAsset('Explosion5', {
					anchorX: 0.5,
					anchorY: 0.5,
					scaleX: spheres[j].scaleX,
					scaleY: spheres[j].scaleY
				});
				explosion5.x = spheres[j].x;
				explosion5.y = spheres[j].y;
				game.addChild(explosion5);
				tween(explosion5, {
					alpha: 0
				}, {
					duration: 1000,
					onFinish: function onFinish() {
						explosion5.destroy();
					}
				});
			}
			// Decrease the dragon's health
			healthBar.currentHealth -= 20; // Consistent damage taken by the dragon from all objects in level 1
			// Remove the rock from the game
			spheres[j].destroy();
			spheres.splice(j, 1);
			break;
		}
		// Decrease dragon's health if any object passes the top of the screen
		if (spheres[j].y < -200) {
			healthBar.currentHealth -= 10; // Decrease health by 10 for each object
			spheres[j].destroy();
			spheres.splice(j, 1);
		}
		// Reuse off-screen lavarocks or spawn new ones if necessary
	}
	// Update the score display when the dragon gets points
	scoreTxt.setText('Score: ' + score);
	// Update the health text display
	if (healthTxt) {
		healthTxt.setText(healthBar.currentHealth.toString());
	}
	// Check if health bar reaches 0 to trigger game over
	if (healthBar.currentHealth <= 0 && !LK.gameOver) {
		// Save final score to recent scores storage when losing
		var storedScores = storage.recentScores || [];
		storedScores.unshift(score); // Add final score at beginning
		// Keep only top 5 scores
		if (storedScores.length > 5) {
			storedScores = storedScores.slice(0, 5);
		}
		// Sort scores in descending order
		storedScores.sort(function (a, b) {
			return b - a;
		});
		storage.recentScores = storedScores;
		// Save final score to high scores for logged in players when losing
		var highScores = storage.highScores || [];
		highScores.push(score); // Add final score
		// Sort high scores in descending order
		highScores.sort(function (a, b) {
			return b - a;
		});
		// Keep only top 5 high scores
		if (highScores.length > 5) {
			highScores = highScores.slice(0, 5);
		}
		storage.highScores = highScores;
		LK.effects.flashScreen(0xff0000, 1000); // Flash screen red for 1 second
		LK.showGameOver(); // Show game over screen with final score saved
	}
	// Regenerate player's health to max each time score crosses a 1000-point milestone
	while (score >= nextHealthRestoreScore) {
		healthBar.currentHealth = healthBar.maxHealth;
		nextHealthRestoreScore += 1000;
	}
	// Transition to the next level
	var scoreThresholds = [532, 1064, 1596, 2128, 2660]; // Score to complete level 1, 2, 3, 4, 5 respectively
	if (level <= 5 && score >= scoreThresholds[level - 1]) {
		level++;
		if (level > 5) {
			// Save score to recent scores storage when winning
			var storedScores = storage.recentScores || [];
			storedScores.unshift(score); // Add winning score at beginning
			// Keep only top 5 scores
			if (storedScores.length > 5) {
				storedScores = storedScores.slice(0, 5);
			}
			// Sort scores in descending order
			storedScores.sort(function (a, b) {
				return b - a;
			});
			storage.recentScores = storedScores;
			// Save score to high scores for logged in players
			var highScores = storage.highScores || [];
			highScores.push(score); // Add current score
			// Sort high scores in descending order
			highScores.sort(function (a, b) {
				return b - a;
			});
			// Keep only top 5 high scores
			if (highScores.length > 5) {
				highScores = highScores.slice(0, 5);
			}
			storage.highScores = highScores;
			LK.showYouWin(); // Player wins after completing level 5
			// Potentially add 'return;' here if no other logic should run after winning in this tick
		} else {
			levelTxt.setText('Level: ' + level);
			levelTxtOrange.setText('Level: ' + level);
			showLevelTextOnce(); // This function calls startRespawningObjects
			// Hide all backgrounds
			backgroundLevel1.visible = false;
			backgroundLevel2.visible = false;
			backgroundLevel3.visible = false;
			backgroundLevel4.visible = false;
			if (backgroundLevel5) {
				backgroundLevel5.visible = false;
			}
			// Show the current level background and spawn an initial object
			if (level === 2) {
				backgroundLevel2.visible = true;
				// Play level 2 music
				LK.playMusic('level2gamemusic');
				var newLavarocks = new Lavarocks();
				spheres.push(newLavarocks);
				game.addChild(newLavarocks);
				newLavarocks.x = Math.random() * (2048 - newLavarocks.width) + newLavarocks.width / 2;
				newLavarocks.y = -100; // Initial position off-screen top
			} else if (level === 3) {
				backgroundLevel3.visible = true;
				// Play level 3 music
				LK.playMusic('level3gamemusic');
				var newIcerocks = new Icerocks();
				spheres.push(newIcerocks);
				game.addChild(newIcerocks);
				newIcerocks.x = Math.random() * (2048 - newIcerocks.width) + newIcerocks.width / 2;
				newIcerocks.y = -100;
			} else if (level === 4) {
				backgroundLevel4.visible = true;
				// Play level 4 music
				LK.playMusic('level4gamemusic');
				var newStone = new Stone();
				spheres.push(newStone);
				game.addChild(newStone);
				newStone.x = Math.random() * (2048 - newStone.width) + newStone.width / 2;
				newStone.y = -100;
			} else if (level === 5) {
				if (backgroundLevel5) {
					backgroundLevel5.visible = true;
				}
				// Play level 5 music
				LK.playMusic('level5gamemusic');
				var randomType = Math.floor(Math.random() * 3);
				var newAirBlock;
				if (randomType === 0) {
					newAirBlock = new AirBlock();
				} else if (randomType === 1) {
					newAirBlock = new Airblockasset1();
					if (newAirBlock.startRotation) {
						newAirBlock.startRotation();
					}
				} else {
					newAirBlock = new Airblockasset2();
					if (newAirBlock.startFlipping) {
						newAirBlock.startFlipping();
					}
				}
				spheres.push(newAirBlock);
				game.addChild(newAirBlock);
				newAirBlock.x = Math.random() * (2048 - newAirBlock.width) + newAirBlock.width / 2;
				newAirBlock.y = -100;
				// Add continuous rotation animation to the right for original AirBlock
				if (newAirBlock instanceof AirBlock) {
					tween(newAirBlock, {
						rotation: Math.PI * 2
					}, {
						duration: 2000,
						easing: tween.linear,
						onFinish: function onFinish() {
							// Start the animation again for continuous rotation
							function rotateAirBlock() {
								if (newAirBlock && !newAirBlock.destroyed) {
									tween(newAirBlock, {
										rotation: newAirBlock.rotation + Math.PI * 2
									}, {
										duration: 2000,
										easing: tween.linear,
										onFinish: rotateAirBlock
									});
								}
							}
							rotateAirBlock();
						}
					});
				}
			}
		}
	}
	// Respawn Lavarocks, Lavarocks1, and Lavarocks2 randomly in level 2
	if (level === 2 && !LK.gameOver && LK.ticks % 70 == 0) {
		var newLavarock;
		for (var i = 0; i < spheres.length; i++) {
			if ((spheres[i] instanceof Lavarocks || spheres[i] instanceof Lavarocks1 || spheres[i] instanceof Lavarocks2) && spheres[i].y < -200) {
				newLavarock = spheres[i];
				break;
			}
		}
		if (!newLavarock) {
			var randomType = Math.floor(Math.random() * 3);
			if (randomType === 0) {
				newLavarock = new Lavarocks();
			} else if (randomType === 1) {
				newLavarock = new Lavarocks1();
			} else {
				newLavarock = new Lavarocks2();
			}
			spheres.push(newLavarock);
			game.addChild(newLavarock);
		}
		var randomScale = 1.0 + Math.random() * 1.0; // Random scale between 1.0 and 2.0
		newLavarock.scaleX = randomScale;
		newLavarock.scaleY = randomScale;
		newLavarock.x = Math.random() * (2048 - newLavarock.width) + newLavarock.width / 2;
		newLavarock.y = 2732;
	}
	// Respawn Icerocks randomly in level 3
	if (level === 3 && !LK.gameOver && LK.ticks % 80 == 0) {
		var newIcerock;
		for (var i = 0; i < spheres.length; i++) {
			if ((spheres[i] instanceof Icerocks || spheres[i] instanceof Icerocks1 || spheres[i] instanceof Icerocks2) && spheres[i].y < -200) {
				newIcerock = spheres[i];
				break;
			}
		}
		if (!newIcerock) {
			var randomType = Math.floor(Math.random() * 3);
			if (randomType === 0) {
				newIcerock = new Icerocks();
			} else if (randomType === 1) {
				newIcerock = new Icerocks1();
			} else {
				newIcerock = new Icerocks2();
			}
			spheres.push(newIcerock);
			game.addChild(newIcerock);
		}
		var randomScaleX = 1.0 + Math.random() * 1.0; // Random scale between 1.0 and 2.0 for width
		var randomScaleY = 1.0 + Math.random() * 1.5; // Random scale between 1.0 and 2.5 for height
		newIcerock.scaleX = randomScaleX;
		newIcerock.scaleY = randomScaleY;
		newIcerock.x = Math.random() * (2048 - newIcerock.width) + newIcerock.width / 2;
		newIcerock.y = 2732;
	}
	// Respawn AirBlocks randomly in level 5 (continuous spawning)
	if (level === 5 && !LK.gameOver && LK.ticks % 100 == 0) {
		var newAirBlock;
		for (var i = 0; i < spheres.length; i++) {
			if ((spheres[i] instanceof AirBlock || spheres[i] instanceof Airblockasset1 || spheres[i] instanceof Airblockasset2) && spheres[i].y < -200) {
				// Check if AirBlock is off-screen
				newAirBlock = spheres[i];
				break;
			}
		}
		if (!newAirBlock) {
			var randomType = Math.floor(Math.random() * 3);
			if (randomType === 0) {
				newAirBlock = new AirBlock();
			} else if (randomType === 1) {
				newAirBlock = new Airblockasset1();
				if (newAirBlock.startRotation) {
					newAirBlock.startRotation();
				}
			} else {
				newAirBlock = new Airblockasset2();
				if (newAirBlock.startFlipping) {
					newAirBlock.startFlipping();
				}
			}
			spheres.push(newAirBlock);
			game.addChild(newAirBlock);
		}
		var randomScaleAir = 1.0 + Math.random() * 1.0; // Random scale between 1.0 and 2.0
		newAirBlock.scaleX = randomScaleAir;
		newAirBlock.scaleY = randomScaleAir;
		newAirBlock.x = Math.random() * (2048 - newAirBlock.width) + newAirBlock.width / 2;
		newAirBlock.y = 2732; // Spawn at the bottom
		// Add continuous rotation animation to the right for original AirBlock
		if (newAirBlock instanceof AirBlock) {
			tween(newAirBlock, {
				rotation: Math.PI * 2
			}, {
				duration: 2000,
				easing: tween.linear,
				onFinish: function onFinish() {
					// Start the animation again for continuous rotation
					function rotateAirBlock() {
						if (newAirBlock && !newAirBlock.destroyed) {
							tween(newAirBlock, {
								rotation: newAirBlock.rotation + Math.PI * 2
							}, {
								duration: 2000,
								easing: tween.linear,
								onFinish: rotateAirBlock
							});
						}
					}
					rotateAirBlock();
				}
			});
		}
	}
};
// Declare dragNode globally as it's used in event handlers set up in setupActiveGame
var dragNode = null;
// Function to set up and start the actual game after intro
function setupActiveGame() {
	// Ensure game backgrounds are set up for level 1
	backgroundLevel1.visible = true;
	backgroundLevel2.visible = false;
	backgroundLevel3.visible = false;
	backgroundLevel4.visible = false;
	if (backgroundLevel5) {
		// Check existence for safety
		backgroundLevel5.visible = false;
	}
	// Initialize dragon
	dragon = game.addChild(new Dragon());
	dragon.x = 2048 / 2;
	dragon.y = 200;
	// Initialize the animated "Start" text that appears after button press
	var animatedStartTxt = new Text2('Start', {
		size: 150,
		fill: 0xffa500,
		// Orange color
		font: "'Time new roman',Impact,'Arial Black',Tahoma" //{aF} // Copied from original startTxt
	}); //{aG} // Copied from original startTxt
	animatedStartTxt.anchor.set(0.5, 0.5);
	LK.gui.center.addChild(animatedStartTxt);
	// Local function to show the animated "Start" text, then proceed to level announcements
	function showAnimatedStartText() {
		animatedStartTxt.visible = true;
		LK.setTimeout(function () {
			animatedStartTxt.visible = false;
			// The global showLevelTextTwice function handles level announcements and then calls startRespawningObjects
			showLevelTextTwice();
		}, 2000);
	}
	// Initialize level display text (purple)
	levelTxt = new Text2('Level: 1', {
		// Assign to global levelTxt
		size: 100,
		fill: 0x800080,
		//{aK} // Purple color
		font: "'Time new roman',Impact,'Arial Black',Tahoma"
	});
	levelTxt.anchor.set(1, 1);
	LK.gui.bottomRight.addChild(levelTxt);
	levelTxt.x = -50;
	levelTxt.y = -50;
	// Call the function to show the animated "Start" text sequence
	showAnimatedStartText();
	// Play level 1 music when game starts
	LK.playMusic('level1gamemusic');
	// Initialize second level display text (orange/yellow, for level announcements)
	levelTxtOrange = new Text2('Level: ' + level, {
		// Assign to global levelTxtOrange
		size: 100,
		fill: 0xffff00,
		// Yellow color
		font: "'Time new roman',Impact,'Arial Black',Tahoma"
	});
	levelTxtOrange.anchor.set(0.5, 0.5);
	LK.gui.center.addChild(levelTxtOrange);
	levelTxtOrange.visible = false; // Initially hidden, showLevelTextTwice will manage it
	// Initialize score display
	scoreTxt = new Text2('Score: 0', {
		// Assign to global scoreTxt
		size: 100,
		fill: 0x800080,
		//{bs} // Purple color
		font: "'Time new roman',Impact,'Arial Black',Tahoma"
	});
	scoreTxt.anchor.set(0, 1); // Using the bottom-left positioning from original code
	LK.gui.bottomLeft.addChild(scoreTxt);
	scoreTxt.x = 50;
	scoreTxt.y = -50;
	// Initialize health bar
	healthBar = game.addChild(new HealthBar()); // Assign to global healthBar
	healthBar.x = 120; // Position in top left corner (avoiding platform menu)
	healthBar.y = 50; // Position in top left corner
	// Initialize health text display
	healthTxt = new Text2('500', {
		size: 60,
		fill: 0xffffff,
		// White color
		font: "'Time new roman',Impact,'Arial Black',Tahoma"
	});
	healthTxt.anchor.set(0.5, 0.5); // Center anchor for centering within health bar
	LK.gui.topLeft.addChild(healthTxt);
	healthTxt.x = healthBar.x + healthBar.width * healthBar.scaleX / 2 - 920; // Center horizontally within health bar
	healthTxt.y = healthBar.y + healthBar.height * healthBar.scaleY / 2 - 100; // Center vertically within health bar
	// Setup touch input for dragging the dragon
	game.down = function (x, y, obj) {
		if (!gameStarted) {
			return;
		} // Should not be needed here as game.down is set after game starts
		dragNode = dragon;
	};
	game.up = function (x, y, obj) {
		if (!gameStarted) {
			return;
		}
		dragNode = null;
	};
	game.move = function (x, y, obj) {
		if (!gameStarted || !dragNode) {
			return;
		}
		var newX = Math.max(dragon.width / 2, Math.min(2048 - dragon.width / 2, x));
		var newY = Math.max(dragon.height / 2, Math.min(2732 - dragon.height / 2, y));
		dragon.x = newX;
		dragon.y = newY;
		if (LK.ticks % 24 == 0) {
			for (var i = 0; i < 1; i++) {
				var assetId;
				if (level === 2) {
					assetId = 'Shout2';
				} else if (level === 3) {
					assetId = 'Shout3';
				} else if (level === 4) {
					assetId = 'Shout4';
				} else if (level === 5) {
					assetId = 'Shout5';
				} else {
					assetId = 'Shout1';
				}
				var fireball = new Fireball(assetId);
				if (dragon.x < 2048 / 2) {
					fireball.x = dragon.x - 80;
				} else {
					fireball.x = dragon.x + 80;
				}
				fireball.y = dragon.y;
				tween(fireball, {
					rotation: Math.PI * 4
				}, {
					duration: 1500,
					easing: tween.linear
				});
				fireballs.push(fireball);
				game.addChild(fireball);
				// Play shout sound based on current level
				if (level === 1) {
					LK.getSound('shout1').play();
				} else if (level === 2) {
					LK.getSound('shout2').play();
				} else if (level === 3) {
					LK.getSound('shout3').play();
				} else if (level === 4) {
					LK.getSound('shout4').play();
				} else if (level === 5) {
					LK.getSound('shout5').play();
				}
			}
		}
	};
}
// === Intro Screen Setup (runs when Game Code is parsed) ===
introBackground = LK.getAsset('Introbackground', {
	anchorX: 0.5,
	anchorY: 0.5
});
introBackground.x = 2048 / 2;
introBackground.y = 2732 / 2;
// Scale intro background to cover the screen, using its own dimensions after LK.getAsset
introBackground.scale.set(2048 / introBackground.width, 2732 / introBackground.height);
game.addChild(introBackground);
// Play intro music during the intro screen
LK.playMusic('Intromusic1');
// Create score button
var scoreButton = LK.getAsset('Scorebutton', {
	anchorX: 0.5,
	anchorY: 0.5
});
scoreButton.interactive = true;
game.addChild(scoreButton);
// Calculate button spacing - keep middle of screen centered between the two buttons
var buttonSpacing = 600; // Distance between button centers (increased from 300 to 600)
startButton = LK.getAsset('Startbutton', {
	anchorX: 0.5,
	anchorY: 0.5
});
startButton.x = 2048 / 2 - buttonSpacing / 2; // Position start button to the left of center
startButton.y = 2732 - startButton.height / 2 - 100; // 100px from bottom edge to center of button
startButton.interactive = true; // Essential for the 'down' event
game.addChild(startButton);
// Create score background - added after buttons so it appears on top when visible
var scoreBackground = LK.getAsset('Scorebackground', {
	anchorX: 0.5,
	anchorY: 0.5
});
scoreBackground.x = 2048 / 2;
scoreBackground.y = 2732 / 2;
// Scale score background to cover the screen
scoreBackground.scale.set(2048 / scoreBackground.width, 2732 / scoreBackground.height);
scoreBackground.visible = false; // Initially hidden
scoreBackground.interactive = true; // Make it interactive for tap to close
game.addChild(scoreBackground);
// Create close button text for scoreBackground
var closeButtonText = new Text2('X', {
	size: 100,
	fill: 0xffffff,
	font: "'Arial Black',Impact,Tahoma"
});
closeButtonText.anchor.set(0.5, 0.5);
closeButtonText.x = scoreBackground.x + scoreBackground.width * scoreBackground.scaleX / 2 - 100;
closeButtonText.y = scoreBackground.y - scoreBackground.height * scoreBackground.scaleY / 2 + 100;
closeButtonText.visible = false; // Initially hidden
closeButtonText.interactive = true;
game.addChild(closeButtonText);
// Position score button to the right of center
scoreButton.x = 2048 / 2 + buttonSpacing / 2;
scoreButton.y = 2732 - scoreButton.height / 2 - 100; // Same Y position as start button
// Add high score text
var highScoreText = new Text2('High Score:', {
	size: 80,
	fill: 0xffffff,
	font: "'Time new roman',Impact,'Arial Black',Tahoma"
});
highScoreText.anchor.set(0.5, 0.5);
highScoreText.x = scoreBackground.x;
highScoreText.y = scoreBackground.y - scoreBackground.height * scoreBackground.scaleY / 2 + 650;
highScoreText.visible = false;
game.addChild(highScoreText);
// Add recent scores display
var recentScoresText = new Text2('', {
	size: 60,
	fill: 0xffffff,
	font: "'Time new roman',Impact,'Arial Black',Tahoma"
});
recentScoresText.anchor.set(0.5, 0);
recentScoresText.x = scoreBackground.x;
recentScoresText.y = highScoreText.y + 60;
recentScoresText.visible = false;
game.addChild(recentScoresText);
// Add score button event handler
scoreButton.down = function () {
	if (gameStarted) {
		return;
	}
	// Show score background and close button
	scoreBackground.visible = true;
	closeButtonText.visible = true;
	highScoreText.visible = true;
	recentScoresText.visible = true;
	// Save current score if game has been played (score > 0)
	if (score > 0) {
		var storedScores = storage.recentScores || [];
		storedScores.unshift(score); // Add current score at beginning
		// Keep only top 5 scores
		if (storedScores.length > 5) {
			storedScores = storedScores.slice(0, 5);
		}
		// Sort scores in descending order
		storedScores.sort(function (a, b) {
			return b - a;
		});
		storage.recentScores = storedScores;
	}
	// Get stored high scores for logged in players or initialize empty array
	var highScores = storage.highScores || [];
	// Get stored recent scores or initialize empty array
	var recentScores = storage.recentScores || [];
	// Always display high scores for logged in players
	var scoresDisplay = '';
	if (highScores.length > 0) {
		for (var i = 0; i < Math.min(highScores.length, 5); i++) {
			scoresDisplay += i + 1 + '. ' + highScores[i] + '\n';
		}
	} else {
		scoresDisplay = 'No high scores yet\n';
	}
	// Add recent scores below high scores
	if (recentScores.length > 0) {
		scoresDisplay += '\nRecent Scores:\n';
		for (var j = 0; j < Math.min(recentScores.length, 5); j++) {
			scoresDisplay += j + 1 + '. ' + recentScores[j] + '\n';
		}
	}
	recentScoresText.setText(scoresDisplay);
	// Leaderboard functionality is handled automatically by LK engine
	// No manual implementation needed
};
// Add tap to close functionality for scoreBackground
scoreBackground.down = function () {
	scoreBackground.visible = false;
	closeButtonText.visible = false;
	highScoreText.visible = false;
	recentScoresText.visible = false;
};
// Add close button functionality
closeButtonText.down = function () {
	scoreBackground.visible = false;
	closeButtonText.visible = false;
	highScoreText.visible = false;
	recentScoresText.visible = false;
};
startButton.down = function () {
	if (gameStarted) {
		return;
	} // Prevent multiple starts if clicked again rapidly
	gameStarted = true;
	introBackground.visible = false;
	startButton.visible = false;
	scoreButton.visible = false;
	scoreBackground.visible = false;
	closeButtonText.visible = false;
	highScoreText.visible = false;
	recentScoresText.visible = false;
	// For performance, you might want to destroy them if they are truly one-time use:
	// introBackground.destroy();
	// startButton.destroy();
	setupActiveGame(); // This will initialize and start the actual game
};
// The original global showStartText, showLevelTextOnce, showLevelTextTwice, startRespawningObjects functions
// are assumed to be defined elsewhere in the "Game Code" section or are part of what was replaced.
// If showStartText was the one replaced, its logic is now within setupActiveGame as showAnimatedStartText.
// The other functions (showLevelTextOnce, showLevelTextTwice, startRespawningObjects) should still be globally available. /**** 
* Plugins
****/ 
var tween = LK.import("@upit/tween.v1");
var storage = LK.import("@upit/storage.v1");
/**** 
* Classes
****/ 
var AirBlock = Container.expand(function () {
	var self = Container.call(this);
	var airBlockGraphics = self.attachAsset('AirBlockAsset', {
		anchorX: 0.5,
		anchorY: 0.5,
		scaleX: 1.0,
		scaleY: 1.0,
		smooth: true,
		filterQuality: 1
	});
	self.speed = level === 5 ? 18 : 12; // Increased speed for AirBlocks in Level 5
	self.update = function () {
		self.y -= self.speed;
	};
	return self;
});
var Airblockasset1 = Container.expand(function () {
	var self = Container.call(this);
	var airblock1Graphics = self.attachAsset('Airblockasset1', {
		anchorX: 0.5,
		anchorY: 0.5,
		scaleX: 1.0,
		scaleY: 1.0,
		smooth: true,
		filterQuality: 1
	});
	self.speed = level === 5 ? 18 : 12;
	// Start continuous rotation to the right
	self.startRotation = function () {
		function rotateRight() {
			if (self && !self.destroyed) {
				tween(self, {
					rotation: self.rotation + Math.PI * 2
				}, {
					duration: 2000,
					easing: tween.linear,
					onFinish: rotateRight
				});
			}
		}
		rotateRight();
	};
	self.update = function () {
		self.y -= self.speed;
	};
	return self;
});
var Airblockasset2 = Container.expand(function () {
	var self = Container.call(this);
	var airblock2Graphics = self.attachAsset('Airblockasset2', {
		anchorX: 0.5,
		anchorY: 0.5,
		scaleX: 1.0,
		scaleY: 1.0,
		smooth: true,
		filterQuality: 1
	});
	self.speed = level === 5 ? 18 : 12;
	// Start continuous flipping from right to left
	self.startFlipping = function () {
		function flipRightLeft() {
			if (self && !self.destroyed) {
				tween(airblock2Graphics, {
					scaleX: -1.0
				}, {
					duration: 1000,
					easing: tween.linear,
					onFinish: function onFinish() {
						if (self && !self.destroyed) {
							tween(airblock2Graphics, {
								scaleX: 1.0
							}, {
								duration: 1000,
								easing: tween.linear,
								onFinish: flipRightLeft
							});
						}
					}
				});
			}
		}
		flipRightLeft();
	};
	self.update = function () {
		self.y -= self.speed;
	};
	return self;
});
//<Assets used in the game will automatically appear here>
//<Write imports for supported plugins here>
// Dragon class to represent the player character
var Dragon = Container.expand(function () {
	var self = Container.call(this);
	// Function to get the appropriate dragon asset based on level
	self.getDragonAsset = function () {
		if (level === 2) {
			return 'Lavadragon';
		}
		if (level === 3) {
			return 'Snowdragon';
		}
		if (level === 4) {
			return 'Stonedragon';
		}
		if (level === 5) {
			return 'Airdragon';
		}
		return 'dragon'; // Default for level 1
	};
	var dragonGraphics = self.attachAsset(self.getDragonAsset(), {
		anchorX: 0.5,
		anchorY: 0.5,
		scaleX: 2.0,
		scaleY: 2.0,
		smooth: true,
		filterQuality: 2
	});
	self.speed = 20; // Further increase the speed of the dragon
	self.currentLevel = level; // Track current level for asset changes
	// Function to update dragon asset when level changes
	self.updateDragonAsset = function () {
		if (self.currentLevel !== level) {
			self.currentLevel = level;
			// Remove old graphics
			dragonGraphics.destroy();
			// Create new graphics with appropriate asset
			dragonGraphics = self.attachAsset(self.getDragonAsset(), {
				anchorX: 0.5,
				anchorY: 0.5,
				scaleX: self.x < 2048 / 2 ? -2.0 : 2.0,
				scaleY: 2.0,
				smooth: true,
				filterQuality: 2
			});
		}
	};
	self.update = function () {
		// Update dragon asset if level changed
		self.updateDragonAsset();
		// Update logic for the dragon to flip based on movement direction
		if (self.x < 2048 / 2) {
			dragonGraphics.scaleX = -2.0; // Flip horizontally when on the left side of the screen
		} else {
			dragonGraphics.scaleX = 2.0; // Normal orientation when on the right side of the screen
		}
		// Removed unnecessary variable to optimize performance
	};
	return self;
});
// Fireball class to represent the fireballs that the dragon shoots
var Fireball = Container.expand(function (assetId) {
	var self = Container.call(this);
	var fireballGraphics = self.attachAsset(assetId, {
		anchorX: 0.5,
		anchorY: 0.5,
		scaleX: 0.6,
		scaleY: 0.9,
		smooth: true,
		filterQuality: 1
	});
	self.speed = 15; // Increase the speed of the fireballs
	self.update = function () {
		self.y += self.speed;
	};
});
// HealthBar class to represent the player's health
var HealthBar = Container.expand(function () {
	var self = Container.call(this);
	var healthBarGraphics = self.attachAsset('healthBar', {
		anchorX: 0.2,
		anchorY: 0.0,
		scaleX: 3800 / 1000,
		// Scale to fit the game width
		scaleY: 0.1
	});
	self.maxHealth = 500;
	self.currentHealth = self.maxHealth;
	self.update = function () {
		healthBarGraphics.scaleX = self.currentHealth / self.maxHealth;
		healthBarGraphics.scaleY = 0.05; // Resize the health bar to fit the top of the screen
	};
});
var Icerocks = Container.expand(function () {
	var self = Container.call(this);
	var icerocksGraphics = self.attachAsset('Icerocks', {
		anchorX: 0.5,
		anchorY: 0.5,
		scaleX: level === 3 ? 1.5 : 1.0,
		scaleY: level === 3 ? 1.5 : 1.0,
		smooth: true,
		filterQuality: 1
	});
	self.speed = level === 3 ? 15 : 5; // Further increase speed for level 3
	self.update = function () {
		self.y -= self.speed;
	};
});
var Icerocks1 = Container.expand(function () {
	var self = Container.call(this);
	var icerocks1Graphics = self.attachAsset('Icerocks1', {
		anchorX: 0.5,
		anchorY: 0.5,
		scaleX: level === 3 ? 1.5 : 1.0,
		scaleY: level === 3 ? 1.5 : 1.0,
		smooth: true,
		filterQuality: 1
	});
	self.speed = level === 3 ? 15 : 5; // Further increase speed for level 3
	self.update = function () {
		// Move the icerocks upwards
		self.y -= self.speed;
	};
});
var Icerocks2 = Container.expand(function () {
	var self = Container.call(this);
	var icerocks2Graphics = self.attachAsset('Icerocks2', {
		anchorX: 0.5,
		anchorY: 0.5,
		scaleX: level === 3 ? 1.5 : 1.0,
		scaleY: level === 3 ? 1.5 : 1.0,
		smooth: true,
		filterQuality: 1
	});
	self.speed = level === 3 ? 15 : 5; // Further increase speed for level 3
	self.update = function () {
		// Move the icerocks upwards
		self.y -= self.speed;
	};
});
var Land01 = Container.expand(function () {
	var self = Container.call(this);
	var land01Graphics = self.attachAsset('Land01', {
		anchorX: 0.5,
		anchorY: 0.5,
		scaleX: 1.0,
		scaleY: 1.0,
		smooth: true,
		filterQuality: 1
	});
	self.speed = 15; // Further increase the speed of the Land01
	self.update = function () {
		self.y -= self.speed;
	};
	return self;
});
var Lavarocks = Container.expand(function () {
	var self = Container.call(this);
	var lavarocksGraphics = self.attachAsset('Lavarocks', {
		anchorX: 0.5,
		anchorY: 0.5,
		scaleX: level === 2 ? 1.5 : 1.0,
		scaleY: level === 2 ? 1.5 : 1.0,
		smooth: true,
		filterQuality: 1
	});
	self.speed = level === 2 ? 20 : 5; // Maximum increase speed for level 2
	self.update = function () {
		self.y -= self.speed;
	};
});
var Lavarocks1 = Container.expand(function () {
	var self = Container.call(this);
	var lavarocks1Graphics = self.attachAsset('Lavarocks1', {
		anchorX: 0.5,
		anchorY: 0.5,
		scaleX: level === 2 ? 1.5 : 1.0,
		scaleY: level === 2 ? 1.5 : 1.0,
		smooth: true,
		filterQuality: 1
	});
	self.speed = level === 2 ? 20 : 5; // Maximum increase speed for level 2
	self.update = function () {
		// Move the lavarocks1 upwards
		self.y -= self.speed;
	};
});
var Lavarocks2 = Container.expand(function () {
	var self = Container.call(this);
	var lavarocks2Graphics = self.attachAsset('Lavarocks2', {
		anchorX: 0.5,
		anchorY: 0.5,
		scaleX: level === 2 ? 1.5 : 1.0,
		scaleY: level === 2 ? 1.5 : 1.0,
		smooth: true,
		filterQuality: 1
	});
	self.speed = level === 2 ? 20 : 5; // Maximum increase speed for level 2
	self.update = function () {
		// Move the lavarocks2 upwards
		self.y -= self.speed;
	};
});
var Stone = Container.expand(function () {
	var self = Container.call(this);
	var stoneGraphics = self.attachAsset('Stone', {
		anchorX: 0.5,
		anchorY: 0.5,
		scaleX: 0.3,
		scaleY: 0.3,
		smooth: true,
		filterQuality: 1
	});
	self.speed = level === 4 ? 15 : 10; // Further increase speed for Stone objects in level 4
	self.update = function () {
		self.y -= self.speed;
	};
});
var StoneCircle = Container.expand(function () {
	var self = Container.call(this);
	var stoneCircleGraphics = self.attachAsset('StoneCircle', {
		anchorX: 0.5,
		anchorY: 0.5,
		scaleX: 0.5,
		scaleY: 0.5,
		smooth: true,
		filterQuality: 1
	});
	self.speed = level === 4 ? 15 : 10; // Further increase speed for StoneCircle objects in level 4
	self.update = function () {
		// Move the stones upwards
		self.y -= self.speed;
	};
});
var StoneSquare = Container.expand(function () {
	var self = Container.call(this);
	var stoneSquareGraphics = self.attachAsset('StoneSquare', {
		anchorX: 0.5,
		anchorY: 0.5,
		scaleX: 0.5,
		scaleY: 0.5,
		smooth: true,
		filterQuality: 1
	});
	self.speed = level === 4 ? 15 : 10; // Further increase speed for StoneSquare objects in level 4
	self.update = function () {
		// Move the stones upwards
		self.y -= self.speed;
	};
});
/**** 
* Initialize Game
****/ 
var game = new LK.Game({
	backgroundColor: 0x000000,
	//Init game with black background
	height: 3000 // Increase the game screen height
});
/**** 
* Game Code
****/ 
// or via static code analysis based on their usage in the code.
// Function to show the level text once
function showLevelTextOnce() {
	// Make sure levelTxtOrange is defined and visible
	if (levelTxtOrange) {
		levelTxtOrange.setText('Level: ' + level); // Update text content
		levelTxtOrange.visible = true;
		LK.setTimeout(function () {
			if (levelTxtOrange) {
				levelTxtOrange.visible = false;
			}
			// Start respawning objects after the text has hidden
			// This ensures objects for the new level start appearing after the level announcement
			startRespawningObjects();
		}, 1500); // Show text for 1.5 seconds
	} else {
		// Fallback or error logging if levelTxtOrange is not ready
		console.log("Error: levelTxtOrange not initialized before showLevelTextOnce call.");
		startRespawningObjects(); // Still try to start respawning
	}
}
function startRespawningObjects() {
	// Logic to start respawning objects based on the current level
	if (level === 1) {
		// Respawn Explosions randomly in level 1
		if (!LK.gameOver && LK.ticks % 60 == 0 && levelTxtOrange.visible === false) {
			var newExplosion;
			for (var i = 0; i < spheres.length; i++) {
				if (spheres[i] instanceof Explosion && spheres[i].y < -200) {
					newExplosion = spheres[i];
					break;
				}
			}
			if (!newExplosion) {
				newExplosion = new Explosion();
				spheres.push(newExplosion);
				game.addChild(newExplosion);
			}
			newExplosion.x = Math.random() * (2048 - newExplosion.width) + newExplosion.width / 2;
			newExplosion.y = 2732;
		}
	} else if (level === 2) {
		// Respawn Lavarocks, Lavarocks1, and Lavarocks2 randomly in level 2
		if (!LK.gameOver && LK.ticks % 70 == 0) {
			var newLavarock;
			for (var i = 0; i < spheres.length; i++) {
				if ((spheres[i] instanceof Lavarocks || spheres[i] instanceof Lavarocks1 || spheres[i] instanceof Lavarocks2) && spheres[i].y < -200) {
					newLavarock = spheres[i];
					break;
				}
			}
			if (!newLavarock) {
				var randomType = Math.floor(Math.random() * 5);
				if (randomType === 0) {
					newLavarock = new Lavarocks();
				} else if (randomType === 1) {
					newLavarock = new Lavarocks1();
				} else {
					newLavarock = new Lavarocks2();
				}
				spheres.push(newLavarock);
				game.addChild(newLavarock);
			}
			newLavarock.x = Math.random() * (2048 - newLavarock.width) + newLavarock.width / 2;
			newLavarock.y = 2732;
			var randomScale = 1.0 + Math.random() * 1.0; // Random scale between 1.0 and 2.0
			newLavarock.scaleX = randomScale;
			newLavarock.scaleY = randomScale;
		}
	} else if (level === 3) {
		// Respawn Icerocks randomly in level 3
		if (!LK.gameOver && LK.ticks % 80 == 0) {
			var newIcerock;
			for (var i = 0; i < spheres.length; i++) {
				if ((spheres[i] instanceof Icerocks || spheres[i] instanceof Icerocks1 || spheres[i] instanceof Icerocks2) && spheres[i].y < -200) {
					newIcerock = spheres[i];
					break;
				}
			}
			if (!newIcerock) {
				var randomType = Math.floor(Math.random() * 3);
				if (randomType === 0) {
					newIcerock = new Icerocks();
				} else if (randomType === 1) {
					newIcerock = new Icerocks1();
				} else {
					newIcerock = new Icerocks2();
				}
				spheres.push(newIcerock);
				game.addChild(newIcerock);
			}
			newIcerock.x = Math.random() * (2048 - newIcerock.width) + newIcerock.width / 2;
			newIcerock.y = 2732;
			var randomScaleX = 1.0 + Math.random() * 1.0; // Random scale between 1.0 and 2.0 for width
			var randomScaleY = 1.0 + Math.random() * 1.5; // Random scale between 1.0 and 2.5 for height
			newIcerock.scaleX = randomScaleX;
			newIcerock.scaleY = randomScaleY;
		}
	} else if (level === 5) {
		// Respawn AirBlocks randomly in level 5
		if (!LK.gameOver && LK.ticks % 100 == 0) {
			// Retaining tick condition for consistency
			var newAirBlock;
			for (var i = 0; i < spheres.length; i++) {
				if ((spheres[i] instanceof AirBlock || spheres[i] instanceof Airblockasset1 || spheres[i] instanceof Airblockasset2) && spheres[i].y < -200) {
					newAirBlock = spheres[i];
					break;
				}
			}
			if (!newAirBlock) {
				var randomType = Math.floor(Math.random() * 3);
				if (randomType === 0) {
					newAirBlock = new AirBlock();
				} else if (randomType === 1) {
					newAirBlock = new Airblockasset1();
					if (newAirBlock.startRotation) {
						newAirBlock.startRotation();
					}
				} else {
					newAirBlock = new Airblockasset2();
					if (newAirBlock.startFlipping) {
						newAirBlock.startFlipping();
					}
				}
				spheres.push(newAirBlock);
				game.addChild(newAirBlock);
			}
			newAirBlock.x = Math.random() * (2048 - newAirBlock.width) + newAirBlock.width / 2;
			newAirBlock.y = 2732;
			var randomScaleAir = 1.0 + Math.random() * 1.0;
			newAirBlock.scaleX = randomScaleAir;
			newAirBlock.scaleY = randomScaleAir;
			// Add continuous rotation animation to the right for original AirBlock
			if (newAirBlock instanceof AirBlock) {
				tween(newAirBlock, {
					rotation: Math.PI * 2
				}, {
					duration: 2000,
					easing: tween.linear,
					onFinish: function onFinish() {
						// Start the animation again for continuous rotation
						function rotateAirBlock() {
							if (newAirBlock && !newAirBlock.destroyed) {
								tween(newAirBlock, {
									rotation: newAirBlock.rotation + Math.PI * 2
								}, {
									duration: 2000,
									easing: tween.linear,
									onFinish: rotateAirBlock
								});
							}
						}
						rotateAirBlock();
					}
				});
			}
		}
	}
}
// Function to show the level text twice
function showLevelTextTwice() {
	levelTxtOrange.fill = 0x0000ff; // Blue color
	levelTxtOrange.visible = true;
	LK.setTimeout(function () {
		levelTxtOrange.visible = false;
		LK.setTimeout(function () {
			levelTxtOrange.visible = true;
			LK.setTimeout(function () {
				levelTxtOrange.visible = false;
				// Start respawning objects after the text has shown and hidden for the last time
				startRespawningObjects();
			}, 500);
		}, 500);
	}, 500);
}
// Add background image for level 4
var backgroundLevel4 = LK.getAsset('Stone_lands', {
	anchorX: 0.0,
	anchorY: 0.0
});
backgroundLevel4.smooth = true;
backgroundLevel4.filterQuality = 0; // Further increase the filter quality for better clarity
backgroundLevel4.scale.set(2048 / 800, 2732 / 800);
backgroundLevel4.smooth = true; // Enable smoothing to remove pixelation
backgroundLevel4.filterQuality = 0; // Adjust filter quality for better clarity
backgroundLevel4.visible = false; // Initially hidden
game.addChild(backgroundLevel4);
// Add background image for level 5
var backgroundLevel5 = LK.getAsset('SkyBackground', {
	anchorX: 0.0,
	anchorY: 0.0
});
backgroundLevel5.smooth = true;
backgroundLevel5.filterQuality = 0;
backgroundLevel5.scale.set(2048 / 800, 2732 / 800);
backgroundLevel5.visible = false; // Initially hidden
game.addChild(backgroundLevel5);
// Initialize game variables
var dragon;
var spheres = [];
var fireballs = []; // Initialize fireballs array
var score = 0; // Initialize score to 0
var scoreTxt;
var level = 1; // Initialize level to 1
var introBackground,
	startButton,
	gameStarted = false;
var healthBar; // Declare healthBar globally, will be initialized in setupActiveGame
var healthTxt; // Declare healthTxt globally for health text display
var nextHealthRestoreScore = 1000; // Track the next score milestone for health restoration
// Add background image to the game for level 1
var backgroundLevel1 = LK.getAsset('Green_lands', {
	anchorX: 0.0,
	anchorY: 0.0
});
backgroundLevel1.smooth = true; // Enable smoothing to remove pixelation
backgroundLevel1.filterQuality = 0; // Adjust filter quality for better clarity
backgroundLevel1.scale.set(2048 / 800, 2732 / 800); // Scale the background to fit the screen 
backgroundLevel1.smooth = true; // Enable smoothing to remove pixelation
backgroundLevel1.filterQuality = 0; // Further increase the filter quality for better clarity
backgroundLevel1.visible = true; // Initially visible
game.addChild(backgroundLevel1);
// Add background image for level 2
var backgroundLevel2 = LK.getAsset('Lava_lands', {
	anchorX: 0.0,
	anchorY: 0.0
});
backgroundLevel2.smooth = true;
backgroundLevel2.filterQuality = 0; // Further increase the filter quality for better clarity
backgroundLevel2.scale.set(2048 / 800, 2732 / 800);
backgroundLevel2.smooth = true; // Enable smoothing to remove pixelation
backgroundLevel2.filterQuality = 2; // Increase filter quality for better clarity
backgroundLevel2.visible = false; // Initially hidden
game.addChild(backgroundLevel2);
// Add background image for level 3
var backgroundLevel3 = LK.getAsset('Ice_lands', {
	anchorX: 0.0,
	anchorY: 0.0
});
backgroundLevel3.smooth = true;
backgroundLevel3.filterQuality = 2; // Increase filter quality for better clarity
backgroundLevel3.scale.set(2048 / 800, 2732 / 800); // Scale the background to fit the screen
backgroundLevel3.smooth = true; // Enable smoothing to remove pixelation
backgroundLevel3.filterQuality = 2; // Further increase the filter quality for better clarity
backgroundLevel3.visible = false; // Initially hidden
game.addChild(backgroundLevel3);
// Refresh the background to be clearer & fit to screen every 60 ticks
game.update = function () {
	backgroundLevel1.x = 2048 / 2; // Center the background horizontally
	backgroundLevel1.y = 2732 / 2; // Center the background vertically
	if (backgroundLevel1.y >= 2732) {
		backgroundLevel1.y = -2732;
	}
};
// Function to handle game updates
game.update = function () {
	if (!gameStarted) {
		// Game has not started, do nothing in the main update loop.
		// If intro elements had animations, they could be updated here.
		return;
	}
	// Reuse off-screen stones or spawn new ones if necessary
	if (level === 4 && !LK.gameOver && LK.ticks % 90 == 0) {
		var newStone;
		for (var i = 0; i < spheres.length; i++) {
			if ((spheres[i] instanceof Stone || spheres[i] instanceof StoneCircle || spheres[i] instanceof StoneSquare) && spheres[i].y < -200) {
				newStone = spheres[i];
				break;
			}
		}
		if (!newStone) {
			var randomType = Math.floor(Math.random() * 3);
			if (randomType === 0) {
				newStone = new Stone();
			} else if (randomType === 1) {
				newStone = new StoneCircle();
			} else {
				newStone = new StoneSquare();
			}
			spheres.push(newStone);
			game.addChild(newStone);
		}
		var randomScale = 1.0 + Math.random() * 1.0; // Random scale between 1.0 and 2.0
		newStone.scaleX = randomScale;
		newStone.scaleY = randomScale;
		newStone.x = Math.random() * (2048 - newStone.width) + newStone.width / 2;
		newStone.y = 2732;
	}
	// Check for collisions between fireballs and stones
	for (var i = fireballs.length - 1; i >= 0; i--) {
		if (fireballs[i].y > 2732) {
			fireballs[i].destroy();
			fireballs.splice(i, 1);
			continue;
		}
		for (var j = spheres.length - 1; j >= 0; j--) {
			if (fireballs[i].intersects(spheres[j]) && (spheres[j] instanceof Stone || spheres[j] instanceof StoneCircle || spheres[j] instanceof StoneSquare)) {
				var explosion4 = LK.getAsset('Explosion4', {
					anchorX: 0.5,
					anchorY: 0.5,
					scaleX: spheres[j].scaleX,
					scaleY: spheres[j].scaleY
				});
				explosion4.x = spheres[j].x;
				explosion4.y = spheres[j].y;
				game.addChild(explosion4);
				tween(explosion4, {
					alpha: 0
				}, {
					duration: 1000,
					onFinish: function onFinish() {
						explosion4.destroy();
					}
				});
				// Add random points from 0-40 when the dragon shoots the stones
				var points = Math.floor(Math.random() * 41);
				score += points;
				// Remove the fireball and the object from the game
				fireballs[i].destroy();
				fireballs.splice(i, 1);
				spheres[j].destroy();
				spheres.splice(j, 1);
				break;
			}
		}
	}
	// Check for collisions between dragon and stones
	for (var j = spheres.length - 1; j >= 0; j--) {
		if (dragon.intersects(spheres[j]) && (spheres[j] instanceof Stone || spheres[j] instanceof StoneCircle || spheres[j] instanceof StoneSquare)) {
			var explosion4 = LK.getAsset('Explosion4', {
				anchorX: 0.5,
				anchorY: 0.5,
				scaleX: spheres[j].scaleX,
				scaleY: spheres[j].scaleY
			});
			explosion4.x = spheres[j].x;
			explosion4.y = spheres[j].y;
			game.addChild(explosion4);
			tween(explosion4, {
				alpha: 0
			}, {
				duration: 1000,
				onFinish: function onFinish() {
					explosion4.destroy();
				}
			});
			// Decrease the dragon's health
			healthBar.currentHealth -= 20; // Consistent damage taken by the dragon from all objects in level 4
			// Remove the stone from the game
			spheres[j].destroy();
			spheres.splice(j, 1);
			break;
		}
	}
	if (!LK.gameOver && dragNode && dragNode.global) {
		dragNode.x = game.toLocal(dragNode.global).x;
	}
	// Reuse off-screen land01 or spawn new ones if necessary
	if (level === 1 && !LK.gameOver && LK.ticks % 60 == 0) {
		// Further reduce the interval for spawning land01 to add more land01 objects
		// Reduce the interval for spawning land01
		var newLand01;
		for (var i = 0; i < spheres.length; i++) {
			if (spheres[i] instanceof Land01 && spheres[i].y < -200) {
				// Check if the land01 is off-screen
				newLand01 = spheres[i];
				break;
			}
		}
		if (!newLand01) {
			newLand01 = new Land01();
			spheres.push(newLand01);
			game.addChild(newLand01);
		}
		var randomScale = 1.0 + Math.random() * 1.0; // Random scale between 1.0 and 2.0
		newLand01.scaleX = randomScale;
		newLand01.scaleY = randomScale;
		newLand01.x = Math.random() * (2048 - newLand01.width) + newLand01.width / 2;
		newLand01.y = 2732;
	}
	// Check for collisions between fireballs and land01 or Lavarocks
	for (var i = fireballs.length - 1; i >= 0; i--) {
		if (fireballs[i].y > 2732) {
			fireballs[i].destroy();
			fireballs.splice(i, 1);
			continue;
		}
		for (var j = spheres.length - 1; j >= 0; j--) {
			if (fireballs[i].intersects(spheres[j])) {
				if (spheres[j] instanceof Land01) {
					var explosion = LK.getAsset('explosion', {
						anchorX: 0.5,
						anchorY: 0.5,
						scaleX: spheres[j].scaleX,
						// Match the scale of the Land01 object
						scaleY: spheres[j].scaleY // Match the scale of the Land01 object
					});
					explosion.x = spheres[j].x;
					explosion.y = spheres[j].y;
					game.addChild(explosion);
					tween(explosion, {
						alpha: 0
					}, {
						duration: 1000,
						onFinish: function onFinish() {
							explosion.destroy();
						}
					});
				} else if (spheres[j] instanceof Lavarocks || spheres[j] instanceof Lavarocks1 || spheres[j] instanceof Lavarocks2) {
					var explosion2 = LK.getAsset('Explosion2', {
						anchorX: 0.5,
						anchorY: 0.5,
						scaleX: spheres[j].scaleX,
						// Match the scale of the Lavarocks object
						scaleY: spheres[j].scaleY // Match the scale of the Lavarocks object
					});
					explosion2.x = spheres[j].x;
					explosion2.y = spheres[j].y;
					game.addChild(explosion2);
					tween(explosion2, {
						alpha: 0
					}, {
						duration: 1000,
						onFinish: function onFinish() {
							explosion2.destroy();
						}
					});
				} else if (spheres[j] instanceof Icerocks || spheres[j] instanceof Icerocks1 || spheres[j] instanceof Icerocks2) {
					var explosion3 = LK.getAsset('Explosion3', {
						anchorX: 0.5,
						anchorY: 0.5,
						scaleX: spheres[j].scaleX,
						// Match the scale of the Icerocks object
						scaleY: spheres[j].scaleY // Match the scale of the Icerocks object
					});
					explosion3.x = spheres[j].x;
					explosion3.y = spheres[j].y;
					game.addChild(explosion3);
					tween(explosion3, {
						alpha: 0
					}, {
						duration: 1000,
						onFinish: function onFinish() {
							explosion3.destroy();
						}
					});
				} else if (spheres[j] instanceof AirBlock || spheres[j] instanceof Airblockasset1 || spheres[j] instanceof Airblockasset2) {
					var explosion5 = LK.getAsset('Explosion5', {
						anchorX: 0.5,
						anchorY: 0.5,
						scaleX: spheres[j].scaleX,
						scaleY: spheres[j].scaleY
					});
					explosion5.x = spheres[j].x;
					explosion5.y = spheres[j].y;
					game.addChild(explosion5);
					tween(explosion5, {
						alpha: 0
					}, {
						duration: 1000,
						onFinish: function onFinish() {
							explosion5.destroy();
						}
					});
				}
				// Add random points from 0-40 when the dragon shoots the land01 or Lavarocks
				var points = Math.floor(Math.random() * 41);
				score += points;
				// Remove the fireball and the object from the game
				fireballs[i].destroy();
				fireballs.splice(i, 1);
				spheres[j].destroy();
				spheres.splice(j, 1);
				break;
			}
		}
	}
	// Check for collisions between dragon and rocks
	for (var j = spheres.length - 1; j >= 0; j--) {
		if (dragon.intersects(spheres[j])) {
			if (spheres[j] instanceof Land01) {
				var explosion = LK.getAsset('explosion', {
					anchorX: 0.5,
					anchorY: 0.5,
					scaleX: spheres[j].scaleX,
					// Match the scale of the Land01 object
					scaleY: spheres[j].scaleY // Match the scale of the Land01 object
				});
				explosion.x = spheres[j].x;
				explosion.y = spheres[j].y;
				game.addChild(explosion);
				tween(explosion, {
					alpha: 0
				}, {
					duration: 1000,
					onFinish: function onFinish() {
						explosion.destroy();
					}
				});
			} else if (spheres[j] instanceof Lavarocks || spheres[j] instanceof Lavarocks1 || spheres[j] instanceof Lavarocks2) {
				var explosion2 = LK.getAsset('Explosion2', {
					anchorX: 0.5,
					anchorY: 0.5,
					scaleX: spheres[j].scaleX,
					// Match the scale of the Lavarocks object
					scaleY: spheres[j].scaleY // Match the scale of the Lavarocks object
				});
				explosion2.x = spheres[j].x;
				explosion2.y = spheres[j].y;
				game.addChild(explosion2);
				tween(explosion2, {
					alpha: 0
				}, {
					duration: 1000,
					onFinish: function onFinish() {
						explosion2.destroy();
					}
				});
			} else if (spheres[j] instanceof Icerocks || spheres[j] instanceof Icerocks1 || spheres[j] instanceof Icerocks2) {
				var explosion3 = LK.getAsset('Explosion3', {
					anchorX: 0.5,
					anchorY: 0.5,
					scaleX: spheres[j].scaleX,
					// Match the scale of the Icerocks object
					scaleY: spheres[j].scaleY // Match the scale of the Icerocks object
				});
				explosion3.x = spheres[j].x;
				explosion3.y = spheres[j].y;
				game.addChild(explosion3);
				tween(explosion3, {
					alpha: 0
				}, {
					duration: 1000,
					onFinish: function onFinish() {
						explosion3.destroy();
					}
				});
			} else if (spheres[j] instanceof AirBlock || spheres[j] instanceof Airblockasset1 || spheres[j] instanceof Airblockasset2) {
				var explosion5 = LK.getAsset('Explosion5', {
					anchorX: 0.5,
					anchorY: 0.5,
					scaleX: spheres[j].scaleX,
					scaleY: spheres[j].scaleY
				});
				explosion5.x = spheres[j].x;
				explosion5.y = spheres[j].y;
				game.addChild(explosion5);
				tween(explosion5, {
					alpha: 0
				}, {
					duration: 1000,
					onFinish: function onFinish() {
						explosion5.destroy();
					}
				});
			}
			// Decrease the dragon's health
			healthBar.currentHealth -= 20; // Consistent damage taken by the dragon from all objects in level 1
			// Remove the rock from the game
			spheres[j].destroy();
			spheres.splice(j, 1);
			break;
		}
		// Decrease dragon's health if any object passes the top of the screen
		if (spheres[j].y < -200) {
			healthBar.currentHealth -= 10; // Decrease health by 10 for each object
			spheres[j].destroy();
			spheres.splice(j, 1);
		}
		// Reuse off-screen lavarocks or spawn new ones if necessary
	}
	// Update the score display when the dragon gets points
	scoreTxt.setText('Score: ' + score);
	// Update the health text display
	if (healthTxt) {
		healthTxt.setText(healthBar.currentHealth.toString());
	}
	// Check if health bar reaches 0 to trigger game over
	if (healthBar.currentHealth <= 0 && !LK.gameOver) {
		// Save final score to recent scores storage when losing
		var storedScores = storage.recentScores || [];
		storedScores.unshift(score); // Add final score at beginning
		// Keep only top 5 scores
		if (storedScores.length > 5) {
			storedScores = storedScores.slice(0, 5);
		}
		// Sort scores in descending order
		storedScores.sort(function (a, b) {
			return b - a;
		});
		storage.recentScores = storedScores;
		// Save final score to high scores for logged in players when losing
		var highScores = storage.highScores || [];
		highScores.push(score); // Add final score
		// Sort high scores in descending order
		highScores.sort(function (a, b) {
			return b - a;
		});
		// Keep only top 5 high scores
		if (highScores.length > 5) {
			highScores = highScores.slice(0, 5);
		}
		storage.highScores = highScores;
		LK.effects.flashScreen(0xff0000, 1000); // Flash screen red for 1 second
		LK.showGameOver(); // Show game over screen with final score saved
	}
	// Regenerate player's health to max each time score crosses a 1000-point milestone
	while (score >= nextHealthRestoreScore) {
		healthBar.currentHealth = healthBar.maxHealth;
		nextHealthRestoreScore += 1000;
	}
	// Transition to the next level
	var scoreThresholds = [532, 1064, 1596, 2128, 2660]; // Score to complete level 1, 2, 3, 4, 5 respectively
	if (level <= 5 && score >= scoreThresholds[level - 1]) {
		level++;
		if (level > 5) {
			// Save score to recent scores storage when winning
			var storedScores = storage.recentScores || [];
			storedScores.unshift(score); // Add winning score at beginning
			// Keep only top 5 scores
			if (storedScores.length > 5) {
				storedScores = storedScores.slice(0, 5);
			}
			// Sort scores in descending order
			storedScores.sort(function (a, b) {
				return b - a;
			});
			storage.recentScores = storedScores;
			// Save score to high scores for logged in players
			var highScores = storage.highScores || [];
			highScores.push(score); // Add current score
			// Sort high scores in descending order
			highScores.sort(function (a, b) {
				return b - a;
			});
			// Keep only top 5 high scores
			if (highScores.length > 5) {
				highScores = highScores.slice(0, 5);
			}
			storage.highScores = highScores;
			LK.showYouWin(); // Player wins after completing level 5
			// Potentially add 'return;' here if no other logic should run after winning in this tick
		} else {
			levelTxt.setText('Level: ' + level);
			levelTxtOrange.setText('Level: ' + level);
			showLevelTextOnce(); // This function calls startRespawningObjects
			// Hide all backgrounds
			backgroundLevel1.visible = false;
			backgroundLevel2.visible = false;
			backgroundLevel3.visible = false;
			backgroundLevel4.visible = false;
			if (backgroundLevel5) {
				backgroundLevel5.visible = false;
			}
			// Show the current level background and spawn an initial object
			if (level === 2) {
				backgroundLevel2.visible = true;
				// Play level 2 music
				LK.playMusic('level2gamemusic');
				var newLavarocks = new Lavarocks();
				spheres.push(newLavarocks);
				game.addChild(newLavarocks);
				newLavarocks.x = Math.random() * (2048 - newLavarocks.width) + newLavarocks.width / 2;
				newLavarocks.y = -100; // Initial position off-screen top
			} else if (level === 3) {
				backgroundLevel3.visible = true;
				// Play level 3 music
				LK.playMusic('level3gamemusic');
				var newIcerocks = new Icerocks();
				spheres.push(newIcerocks);
				game.addChild(newIcerocks);
				newIcerocks.x = Math.random() * (2048 - newIcerocks.width) + newIcerocks.width / 2;
				newIcerocks.y = -100;
			} else if (level === 4) {
				backgroundLevel4.visible = true;
				// Play level 4 music
				LK.playMusic('level4gamemusic');
				var newStone = new Stone();
				spheres.push(newStone);
				game.addChild(newStone);
				newStone.x = Math.random() * (2048 - newStone.width) + newStone.width / 2;
				newStone.y = -100;
			} else if (level === 5) {
				if (backgroundLevel5) {
					backgroundLevel5.visible = true;
				}
				// Play level 5 music
				LK.playMusic('level5gamemusic');
				var randomType = Math.floor(Math.random() * 3);
				var newAirBlock;
				if (randomType === 0) {
					newAirBlock = new AirBlock();
				} else if (randomType === 1) {
					newAirBlock = new Airblockasset1();
					if (newAirBlock.startRotation) {
						newAirBlock.startRotation();
					}
				} else {
					newAirBlock = new Airblockasset2();
					if (newAirBlock.startFlipping) {
						newAirBlock.startFlipping();
					}
				}
				spheres.push(newAirBlock);
				game.addChild(newAirBlock);
				newAirBlock.x = Math.random() * (2048 - newAirBlock.width) + newAirBlock.width / 2;
				newAirBlock.y = -100;
				// Add continuous rotation animation to the right for original AirBlock
				if (newAirBlock instanceof AirBlock) {
					tween(newAirBlock, {
						rotation: Math.PI * 2
					}, {
						duration: 2000,
						easing: tween.linear,
						onFinish: function onFinish() {
							// Start the animation again for continuous rotation
							function rotateAirBlock() {
								if (newAirBlock && !newAirBlock.destroyed) {
									tween(newAirBlock, {
										rotation: newAirBlock.rotation + Math.PI * 2
									}, {
										duration: 2000,
										easing: tween.linear,
										onFinish: rotateAirBlock
									});
								}
							}
							rotateAirBlock();
						}
					});
				}
			}
		}
	}
	// Respawn Lavarocks, Lavarocks1, and Lavarocks2 randomly in level 2
	if (level === 2 && !LK.gameOver && LK.ticks % 70 == 0) {
		var newLavarock;
		for (var i = 0; i < spheres.length; i++) {
			if ((spheres[i] instanceof Lavarocks || spheres[i] instanceof Lavarocks1 || spheres[i] instanceof Lavarocks2) && spheres[i].y < -200) {
				newLavarock = spheres[i];
				break;
			}
		}
		if (!newLavarock) {
			var randomType = Math.floor(Math.random() * 3);
			if (randomType === 0) {
				newLavarock = new Lavarocks();
			} else if (randomType === 1) {
				newLavarock = new Lavarocks1();
			} else {
				newLavarock = new Lavarocks2();
			}
			spheres.push(newLavarock);
			game.addChild(newLavarock);
		}
		var randomScale = 1.0 + Math.random() * 1.0; // Random scale between 1.0 and 2.0
		newLavarock.scaleX = randomScale;
		newLavarock.scaleY = randomScale;
		newLavarock.x = Math.random() * (2048 - newLavarock.width) + newLavarock.width / 2;
		newLavarock.y = 2732;
	}
	// Respawn Icerocks randomly in level 3
	if (level === 3 && !LK.gameOver && LK.ticks % 80 == 0) {
		var newIcerock;
		for (var i = 0; i < spheres.length; i++) {
			if ((spheres[i] instanceof Icerocks || spheres[i] instanceof Icerocks1 || spheres[i] instanceof Icerocks2) && spheres[i].y < -200) {
				newIcerock = spheres[i];
				break;
			}
		}
		if (!newIcerock) {
			var randomType = Math.floor(Math.random() * 3);
			if (randomType === 0) {
				newIcerock = new Icerocks();
			} else if (randomType === 1) {
				newIcerock = new Icerocks1();
			} else {
				newIcerock = new Icerocks2();
			}
			spheres.push(newIcerock);
			game.addChild(newIcerock);
		}
		var randomScaleX = 1.0 + Math.random() * 1.0; // Random scale between 1.0 and 2.0 for width
		var randomScaleY = 1.0 + Math.random() * 1.5; // Random scale between 1.0 and 2.5 for height
		newIcerock.scaleX = randomScaleX;
		newIcerock.scaleY = randomScaleY;
		newIcerock.x = Math.random() * (2048 - newIcerock.width) + newIcerock.width / 2;
		newIcerock.y = 2732;
	}
	// Respawn AirBlocks randomly in level 5 (continuous spawning)
	if (level === 5 && !LK.gameOver && LK.ticks % 100 == 0) {
		var newAirBlock;
		for (var i = 0; i < spheres.length; i++) {
			if ((spheres[i] instanceof AirBlock || spheres[i] instanceof Airblockasset1 || spheres[i] instanceof Airblockasset2) && spheres[i].y < -200) {
				// Check if AirBlock is off-screen
				newAirBlock = spheres[i];
				break;
			}
		}
		if (!newAirBlock) {
			var randomType = Math.floor(Math.random() * 3);
			if (randomType === 0) {
				newAirBlock = new AirBlock();
			} else if (randomType === 1) {
				newAirBlock = new Airblockasset1();
				if (newAirBlock.startRotation) {
					newAirBlock.startRotation();
				}
			} else {
				newAirBlock = new Airblockasset2();
				if (newAirBlock.startFlipping) {
					newAirBlock.startFlipping();
				}
			}
			spheres.push(newAirBlock);
			game.addChild(newAirBlock);
		}
		var randomScaleAir = 1.0 + Math.random() * 1.0; // Random scale between 1.0 and 2.0
		newAirBlock.scaleX = randomScaleAir;
		newAirBlock.scaleY = randomScaleAir;
		newAirBlock.x = Math.random() * (2048 - newAirBlock.width) + newAirBlock.width / 2;
		newAirBlock.y = 2732; // Spawn at the bottom
		// Add continuous rotation animation to the right for original AirBlock
		if (newAirBlock instanceof AirBlock) {
			tween(newAirBlock, {
				rotation: Math.PI * 2
			}, {
				duration: 2000,
				easing: tween.linear,
				onFinish: function onFinish() {
					// Start the animation again for continuous rotation
					function rotateAirBlock() {
						if (newAirBlock && !newAirBlock.destroyed) {
							tween(newAirBlock, {
								rotation: newAirBlock.rotation + Math.PI * 2
							}, {
								duration: 2000,
								easing: tween.linear,
								onFinish: rotateAirBlock
							});
						}
					}
					rotateAirBlock();
				}
			});
		}
	}
};
// Declare dragNode globally as it's used in event handlers set up in setupActiveGame
var dragNode = null;
// Function to set up and start the actual game after intro
function setupActiveGame() {
	// Ensure game backgrounds are set up for level 1
	backgroundLevel1.visible = true;
	backgroundLevel2.visible = false;
	backgroundLevel3.visible = false;
	backgroundLevel4.visible = false;
	if (backgroundLevel5) {
		// Check existence for safety
		backgroundLevel5.visible = false;
	}
	// Initialize dragon
	dragon = game.addChild(new Dragon());
	dragon.x = 2048 / 2;
	dragon.y = 200;
	// Initialize the animated "Start" text that appears after button press
	var animatedStartTxt = new Text2('Start', {
		size: 150,
		fill: 0xffa500,
		// Orange color
		font: "'Time new roman',Impact,'Arial Black',Tahoma" //{aF} // Copied from original startTxt
	}); //{aG} // Copied from original startTxt
	animatedStartTxt.anchor.set(0.5, 0.5);
	LK.gui.center.addChild(animatedStartTxt);
	// Local function to show the animated "Start" text, then proceed to level announcements
	function showAnimatedStartText() {
		animatedStartTxt.visible = true;
		LK.setTimeout(function () {
			animatedStartTxt.visible = false;
			// The global showLevelTextTwice function handles level announcements and then calls startRespawningObjects
			showLevelTextTwice();
		}, 2000);
	}
	// Initialize level display text (purple)
	levelTxt = new Text2('Level: 1', {
		// Assign to global levelTxt
		size: 100,
		fill: 0x800080,
		//{aK} // Purple color
		font: "'Time new roman',Impact,'Arial Black',Tahoma"
	});
	levelTxt.anchor.set(1, 1);
	LK.gui.bottomRight.addChild(levelTxt);
	levelTxt.x = -50;
	levelTxt.y = -50;
	// Call the function to show the animated "Start" text sequence
	showAnimatedStartText();
	// Play level 1 music when game starts
	LK.playMusic('level1gamemusic');
	// Initialize second level display text (orange/yellow, for level announcements)
	levelTxtOrange = new Text2('Level: ' + level, {
		// Assign to global levelTxtOrange
		size: 100,
		fill: 0xffff00,
		// Yellow color
		font: "'Time new roman',Impact,'Arial Black',Tahoma"
	});
	levelTxtOrange.anchor.set(0.5, 0.5);
	LK.gui.center.addChild(levelTxtOrange);
	levelTxtOrange.visible = false; // Initially hidden, showLevelTextTwice will manage it
	// Initialize score display
	scoreTxt = new Text2('Score: 0', {
		// Assign to global scoreTxt
		size: 100,
		fill: 0x800080,
		//{bs} // Purple color
		font: "'Time new roman',Impact,'Arial Black',Tahoma"
	});
	scoreTxt.anchor.set(0, 1); // Using the bottom-left positioning from original code
	LK.gui.bottomLeft.addChild(scoreTxt);
	scoreTxt.x = 50;
	scoreTxt.y = -50;
	// Initialize health bar
	healthBar = game.addChild(new HealthBar()); // Assign to global healthBar
	healthBar.x = 120; // Position in top left corner (avoiding platform menu)
	healthBar.y = 50; // Position in top left corner
	// Initialize health text display
	healthTxt = new Text2('500', {
		size: 60,
		fill: 0xffffff,
		// White color
		font: "'Time new roman',Impact,'Arial Black',Tahoma"
	});
	healthTxt.anchor.set(0.5, 0.5); // Center anchor for centering within health bar
	LK.gui.topLeft.addChild(healthTxt);
	healthTxt.x = healthBar.x + healthBar.width * healthBar.scaleX / 2 - 920; // Center horizontally within health bar
	healthTxt.y = healthBar.y + healthBar.height * healthBar.scaleY / 2 - 100; // Center vertically within health bar
	// Setup touch input for dragging the dragon
	game.down = function (x, y, obj) {
		if (!gameStarted) {
			return;
		} // Should not be needed here as game.down is set after game starts
		dragNode = dragon;
	};
	game.up = function (x, y, obj) {
		if (!gameStarted) {
			return;
		}
		dragNode = null;
	};
	game.move = function (x, y, obj) {
		if (!gameStarted || !dragNode) {
			return;
		}
		var newX = Math.max(dragon.width / 2, Math.min(2048 - dragon.width / 2, x));
		var newY = Math.max(dragon.height / 2, Math.min(2732 - dragon.height / 2, y));
		dragon.x = newX;
		dragon.y = newY;
		if (LK.ticks % 24 == 0) {
			for (var i = 0; i < 1; i++) {
				var assetId;
				if (level === 2) {
					assetId = 'Shout2';
				} else if (level === 3) {
					assetId = 'Shout3';
				} else if (level === 4) {
					assetId = 'Shout4';
				} else if (level === 5) {
					assetId = 'Shout5';
				} else {
					assetId = 'Shout1';
				}
				var fireball = new Fireball(assetId);
				if (dragon.x < 2048 / 2) {
					fireball.x = dragon.x - 80;
				} else {
					fireball.x = dragon.x + 80;
				}
				fireball.y = dragon.y;
				tween(fireball, {
					rotation: Math.PI * 4
				}, {
					duration: 1500,
					easing: tween.linear
				});
				fireballs.push(fireball);
				game.addChild(fireball);
				// Play shout sound based on current level
				if (level === 1) {
					LK.getSound('shout1').play();
				} else if (level === 2) {
					LK.getSound('shout2').play();
				} else if (level === 3) {
					LK.getSound('shout3').play();
				} else if (level === 4) {
					LK.getSound('shout4').play();
				} else if (level === 5) {
					LK.getSound('shout5').play();
				}
			}
		}
	};
}
// === Intro Screen Setup (runs when Game Code is parsed) ===
introBackground = LK.getAsset('Introbackground', {
	anchorX: 0.5,
	anchorY: 0.5
});
introBackground.x = 2048 / 2;
introBackground.y = 2732 / 2;
// Scale intro background to cover the screen, using its own dimensions after LK.getAsset
introBackground.scale.set(2048 / introBackground.width, 2732 / introBackground.height);
game.addChild(introBackground);
// Play intro music during the intro screen
LK.playMusic('Intromusic1');
// Create score button
var scoreButton = LK.getAsset('Scorebutton', {
	anchorX: 0.5,
	anchorY: 0.5
});
scoreButton.interactive = true;
game.addChild(scoreButton);
// Calculate button spacing - keep middle of screen centered between the two buttons
var buttonSpacing = 600; // Distance between button centers (increased from 300 to 600)
startButton = LK.getAsset('Startbutton', {
	anchorX: 0.5,
	anchorY: 0.5
});
startButton.x = 2048 / 2 - buttonSpacing / 2; // Position start button to the left of center
startButton.y = 2732 - startButton.height / 2 - 100; // 100px from bottom edge to center of button
startButton.interactive = true; // Essential for the 'down' event
game.addChild(startButton);
// Create score background - added after buttons so it appears on top when visible
var scoreBackground = LK.getAsset('Scorebackground', {
	anchorX: 0.5,
	anchorY: 0.5
});
scoreBackground.x = 2048 / 2;
scoreBackground.y = 2732 / 2;
// Scale score background to cover the screen
scoreBackground.scale.set(2048 / scoreBackground.width, 2732 / scoreBackground.height);
scoreBackground.visible = false; // Initially hidden
scoreBackground.interactive = true; // Make it interactive for tap to close
game.addChild(scoreBackground);
// Create close button text for scoreBackground
var closeButtonText = new Text2('X', {
	size: 100,
	fill: 0xffffff,
	font: "'Arial Black',Impact,Tahoma"
});
closeButtonText.anchor.set(0.5, 0.5);
closeButtonText.x = scoreBackground.x + scoreBackground.width * scoreBackground.scaleX / 2 - 100;
closeButtonText.y = scoreBackground.y - scoreBackground.height * scoreBackground.scaleY / 2 + 100;
closeButtonText.visible = false; // Initially hidden
closeButtonText.interactive = true;
game.addChild(closeButtonText);
// Position score button to the right of center
scoreButton.x = 2048 / 2 + buttonSpacing / 2;
scoreButton.y = 2732 - scoreButton.height / 2 - 100; // Same Y position as start button
// Add high score text
var highScoreText = new Text2('High Score:', {
	size: 80,
	fill: 0xffffff,
	font: "'Time new roman',Impact,'Arial Black',Tahoma"
});
highScoreText.anchor.set(0.5, 0.5);
highScoreText.x = scoreBackground.x;
highScoreText.y = scoreBackground.y - scoreBackground.height * scoreBackground.scaleY / 2 + 650;
highScoreText.visible = false;
game.addChild(highScoreText);
// Add recent scores display
var recentScoresText = new Text2('', {
	size: 60,
	fill: 0xffffff,
	font: "'Time new roman',Impact,'Arial Black',Tahoma"
});
recentScoresText.anchor.set(0.5, 0);
recentScoresText.x = scoreBackground.x;
recentScoresText.y = highScoreText.y + 60;
recentScoresText.visible = false;
game.addChild(recentScoresText);
// Add score button event handler
scoreButton.down = function () {
	if (gameStarted) {
		return;
	}
	// Show score background and close button
	scoreBackground.visible = true;
	closeButtonText.visible = true;
	highScoreText.visible = true;
	recentScoresText.visible = true;
	// Save current score if game has been played (score > 0)
	if (score > 0) {
		var storedScores = storage.recentScores || [];
		storedScores.unshift(score); // Add current score at beginning
		// Keep only top 5 scores
		if (storedScores.length > 5) {
			storedScores = storedScores.slice(0, 5);
		}
		// Sort scores in descending order
		storedScores.sort(function (a, b) {
			return b - a;
		});
		storage.recentScores = storedScores;
	}
	// Get stored high scores for logged in players or initialize empty array
	var highScores = storage.highScores || [];
	// Get stored recent scores or initialize empty array
	var recentScores = storage.recentScores || [];
	// Always display high scores for logged in players
	var scoresDisplay = '';
	if (highScores.length > 0) {
		for (var i = 0; i < Math.min(highScores.length, 5); i++) {
			scoresDisplay += i + 1 + '. ' + highScores[i] + '\n';
		}
	} else {
		scoresDisplay = 'No high scores yet\n';
	}
	// Add recent scores below high scores
	if (recentScores.length > 0) {
		scoresDisplay += '\nRecent Scores:\n';
		for (var j = 0; j < Math.min(recentScores.length, 5); j++) {
			scoresDisplay += j + 1 + '. ' + recentScores[j] + '\n';
		}
	}
	recentScoresText.setText(scoresDisplay);
	// Leaderboard functionality is handled automatically by LK engine
	// No manual implementation needed
};
// Add tap to close functionality for scoreBackground
scoreBackground.down = function () {
	scoreBackground.visible = false;
	closeButtonText.visible = false;
	highScoreText.visible = false;
	recentScoresText.visible = false;
};
// Add close button functionality
closeButtonText.down = function () {
	scoreBackground.visible = false;
	closeButtonText.visible = false;
	highScoreText.visible = false;
	recentScoresText.visible = false;
};
startButton.down = function () {
	if (gameStarted) {
		return;
	} // Prevent multiple starts if clicked again rapidly
	gameStarted = true;
	introBackground.visible = false;
	startButton.visible = false;
	scoreButton.visible = false;
	scoreBackground.visible = false;
	closeButtonText.visible = false;
	highScoreText.visible = false;
	recentScoresText.visible = false;
	// For performance, you might want to destroy them if they are truly one-time use:
	// introBackground.destroy();
	// startButton.destroy();
	setupActiveGame(); // This will initialize and start the actual game
};
// The original global showStartText, showLevelTextOnce, showLevelTextTwice, startRespawningObjects functions
// are assumed to be defined elsewhere in the "Game Code" section or are part of what was replaced.
// If showStartText was the one replaced, its logic is now within setupActiveGame as showAnimatedStartText.
// The other functions (showLevelTextOnce, showLevelTextTwice, startRespawningObjects) should still be globally available.
:quality(85)/https://cdn.frvr.ai/67647193dc985fce75621c59.png%3F3) 
 :quality(85)/https://cdn.frvr.ai/676471a2dc985fce75621c5d.png%3F3) 
 :quality(85)/https://cdn.frvr.ai/676471b1dc985fce75621c61.png%3F3) 
 :quality(85)/https://cdn.frvr.ai/676471ecdc985fce75621c69.png%3F3) 
 :quality(85)/https://cdn.frvr.ai/6765e6d78ca6010c5bf77670.png%3F3) 
 :quality(85)/https://cdn.frvr.ai/6765f56d8ca6010c5bf7768a.png%3F3) 
 :quality(85)/https://cdn.frvr.ai/6765f6768ca6010c5bf77690.png%3F3) 
 :quality(85)/https://cdn.frvr.ai/6766384b4ce3d4700e55ceea.png%3F3) 
 floating land world imagination green colors not pixels no text in the image. Single Game Texture. In-Game asset. 2d. Blank background. High contrast. No shadows.
:quality(85)/https://cdn.frvr.ai/67675ba3268ce870cfc894b2.png%3F3) 
 :quality(85)/https://cdn.frvr.ai/67679059f88468c7b50be404.png%3F3) 
 :quality(85)/https://cdn.frvr.ai/6767908bf88468c7b50be408.png%3F3) 
 :quality(85)/https://cdn.frvr.ai/676790fcf88468c7b50be40c.png%3F3) 
 :quality(85)/https://cdn.frvr.ai/6767910ff88468c7b50be410.png%3F3) 
 :quality(85)/https://cdn.frvr.ai/676792d9f88468c7b50be426.png%3F3) 
 :quality(85)/https://cdn.frvr.ai/67679413f88468c7b50be43a.png%3F3) 
 :quality(85)/https://cdn.frvr.ai/6767945cf88468c7b50be43e.png%3F3) 
 :quality(85)/https://cdn.frvr.ai/67679467f88468c7b50be442.png%3F3) 
 :quality(85)/https://cdn.frvr.ai/6767962df88468c7b50be44e.png%3F3) 
 :quality(85)/https://cdn.frvr.ai/67679734f88468c7b50be45a.png%3F3) 
 :quality(85)/https://cdn.frvr.ai/676797f5f88468c7b50be45e.png%3F3) 
 :quality(85)/https://cdn.frvr.ai/67679862f88468c7b50be467.png%3F3) 
 :quality(85)/https://cdn.frvr.ai/685a93e4206de959973244f6.png%3F3) 
 Pack of different standing white dragon of stone on four legs, looking down. HD different mixed colors. Blur. not a sculpt model! the dragon is a real dragon have all things of dragon with opened mouth like he ready to shoot, have eyes opened . Single Game Texture. In-Game asset. 2D. Blank background. High contrast. No shadows.
:quality(85)/https://cdn.frvr.ai/685a9ab9206de95997324520.png%3F3) 
 :quality(85)/https://cdn.frvr.ai/685ab2c4206de95997324551.png%3F3) 
 Different standing dragon on four legs, looking down. have mixed colors. Blur. the dragon is opened mouth like he is ready to shout. Single Game Texture. In-Game asset. 3D. Blank background. High contrast. No shadows.
:quality(85)/https://cdn.frvr.ai/685ab3ea206de9599732455f.png%3F3) 
 Different standing dragon of forest on four legs, he's head is down and opened mouth to shout. HD colors. Single Game Texture. In-Game asset. 3D. Blank background. High contrast. No shadows.
:quality(85)/https://cdn.frvr.ai/685abb50206de95997324577.png%3F3) 
 Airball of dragon shout. sphere. HD colors.. In-Game asset. 2d. High contrast. No shadows
:quality(85)/https://cdn.frvr.ai/685abd10206de9599732458e.png%3F3) 
 Airball explosion. sphere. mixed grey with white & blue colors. HD colors In-Game asset. 2d. High contrast. No shadows
:quality(85)/https://cdn.frvr.ai/685abdfc206de959973245b9.png%3F3) 
 Air airball shout of a dragon. sphere. mixed grey with white & blue colors. HD colors In-Game asset. 2d. High contrast. No shadows
:quality(85)/https://cdn.frvr.ai/685aca9f206de95997324621.png%3F3) 
 Different standing dragons on four legs, looking down. HD colors. the dragon is opened mouth like he is ready to shout. Single Game Texture. In-Game asset. 3D. Blank background. High contrast. No shadows.
:quality(85)/https://cdn.frvr.ai/685acc12206de9599732464b.png%3F3) 
 standing air dragons on four legs, looking down. HD blue color. the dragon is opened mouth like he is ready to shout. Single Game Texture. In-Game asset. 3D. Blank background. High contrast. No shadows.
:quality(85)/https://cdn.frvr.ai/685ad1aa206de959973246b8.png%3F3) 
 Medieval "start game" buttons. HD colors. In-Game asset. High contrast. No shadows. 3D
:quality(85)/https://cdn.frvr.ai/685ecfa0d57c11a6010a30bd.png%3F3) 
 Medieval 'High score' buttons. HD colors. In-Game asset. High contrast. No shadows. 3D
:quality(85)/https://cdn.frvr.ai/685fc0bab2a222474ef6058a.png%3F3) 
 Airball of dragon shout. sphere. HD colors.. In-Game asset. 2d. High contrast. No shadows
:quality(85)/https://cdn.frvr.ai/685fdc50b2a222474ef60730.png%3F3)