Code edit (1 edits merged)
Please save this source code
User prompt
in initNewRound show the grisboard and hide the logo
Code edit (5 edits merged)
Please save this source code
User prompt
Please fix the bug: 'Uncaught ReferenceError: logo is not defined' in or related to this line: 'if (logo && currentState === GAME_STATE.MENU) {' Line Number: 1095
User prompt
move it 50px down
User prompt
move logo 100px down
User prompt
make logo 1480x1480 and remove it when changing state
User prompt
show logo in menu state
User prompt
Double water drops count
User prompt
Set fontaine base size to 250
User prompt
Increase Fontaine base size to 300
User prompt
Reduce the fountainโs size change to be +/-30 ( base size 200)
User prompt
Along with Fontain rotation, animate its size (use sin with +/-100px)
Code edit (1 edits merged)
Please save this source code
User prompt
Like the fontain, let the valve turn indefinetly
User prompt
Please fix the bug: 'Timeout.tick error: self.normalizeRotation is not a function' in or related to this line: 'var normalizedRotation = self.normalizeRotation(tile.rotation);' Line Number: 760
Code edit (1 edits merged)
Please save this source code
User prompt
Please fix the bug: 'Uncaught TypeError: self.normalizeRotation is not a function' in or related to this line: 'var normalizedRotation = self.normalizeRotation(tile.rotation);' Line Number: 752
Code edit (8 edits merged)
Please save this source code
User prompt
add detail logs using log() in flowThroughPipe enough to debug the water flow not working
Code edit (2 edits merged)
Please save this source code
User prompt
Please fix the bug: 'Uncaught TypeError: Cannot set properties of undefined (setting 'normalizeRotation')' in or related to this line: 'self.normalizeRotation = function (rotation) {' Line Number: 1134
User prompt
Please fix the bug: 'Uncaught TypeError: self.normalizeRotation is not a function' in or related to this line: 'var normalizedRotation = self.normalizeRotation(tile.rotation);' Line Number: 839
Code edit (1 edits merged)
Please save this source code
User prompt
log canReachEnd result (use log())
/**** 
* Classes
****/ 
var Tile = Container.expand(function () {
	var self = Container.call(this);
	// Properties
	self.type = 'empty';
	self.baseTint = 0x8FBE00;
	self.baseTintLight = 0x5ED000;
	self.maxWaterSize = 260;
	self.flowSpeed = 12;
	self.startFlowTicks = 0;
	self.flow = false;
	self.connections = [];
	self.position = {
		x: 0,
		y: 0
	};
	self.rotation = 0;
	// Methods
	self.setType = function (type, x, y) {
		self.type = type;
		var baseTileAsset = type == 'start' || type == 'end' || puzzleManager && puzzleManager.levelConfigs[puzzleManager.currentLevel].fixedTiles.includes(x + ',' + y) ? 'baseTile' : 'baseMobileTile';
		if (type == 'empty') {
			return;
		}
		// Attach baseTile asset
		self.baseTile = self.attachAsset(baseTileAsset, {
			anchorX: 0.5,
			anchorY: 0.5,
			width: tileSize,
			height: tileSize,
			tint: 0xFFFFFF
		});
		self.width = tileSize;
		self.height = tileSize;
		switch (type) {
			case 'start':
				self.attachAsset('startPipeAsset', {
					anchorX: 0.5,
					anchorY: 0.5,
					x: 20,
					y: 55,
					tint: self.baseTint
				});
				self.valve = self.attachAsset('vane', {
					anchorX: 0.5,
					anchorY: 0.5,
					x: 20,
					y: 15,
					tint: self.baseTint
				});
				self.water = self.attachAsset('waterV', {
					anchorX: 0.5,
					anchorY: 0,
					x: -0,
					y: -120,
					height: 0,
					visible: false,
					dir: ''
				});
				break;
			case 'end':
				self.attachAsset('endPipeAsset', {
					anchorX: 0.5,
					anchorY: 0.5,
					x: 0,
					y: 55,
					tint: self.baseTint
				});
				self.water = self.attachAsset('waterV', {
					anchorX: 0.5,
					anchorY: 0,
					x: -0,
					y: -120,
					height: 0,
					visible: false,
					dir: ''
				});
				self.fountain = self.attachAsset('fontain', {
					anchorX: 0.5,
					anchorY: 0.5,
					x: 0,
					y: 0,
					width: 0,
					height: 0,
					visible: false
				});
				break;
			case 'crossPipe':
				self.attachAsset('straightPipeHAsset', {
					anchorX: 0.5,
					anchorY: 0.5,
					y: -40,
					tint: self.baseTint
				});
				self.attachAsset('straightPipeHAsset', {
					anchorX: 0.5,
					anchorY: 0.5,
					scaleY: -1,
					y: 30,
					tint: self.baseTint
				});
				self.attachAsset('straightPipeVAsset', {
					anchorX: 0.5,
					anchorY: 0.5,
					x: -30,
					tint: self.baseTint
				});
				self.attachAsset('straightPipeVAsset', {
					anchorX: 0.5,
					anchorY: 0.5,
					scaleX: -1,
					x: 30,
					tint: self.baseTint
				});
				self.water = self.attachAsset('waterV', {
					anchorX: 0.5,
					anchorY: 0,
					x: -0,
					y: -120,
					height: 0,
					visible: false,
					dir: ''
				});
				break;
			case 'straightPipeH':
				self.attachAsset('straightPipeHAsset', {
					anchorX: 0.5,
					anchorY: 0.5,
					y: -40,
					tint: self.baseTint
				});
				self.attachAsset('straightPipeHAsset', {
					anchorX: 0.5,
					anchorY: 0.5,
					scaleY: -1,
					y: 30,
					tint: self.baseTint
				});
				self.water = self.attachAsset('waterH', {
					anchorX: 0,
					anchorY: 0.5,
					x: -130,
					y: -5,
					width: 0,
					visible: false,
					dir: 'lr'
				});
				break;
			case 'straightPipeV':
				self.attachAsset('straightPipeVAsset', {
					anchorX: 0.5,
					anchorY: 0.5,
					x: -30,
					tint: self.baseTint
				});
				self.attachAsset('straightPipeVAsset', {
					anchorX: 0.5,
					anchorY: 0.5,
					scaleX: -1,
					x: 30,
					tint: self.baseTint
				});
				self.water = self.attachAsset('waterV', {
					anchorX: 0.5,
					anchorY: 0,
					x: -0,
					y: -120,
					height: 0,
					visible: false,
					dir: 'tb'
				});
				break;
			case 'cornerPipe':
				self.attachAsset('cornerPipeAsset', {
					anchorX: 0.5,
					anchorY: 0.5,
					x: -60,
					y: -60,
					tint: self.baseTintLight
				});
				// Corner part of the water
				self.waterCorner = self.attachAsset('waterCorner', {
					anchorX: 1,
					anchorY: 1,
					width: 108,
					height: 108,
					x: -65,
					y: -65,
					rotation: -Math.PI / 2,
					//-Math.PI / 2, at start to -Math.PI,
					visible: false,
					dir: ''
				});
				// Vertical part of the water
				self.waterV = self.attachAsset('waterV', {
					anchorX: 0.5,
					anchorY: 0,
					width: 110,
					x: -120,
					y: -5,
					rotation: -Math.PI / 2,
					height: 0,
					visible: false,
					dir: ''
				});
				// Horizontal part of the water
				self.waterH = self.attachAsset('waterH', {
					anchorX: 0,
					anchorY: 0.5,
					x: -5,
					y: -50,
					//-15,
					width: 0,
					height: 112,
					rotation: -Math.PI / 2,
					visible: false,
					dir: ''
				});
				// Corner part of the water
				self.waterCornerCover = self.attachAsset('waterCorner', {
					anchorX: 1,
					anchorY: 1,
					width: 108,
					height: 108,
					x: -65,
					y: -65,
					rotation: -Math.PI,
					visible: false,
					dir: ''
				});
				break;
		}
	};
	self.updatePosition = function (x, y) {
		self.position.x = x;
		self.position.y = y;
		if (self.baseTile) {
			self.baseTile.width = tileSize;
			self.baseTile.height = tileSize;
		}
		self.x = x * tileSize + gridBoard.x - gridBoard.width / 2 + tileSize / 2 + boardOffsetX;
		self.y = y * tileSize + gridBoard.y - gridBoard.height / 2 + tileSize / 2 + boardOffsetY;
		log('Tile index:', x, y, 'Tile position:', self.x, self.y, 'Tile dimensions:', self.width, self.height, ' self:', self);
	};
	self.normalizeRotation = function (rotation) {
		// If rotation is a number (radians), convert it to our direction system
		if (typeof rotation === 'number') {
			// Convert radians to our direction system
			// 0 = right
			// ฯ/2 = down
			// ฯ = left
			// 3ฯ/2 = up
			var angle = rotation % (2 * Math.PI);
			if (angle < 0) {
				angle += 2 * Math.PI;
			}
			if (angle < Math.PI / 4 || angle > 7 * Math.PI / 4) {
				return 'right';
			}
			if (angle < 3 * Math.PI / 4) {
				return 'down';
			}
			if (angle < 5 * Math.PI / 4) {
				return 'left';
			}
			return 'up';
		}
		return rotation || 'down';
	};
	self.setRotation = function (direction) {
		switch (direction) {
			case 'left':
				self.rotation = Math.PI * 0.5;
				break;
			case 'right':
				self.rotation = -Math.PI * 0.5;
				break;
			case 'up':
				self.rotation = 0;
				break;
			case 'down':
				self.rotation = Math.PI;
				break;
		}
		log('Tile position:', self.x, self.y, 'Tile rotation:', self.rotation);
	};
	self.update = function () {
		if (self.flow) {
			if (!self.startFlowTicks) {
				self.startFlowTicks = LK.ticks;
				if (self.water) {
					self.water.visible = true;
				}
				if (self.waterV) {
					self.waterV.visible = true;
				}
				if (self.waterH) {
					self.waterH.visible = true;
				}
			}
			if (self.type === 'start') {
				// Rotate valve for start pipe
				var rotationValue = (LK.ticks - self.startFlowTicks) * 0.1;
				if (self.valve) {
					self.valve.rotation = rotationValue;
				}
				if (rotationValue >= Math.PI * 2) {
					self.flow = false;
				}
			} else if (self.type === 'cornerPipe') {
				// Corner pipe animation
				var progress = (LK.ticks - self.startFlowTicks) * self.flowSpeed; // Accelerate water speed
				var thirdSize = self.maxWaterSize / 3 - 10; // Split animation into three phases
				var sidesSize = self.maxWaterSize / 3; //+ 40;
				if (progress < self.maxWaterSize) {
					// Phase 1: Vertical water grows
					if (progress < thirdSize) {
						if (self.waterV) {
							self.waterV.height = progress;
						}
					}
					// Phase 2: Corner water appears and rotates
					else if (progress < thirdSize * 2) {
						if (self.waterV) {
							self.waterV.height = thirdSize; // Keep vertical at full first-phase height
						}
						if (self.waterCorner) {
							self.waterCorner.visible = true;
							self.waterCorner.alpha = Math.min(Math.max(0, ((progress - thirdSize) / thirdSize - 0.5) * 2, 0), 1); // Animate alpha from 0 to 1
							// Calculate rotation from -PI/2 to -PI
							var rotationProgress = (progress - thirdSize) / thirdSize; // 0 to 1
							self.waterCorner.rotation = -Math.PI / 2 - rotationProgress * Math.PI / 2;
						}
					}
					// Phase 3: Horizontal water grows
					else {
						if (self.waterV) {
							self.waterV.height = thirdSize;
						}
						if (self.waterCorner) {
							self.waterCorner.visible = true;
							self.waterCorner.alpha = 1;
							self.waterCorner.rotation = -Math.PI; // Keep at final rotation
						}
						if (self.waterH) {
							self.waterH.visible = true;
							self.waterH.width = Math.min(progress - thirdSize * 2, sidesSize);
						}
					}
				} else {
					self.flow = false;
				}
			} else if (self.type === 'end' && self.fountain) {
				// Animate fountain growth
				var sizeValue = (LK.ticks - self.startFlowTicks) * self.flowSpeed;
				if (sizeValue < self.maxWaterSize) {
					self.fountain.width = sizeValue;
					self.fountain.height = sizeValue;
					self.fountain.visible = true;
				} else {
					self.flow = false;
					if (!waterDropInterval) {
						createWaterDrops(self.x, self.y, game);
						waterDropInterval = LK.setInterval(function () {
							createWaterDrops(self.x, self.y, game);
						}, 500 + Math.random() * 500);
					}
				}
			} else if (self.water) {
				// Regular pipe animation
				var heightValue = (LK.ticks - self.startFlowTicks) * self.flowSpeed;
				if (self.water.dir != '' && heightValue < self.maxWaterSize) {
					if (self.water.dir == 'tb') {
						self.water.height = heightValue;
					}
					if (self.water.dir == 'lr') {
						self.water.width = heightValue;
					}
				} else {
					self.flow = false;
				}
			}
		}
		if (self.type === 'end' && self.fountain && self.fountain.visible) {
			self.fountain.rotation += 0.1; // Rotate the fountain indefinitely
		}
	};
	self.setType(self.type);
	return self;
});
var WaterDrop = Container.expand(function () {
	var self = Container.call(this);
	var waterDropGraphics = self.attachAsset('waterDrop', {
		anchorX: 0.5,
		anchorY: 0.5
	});
	// Set initial tint to a random  color
	var rainbowColors = [0xC7ECFE, 0xDDFDFF, 0xF4FFFF, 0xC8F8FF]; // Rainbow [0xFF0000, 0xFF7F00, 0xFFFF00, 0x00FF00, 0x0000FF, 0x4B0082, 0x8B00FF];
	waterDropGraphics.tint = rainbowColors[Math.floor(Math.random() * rainbowColors.length)];
	self.vx = 0;
	self.vy = 0;
	self.life = 0;
	self.size = 7;
	self.alpha = 0.75 + Math.random() * 0.25;
	self.update = function () {
		self.x += self.vx;
		self.y += self.vy;
		self.rotation = Math.atan2(self.vy, self.vx) + Math.PI * 0.55;
		// Animate size 
		var sizeProgress = (120 - self.life) / 120; // Assuming life starts at 120
		waterDropGraphics.width = self.size + sizeProgress * self.size * 2;
		waterDropGraphics.height = self.size * 2 + sizeProgress * self.size * 4;
		self.life--;
		if (self.life <= 0) {
			self.visible = false;
		}
	};
	return self;
});
/**** 
* Initialize Game
****/ 
var game = new LK.Game({
	backgroundColor: 0x000000
});
/**** 
* Game Code
****/ 
function _slicedToArray(r, e) {
	return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest();
}
function _nonIterableRest() {
	throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _unsupportedIterableToArray(r, a) {
	if (r) {
		if ("string" == typeof r) {
			return _arrayLikeToArray(r, a);
		}
		var t = {}.toString.call(r).slice(8, -1);
		return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0;
	}
}
function _arrayLikeToArray(r, a) {
	(null == a || a > r.length) && (a = r.length);
	for (var e = 0, n = Array(a); e < a; e++) {
		n[e] = r[e];
	}
	return n;
}
function _iterableToArrayLimit(r, l) {
	var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
	if (null != t) {
		var e,
			n,
			i,
			u,
			a = [],
			f = !0,
			o = !1;
		try {
			if (i = (t = t.call(r)).next, 0 === l) {
				if (Object(t) !== t) {
					return;
				}
				f = !1;
			} else {
				for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0) {
					;
				}
			}
		} catch (r) {
			o = !0, n = r;
		} finally {
			try {
				if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) {
					return;
				}
			} finally {
				if (o) {
					throw n;
				}
			}
		}
		return a;
	}
}
function _arrayWithHoles(r) {
	if (Array.isArray(r)) {
		return r;
	}
}
var SimpleSet = function SimpleSet() {
	this.items = {};
	this.has = function (item) {
		return this.items.hasOwnProperty(item);
	};
	this.add = function (item) {
		if (!this.has(item)) {
			this.items[item] = true;
		}
	};
};
var PuzzleManager = function PuzzleManager() {
	var self = this;
	// Properties
	self.currentLevel = 1;
	self.maxLevels = 30;
	self.grid = [];
	self.gridSize = 4;
	self.selectedTile = null;
	self.waterFlowing = false;
	self.isComplete = false;
	// Level configurations
	self.levelConfigs = {
		1: {
			tiles: [['start', 'straightPipeV', 'straightPipeV', 'cornerPipe'], [null, null, null, 'straightPipeH'], [null, null, 'straightPipeH', null], [null, null, null, 'end']],
			rotations: {
				'0,3': 'left',
				'3,3': 'left'
			},
			fixedTiles: ['0,0', '0,1', '0,2', '0,3', '1,3', '3,3'] // All tiles fixed except 2,2
		},
		2: {
			tiles: [['start', 'straightPipeH', null, null], [null, 'cornerPipe', null, null], [null, 'straightPipeV', 'cornerPipe', null], [null, null, null, 'end']],
			rotations: {
				'0,1': 'right',
				'1,1': 'down',
				'2,2': 'left'
			}
		}
		// Add more levels here
	};
	self.initPuzzle = function () {
		log("Initializing puzzle for level", self.currentLevel);
		// Clear existing grid
		self.grid = [];
		// Get level config
		var config = self.levelConfigs[self.currentLevel];
		if (!config) {
			log("No configuration for level", self.currentLevel);
			return;
		}
		// Initialize grid
		for (var i = 0; i < self.gridSize; i++) {
			self.grid[i] = [];
			for (var j = 0; j < self.gridSize; j++) {
				var tile = new Tile();
				if (config.tiles[i] && config.tiles[i][j]) {
					tile.setType(config.tiles[i][j], i, j);
				}
				tile.updatePosition(i, j);
				self.grid[i][j] = tile;
				game.addChild(tile);
			}
		}
		// Apply rotations
		if (config.rotations) {
			for (var pos in config.rotations) {
				var _pos$split$map = pos.split(',').map(Number),
					_pos$split$map2 = _slicedToArray(_pos$split$map, 2),
					x = _pos$split$map2[0],
					y = _pos$split$map2[1];
				self.grid[x][y].setRotation(config.rotations[pos]);
			}
		}
	};
	self.selectTile = function (x, y) {
		// Convert screen coordinates to grid coordinates
		if (!isPlaying) {
			return;
		}
		// Adjust coordinate calculation to use grid board position and size
		var boardX = gridBoard.x - gridBoard.width / 2;
		var boardY = gridBoard.y - gridBoard.height / 2;
		var gridX = Math.floor((x - boardX) / tileSize);
		var gridY = Math.floor((y - boardY) / tileSize);
		log("Grid coordinates:", gridX, gridY);
		// Check if coordinates are within grid
		if (gridX >= 0 && gridX < self.gridSize && gridY >= 0 && gridY < self.gridSize) {
			var tile = self.grid[gridX][gridY];
			var key = gridX + ',' + gridY;
			// Check if tile exists, is not empty, not start/end, and not fixed
			if (tile && tile.type !== 'empty' && tile.type !== 'start' && tile.type !== 'end' && (!self.levelConfigs[self.currentLevel].fixedTiles || !self.levelConfigs[self.currentLevel].fixedTiles.includes(key))) {
				self.selectedTile = {
					x: gridX,
					y: gridY,
					tile: tile
				};
				// Check possible moves
				self.checkPossibleMoves();
			}
		}
	};
	self.checkPossibleMoves = function () {
		if (!self.selectedTile) {
			return;
		}
		var x = self.selectedTile.x;
		var y = self.selectedTile.y;
		var possibleMoves = [];
		// Check each direction
		// Right
		if (x < self.gridSize - 1 && self.grid[x + 1][y].type === 'empty') {
			possibleMoves.push('right');
		}
		// Left
		if (x > 0 && self.grid[x - 1][y].type === 'empty') {
			possibleMoves.push('left');
		}
		// Down
		if (y < self.gridSize - 1 && self.grid[x][y + 1].type === 'empty') {
			possibleMoves.push('down');
		}
		// Up
		if (y > 0 && self.grid[x][y - 1].type === 'empty') {
			possibleMoves.push('up');
		}
		self.selectedTile.possibleMoves = possibleMoves;
	};
	self.moveTile = function (direction) {
		if (!isPlaying || !self.selectedTile || !self.selectedTile.possibleMoves.includes(direction)) {
			return;
		}
		var oldX = self.selectedTile.x;
		var oldY = self.selectedTile.y;
		var newX = oldX;
		var newY = oldY;
		// Calculate new position
		switch (direction) {
			case 'right':
				newX++;
				break;
			case 'left':
				newX--;
				break;
			case 'down':
				newY++;
				break;
			case 'up':
				newY--;
				break;
		}
		// Swap tiles
		var movingTile = self.grid[oldX][oldY];
		var emptyTile = self.grid[newX][newY];
		// Update grid
		self.grid[newX][newY] = movingTile;
		self.grid[oldX][oldY] = emptyTile;
		// Update positions
		movingTile.updatePosition(newX, newY);
		emptyTile.updatePosition(oldX, oldY);
		// Clear selection
		self.selectedTile = null;
		// Check if puzzle is solved
		if (self.checkWinCondition()) {
			self.isComplete = true;
			self.startWaterFlow();
			levelText.setText('Level: ' + self.currentLevel + ' Solved!');
			isPlaying = false;
		}
	};
	self.startWaterFlow = function () {
		if (self.waterFlowing) {
			return;
		}
		self.waterFlowing = true;
		// Find start position
		var startX = -1,
			startY = -1;
		for (var i = 0; i < self.gridSize; i++) {
			for (var j = 0; j < self.gridSize; j++) {
				if (self.grid[i][j].type === 'start') {
					startX = i;
					startY = j;
					break;
				}
			}
			if (startX !== -1) {
				break;
			}
		}
		// Start the flow animation from the start tile
		if (startX !== -1) {
			var startTile = self.grid[startX][startY];
			startTile.flow = true;
			startTile.startFlowTicks = 0;
			// Start valve animation
			if (startTile.valve) {
				startTile.valve.rotationSpeed = 0.1;
			}
			// Start flowing through pipes
			self.flowThroughPipe(startX, startY + 1, [startX + ',' + startY]);
		}
	};
	self.flowThroughPipe = function (x, y, visited) {
		if (x < 0 || x >= self.gridSize || y < 0 || y >= self.gridSize) {
			return;
		}
		var key = x + ',' + y;
		if (visited.includes(key)) {
			return;
		}
		visited.push(key);
		var tile = self.grid[x][y];
		if (!tile || tile.type === 'empty') {
			return;
		}
		// Start flow animation for this tile
		tile.flow = true;
		tile.startFlowTicks = visited.length * 30; // Delay based on distance from start
		// Get next positions to flow to
		var nextPositions = [];
		switch (tile.type) {
			case 'straightPipeV':
				nextPositions.push([x, y - 1], [x, y + 1]); // Up and down
				break;
			case 'straightPipeH':
				nextPositions.push([x - 1, y], [x + 1, y]); // Left and right
				break;
			case 'cornerPipe':
				switch (tile.rotation) {
					case 'up':
						// โ
						nextPositions.push([x, y - 1], [x + 1, y]); // Up and right
						break;
					case 'right':
						// โ
						nextPositions.push([x + 1, y], [x, y + 1]); // Right and down
						break;
					case 'down':
						// โ
						nextPositions.push([x - 1, y], [x, y + 1]); // Left and down
						break;
					case 'left':
						// โ
						nextPositions.push([x - 1, y], [x, y - 1]); // Left and up
						break;
				}
				break;
			case 'end':
				// Create water drops effect
				createWaterDrops(tile.x, tile.y + 100, game);
				break;
		}
		// Continue flow to next positions
		for (var i = 0; i < nextPositions.length; i++) {
			self.flowThroughPipe(nextPositions[i][0], nextPositions[i][1], visited);
		}
	};
	self.reset = function () {
		self.currentLevel = 1;
		self.selectedTile = null;
		self.isComplete = false;
		self.waterFlowing = false;
		self.initPuzzle();
	};
	self.checkWinCondition = function () {
		// Find start position
		log("Checking win condition");
		log("Start position search initiated.");
		var startX = -1,
			startY = -1;
		for (var i = 0; i < self.gridSize; i++) {
			for (var j = 0; j < self.gridSize; j++) {
				if (self.grid[i][j].type === 'start') {
					startX = i;
					startY = j;
					log("Start position found at:", startX, startY);
					break;
				}
			}
			if (startX !== -1) {
				break;
			}
		}
		// Use array to track visited positions (simpler than Set)
		var visited = [];
		// Start flowing down from start
		var result = self.canReachEnd(startX, startY + 1, visited);
		log("Visited tiles during win check:", visited);
		return result;
	};
	self.canReachEnd = function (x, y, visited) {
		// Check bounds
		log("canReachEnd called with coordinates:", x, y);
		if (x < 0 || x >= self.gridSize || y < 0 || y >= self.gridSize) {
			return false;
		}
		// Create position key
		var key = x + ',' + y;
		if (visited.includes(key)) {
			return false;
		}
		visited.push(key);
		var tile = self.grid[x][y];
		if (!tile || tile.type === 'empty') {
			return false;
		}
		// If we reached the end, success!
		if (tile.type === 'end') {
			return true;
		}
		// Get next possible positions based on current tile type and rotation
		var nextPositions = [];
		switch (tile.type) {
			case 'straightPipeV':
				nextPositions.push([x, y - 1], [x, y + 1]); // Up and down
				break;
			case 'straightPipeH':
				nextPositions.push([x - 1, y], [x + 1, y]); // Left and right
				break;
			case 'cornerPipe':
				switch (tile.rotation) {
					case 'up':
						// โ
						nextPositions.push([x, y - 1], [x + 1, y]); // Up and right
						break;
					case 'right':
						// โ
						nextPositions.push([x + 1, y], [x, y + 1]); // Right and down
						break;
					case 'down':
						// โ
						nextPositions.push([x - 1, y], [x, y + 1]); // Left and down
						break;
					case 'left':
						// โ
						nextPositions.push([x - 1, y], [x, y - 1]); // Left and up
						break;
				}
				break;
		}
		// Try each possible next position
		for (var i = 0; i < nextPositions.length; i++) {
			var nextX = nextPositions[i][0];
			var nextY = nextPositions[i][1];
			if (self.canReachEnd(nextX, nextY, visited)) {
				log("canReachEnd result:", true);
				return true;
			}
		}
		log("canReachEnd result:", false);
		return false;
	};
	return this;
};
/**** 
* Game Variables
****/ 
var debug = true;
function log() {
	if (debug) {
		console.log.apply(console, arguments);
	}
}
// Game constants
var tileSize = 400;
var boardOffsetX = 90;
var boardOffsetY = -100;
// Game state variables
var GAME_STATE = {
	INIT: 'INIT',
	MENU: 'MENU',
	NEW_ROUND: 'NEW_ROUND',
	PLAYING: 'PLAYING',
	SCORE: 'SCORE'
};
var currentState = GAME_STATE.INIT;
var isPlaying = true;
var gridBoard;
var isMouseDown = false;
var startX = 0;
var startY = 0;
var selectedTile = null;
var dragThreshold = 20;
var levelText;
var waterDrops = [];
var waterDropInterval;
var puzzleManager;
/**** 
* Helper Functions
****/ 
function createWaterDrops(x, y, game) {
	for (var i = 0; i < 10; i++) {
		var waterDrop = waterDrops.find(function (drop) {
			return !drop.visible;
		});
		if (!waterDrop) {
			waterDrop = new WaterDrop();
			waterDrops.push(waterDrop);
			game.addChild(waterDrop);
		}
		waterDrop.x = x;
		waterDrop.y = y;
		var angle = Math.random() * Math.PI * 2;
		var speed = Math.random() * 3 + 3;
		var easeFactor = Math.random() * 0.05 + 0.95; // Random easing factor between 0.95 and 1.0
		waterDrop.vx = Math.cos(angle) * speed * easeFactor;
		waterDrop.vy = Math.sin(angle) * speed * easeFactor;
		waterDrop.life = 120;
		waterDrop.visible = true;
	}
}
/**** 
* Game State Management
****/ 
function initializeGame() {
	// Initialize game assets and variables
	puzzleManager = new PuzzleManager();
	// Initialize level text
	levelText = new Text2("Level 1", {
		size: 100,
		fill: "#ffffff"
	});
	levelText.x = 2048 / 2;
	levelText.y = 200;
	levelText.anchorX = 0.5;
	// Add the level text to the game
	game.addChild(levelText);
	// Initialize grid board
	gridBoard = LK.getAsset('gridBoard', {
		anchorX: 0.5,
		anchorY: 0.5
	});
	gridBoard.x = 2048 / 2;
	gridBoard.y = 2732 / 2;
	game.addChild(gridBoard);
	// Transition to menu state
	changeGameState(GAME_STATE.MENU);
}
function initMenuState() {
	// Show level selection UI
	console.log("Entering Menu State");
	isPlaying = false;
	levelText.visible = true;
	levelText.text = "Level 1\nTap to Start";
}
function handleMenuLoop() {
	// Update any menu animations here
}
function cleanMenuState() {
	levelText.visible = true;
	levelText.text = "Level 1";
}
function initNewRoundState() {
	// Reset puzzle manager for new round
	console.log("Entering New Round State");
	if (puzzleManager) {
		puzzleManager.reset();
	}
	// After a short delay, transition to PLAYING state
	LK.setTimeout(function () {
		changeGameState(GAME_STATE.PLAYING);
	}, 1000);
}
function handleNewRoundLoop() {
	// Any pre-game animations can go here
}
function cleanNewRoundState() {
	// Clean up any new round state
}
function initPlayingState() {
	// Start the gameplay
	console.log("Entering Playing State");
	isPlaying = true;
}
function handlePlayingLoop() {
	// Update game logic
	if (puzzleManager) {
		puzzleManager.update();
		// Check if level is complete
		if (puzzleManager.isComplete) {
			changeGameState(GAME_STATE.SCORE);
		}
	}
}
function cleanPlayingState() {
	isPlaying = false;
}
function initScoreState() {
	// Show score screen
	console.log("Entering Score State");
	levelText.visible = true;
	levelText.text = "Level Complete!\nTap to continue";
}
function handleScoreLoop() {
	// Update any score animations
	if (puzzleManager) {
		puzzleManager.update();
	}
}
function cleanScoreState() {
	levelText.visible = false;
}
function changeGameState(newState) {
	// Clean up current state
	console.log("Changing state from", currentState, "to", newState);
	switch (currentState) {
		case GAME_STATE.MENU:
			cleanMenuState();
			break;
		case GAME_STATE.NEW_ROUND:
			cleanNewRoundState();
			break;
		case GAME_STATE.PLAYING:
			cleanPlayingState();
			break;
		case GAME_STATE.SCORE:
			cleanScoreState();
			break;
	}
	// Initialize new state
	currentState = newState;
	switch (newState) {
		case GAME_STATE.MENU:
			initMenuState();
			break;
		case GAME_STATE.NEW_ROUND:
			initNewRoundState();
			break;
		case GAME_STATE.PLAYING:
			initPlayingState();
			break;
		case GAME_STATE.SCORE:
			initScoreState();
			break;
	}
}
/**** 
* Event Handlers
****/ 
game.down = function (x, y, obj) {
	switch (currentState) {
		case GAME_STATE.MENU:
			changeGameState(GAME_STATE.NEW_ROUND);
			break;
		case GAME_STATE.PLAYING:
			startX = x;
			startY = y;
			isMouseDown = true;
			if (puzzleManager) {
				puzzleManager.selectTile(x, y);
			}
			break;
		case GAME_STATE.SCORE:
			changeGameState(GAME_STATE.MENU);
			break;
	}
};
game.move = function (x, y, obj) {
	if (currentState !== GAME_STATE.PLAYING || !isMouseDown || !puzzleManager || !puzzleManager.selectedTile) {
		return;
	}
	var deltaX = x - startX;
	var deltaY = y - startY;
	// Only move if drag distance exceeds threshold
	if (Math.abs(deltaX) > dragThreshold || Math.abs(deltaY) > dragThreshold) {
		var direction = null;
		if (Math.abs(deltaX) > Math.abs(deltaY)) {
			direction = deltaX > 0 ? 'right' : 'left';
		} else {
			direction = deltaY > 0 ? 'down' : 'up';
		}
		puzzleManager.moveTile(direction);
		isMouseDown = false; // Reset after move
	}
};
game.up = function (x, y, obj) {
	isMouseDown = false;
	if (currentState === GAME_STATE.PLAYING && puzzleManager) {
		puzzleManager.selectedTile = null;
	}
};
/**** 
* Main Update Loop
****/ 
function update() {
	// Handle state-specific updates
	switch (currentState) {
		case GAME_STATE.MENU:
			handleMenuLoop();
			break;
		case GAME_STATE.NEW_ROUND:
			handleNewRoundLoop();
			break;
		case GAME_STATE.PLAYING:
			handlePlayingLoop();
			break;
		case GAME_STATE.SCORE:
			handleScoreLoop();
			break;
	}
	// Update water drops
	for (var i = waterDrops.length - 1; i >= 0; i--) {
		if (waterDrops[i].visible) {
			waterDrops[i].update();
		}
	}
}
// Start the game
initializeGame(); /**** 
* Classes
****/ 
var Tile = Container.expand(function () {
	var self = Container.call(this);
	// Properties
	self.type = 'empty';
	self.baseTint = 0x8FBE00;
	self.baseTintLight = 0x5ED000;
	self.maxWaterSize = 260;
	self.flowSpeed = 12;
	self.startFlowTicks = 0;
	self.flow = false;
	self.connections = [];
	self.position = {
		x: 0,
		y: 0
	};
	self.rotation = 0;
	// Methods
	self.setType = function (type, x, y) {
		self.type = type;
		var baseTileAsset = type == 'start' || type == 'end' || puzzleManager && puzzleManager.levelConfigs[puzzleManager.currentLevel].fixedTiles.includes(x + ',' + y) ? 'baseTile' : 'baseMobileTile';
		if (type == 'empty') {
			return;
		}
		// Attach baseTile asset
		self.baseTile = self.attachAsset(baseTileAsset, {
			anchorX: 0.5,
			anchorY: 0.5,
			width: tileSize,
			height: tileSize,
			tint: 0xFFFFFF
		});
		self.width = tileSize;
		self.height = tileSize;
		switch (type) {
			case 'start':
				self.attachAsset('startPipeAsset', {
					anchorX: 0.5,
					anchorY: 0.5,
					x: 20,
					y: 55,
					tint: self.baseTint
				});
				self.valve = self.attachAsset('vane', {
					anchorX: 0.5,
					anchorY: 0.5,
					x: 20,
					y: 15,
					tint: self.baseTint
				});
				self.water = self.attachAsset('waterV', {
					anchorX: 0.5,
					anchorY: 0,
					x: -0,
					y: -120,
					height: 0,
					visible: false,
					dir: ''
				});
				break;
			case 'end':
				self.attachAsset('endPipeAsset', {
					anchorX: 0.5,
					anchorY: 0.5,
					x: 0,
					y: 55,
					tint: self.baseTint
				});
				self.water = self.attachAsset('waterV', {
					anchorX: 0.5,
					anchorY: 0,
					x: -0,
					y: -120,
					height: 0,
					visible: false,
					dir: ''
				});
				self.fountain = self.attachAsset('fontain', {
					anchorX: 0.5,
					anchorY: 0.5,
					x: 0,
					y: 0,
					width: 0,
					height: 0,
					visible: false
				});
				break;
			case 'crossPipe':
				self.attachAsset('straightPipeHAsset', {
					anchorX: 0.5,
					anchorY: 0.5,
					y: -40,
					tint: self.baseTint
				});
				self.attachAsset('straightPipeHAsset', {
					anchorX: 0.5,
					anchorY: 0.5,
					scaleY: -1,
					y: 30,
					tint: self.baseTint
				});
				self.attachAsset('straightPipeVAsset', {
					anchorX: 0.5,
					anchorY: 0.5,
					x: -30,
					tint: self.baseTint
				});
				self.attachAsset('straightPipeVAsset', {
					anchorX: 0.5,
					anchorY: 0.5,
					scaleX: -1,
					x: 30,
					tint: self.baseTint
				});
				self.water = self.attachAsset('waterV', {
					anchorX: 0.5,
					anchorY: 0,
					x: -0,
					y: -120,
					height: 0,
					visible: false,
					dir: ''
				});
				break;
			case 'straightPipeH':
				self.attachAsset('straightPipeHAsset', {
					anchorX: 0.5,
					anchorY: 0.5,
					y: -40,
					tint: self.baseTint
				});
				self.attachAsset('straightPipeHAsset', {
					anchorX: 0.5,
					anchorY: 0.5,
					scaleY: -1,
					y: 30,
					tint: self.baseTint
				});
				self.water = self.attachAsset('waterH', {
					anchorX: 0,
					anchorY: 0.5,
					x: -130,
					y: -5,
					width: 0,
					visible: false,
					dir: 'lr'
				});
				break;
			case 'straightPipeV':
				self.attachAsset('straightPipeVAsset', {
					anchorX: 0.5,
					anchorY: 0.5,
					x: -30,
					tint: self.baseTint
				});
				self.attachAsset('straightPipeVAsset', {
					anchorX: 0.5,
					anchorY: 0.5,
					scaleX: -1,
					x: 30,
					tint: self.baseTint
				});
				self.water = self.attachAsset('waterV', {
					anchorX: 0.5,
					anchorY: 0,
					x: -0,
					y: -120,
					height: 0,
					visible: false,
					dir: 'tb'
				});
				break;
			case 'cornerPipe':
				self.attachAsset('cornerPipeAsset', {
					anchorX: 0.5,
					anchorY: 0.5,
					x: -60,
					y: -60,
					tint: self.baseTintLight
				});
				// Corner part of the water
				self.waterCorner = self.attachAsset('waterCorner', {
					anchorX: 1,
					anchorY: 1,
					width: 108,
					height: 108,
					x: -65,
					y: -65,
					rotation: -Math.PI / 2,
					//-Math.PI / 2, at start to -Math.PI,
					visible: false,
					dir: ''
				});
				// Vertical part of the water
				self.waterV = self.attachAsset('waterV', {
					anchorX: 0.5,
					anchorY: 0,
					width: 110,
					x: -120,
					y: -5,
					rotation: -Math.PI / 2,
					height: 0,
					visible: false,
					dir: ''
				});
				// Horizontal part of the water
				self.waterH = self.attachAsset('waterH', {
					anchorX: 0,
					anchorY: 0.5,
					x: -5,
					y: -50,
					//-15,
					width: 0,
					height: 112,
					rotation: -Math.PI / 2,
					visible: false,
					dir: ''
				});
				// Corner part of the water
				self.waterCornerCover = self.attachAsset('waterCorner', {
					anchorX: 1,
					anchorY: 1,
					width: 108,
					height: 108,
					x: -65,
					y: -65,
					rotation: -Math.PI,
					visible: false,
					dir: ''
				});
				break;
		}
	};
	self.updatePosition = function (x, y) {
		self.position.x = x;
		self.position.y = y;
		if (self.baseTile) {
			self.baseTile.width = tileSize;
			self.baseTile.height = tileSize;
		}
		self.x = x * tileSize + gridBoard.x - gridBoard.width / 2 + tileSize / 2 + boardOffsetX;
		self.y = y * tileSize + gridBoard.y - gridBoard.height / 2 + tileSize / 2 + boardOffsetY;
		log('Tile index:', x, y, 'Tile position:', self.x, self.y, 'Tile dimensions:', self.width, self.height, ' self:', self);
	};
	self.normalizeRotation = function (rotation) {
		// If rotation is a number (radians), convert it to our direction system
		if (typeof rotation === 'number') {
			// Convert radians to our direction system
			// 0 = right
			// ฯ/2 = down
			// ฯ = left
			// 3ฯ/2 = up
			var angle = rotation % (2 * Math.PI);
			if (angle < 0) {
				angle += 2 * Math.PI;
			}
			if (angle < Math.PI / 4 || angle > 7 * Math.PI / 4) {
				return 'right';
			}
			if (angle < 3 * Math.PI / 4) {
				return 'down';
			}
			if (angle < 5 * Math.PI / 4) {
				return 'left';
			}
			return 'up';
		}
		return rotation || 'down';
	};
	self.setRotation = function (direction) {
		switch (direction) {
			case 'left':
				self.rotation = Math.PI * 0.5;
				break;
			case 'right':
				self.rotation = -Math.PI * 0.5;
				break;
			case 'up':
				self.rotation = 0;
				break;
			case 'down':
				self.rotation = Math.PI;
				break;
		}
		log('Tile position:', self.x, self.y, 'Tile rotation:', self.rotation);
	};
	self.update = function () {
		if (self.flow) {
			if (!self.startFlowTicks) {
				self.startFlowTicks = LK.ticks;
				if (self.water) {
					self.water.visible = true;
				}
				if (self.waterV) {
					self.waterV.visible = true;
				}
				if (self.waterH) {
					self.waterH.visible = true;
				}
			}
			if (self.type === 'start') {
				// Rotate valve for start pipe
				var rotationValue = (LK.ticks - self.startFlowTicks) * 0.1;
				if (self.valve) {
					self.valve.rotation = rotationValue;
				}
				if (rotationValue >= Math.PI * 2) {
					self.flow = false;
				}
			} else if (self.type === 'cornerPipe') {
				// Corner pipe animation
				var progress = (LK.ticks - self.startFlowTicks) * self.flowSpeed; // Accelerate water speed
				var thirdSize = self.maxWaterSize / 3 - 10; // Split animation into three phases
				var sidesSize = self.maxWaterSize / 3; //+ 40;
				if (progress < self.maxWaterSize) {
					// Phase 1: Vertical water grows
					if (progress < thirdSize) {
						if (self.waterV) {
							self.waterV.height = progress;
						}
					}
					// Phase 2: Corner water appears and rotates
					else if (progress < thirdSize * 2) {
						if (self.waterV) {
							self.waterV.height = thirdSize; // Keep vertical at full first-phase height
						}
						if (self.waterCorner) {
							self.waterCorner.visible = true;
							self.waterCorner.alpha = Math.min(Math.max(0, ((progress - thirdSize) / thirdSize - 0.5) * 2, 0), 1); // Animate alpha from 0 to 1
							// Calculate rotation from -PI/2 to -PI
							var rotationProgress = (progress - thirdSize) / thirdSize; // 0 to 1
							self.waterCorner.rotation = -Math.PI / 2 - rotationProgress * Math.PI / 2;
						}
					}
					// Phase 3: Horizontal water grows
					else {
						if (self.waterV) {
							self.waterV.height = thirdSize;
						}
						if (self.waterCorner) {
							self.waterCorner.visible = true;
							self.waterCorner.alpha = 1;
							self.waterCorner.rotation = -Math.PI; // Keep at final rotation
						}
						if (self.waterH) {
							self.waterH.visible = true;
							self.waterH.width = Math.min(progress - thirdSize * 2, sidesSize);
						}
					}
				} else {
					self.flow = false;
				}
			} else if (self.type === 'end' && self.fountain) {
				// Animate fountain growth
				var sizeValue = (LK.ticks - self.startFlowTicks) * self.flowSpeed;
				if (sizeValue < self.maxWaterSize) {
					self.fountain.width = sizeValue;
					self.fountain.height = sizeValue;
					self.fountain.visible = true;
				} else {
					self.flow = false;
					if (!waterDropInterval) {
						createWaterDrops(self.x, self.y, game);
						waterDropInterval = LK.setInterval(function () {
							createWaterDrops(self.x, self.y, game);
						}, 500 + Math.random() * 500);
					}
				}
			} else if (self.water) {
				// Regular pipe animation
				var heightValue = (LK.ticks - self.startFlowTicks) * self.flowSpeed;
				if (self.water.dir != '' && heightValue < self.maxWaterSize) {
					if (self.water.dir == 'tb') {
						self.water.height = heightValue;
					}
					if (self.water.dir == 'lr') {
						self.water.width = heightValue;
					}
				} else {
					self.flow = false;
				}
			}
		}
		if (self.type === 'end' && self.fountain && self.fountain.visible) {
			self.fountain.rotation += 0.1; // Rotate the fountain indefinitely
		}
	};
	self.setType(self.type);
	return self;
});
var WaterDrop = Container.expand(function () {
	var self = Container.call(this);
	var waterDropGraphics = self.attachAsset('waterDrop', {
		anchorX: 0.5,
		anchorY: 0.5
	});
	// Set initial tint to a random  color
	var rainbowColors = [0xC7ECFE, 0xDDFDFF, 0xF4FFFF, 0xC8F8FF]; // Rainbow [0xFF0000, 0xFF7F00, 0xFFFF00, 0x00FF00, 0x0000FF, 0x4B0082, 0x8B00FF];
	waterDropGraphics.tint = rainbowColors[Math.floor(Math.random() * rainbowColors.length)];
	self.vx = 0;
	self.vy = 0;
	self.life = 0;
	self.size = 7;
	self.alpha = 0.75 + Math.random() * 0.25;
	self.update = function () {
		self.x += self.vx;
		self.y += self.vy;
		self.rotation = Math.atan2(self.vy, self.vx) + Math.PI * 0.55;
		// Animate size 
		var sizeProgress = (120 - self.life) / 120; // Assuming life starts at 120
		waterDropGraphics.width = self.size + sizeProgress * self.size * 2;
		waterDropGraphics.height = self.size * 2 + sizeProgress * self.size * 4;
		self.life--;
		if (self.life <= 0) {
			self.visible = false;
		}
	};
	return self;
});
/**** 
* Initialize Game
****/ 
var game = new LK.Game({
	backgroundColor: 0x000000
});
/**** 
* Game Code
****/ 
function _slicedToArray(r, e) {
	return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest();
}
function _nonIterableRest() {
	throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _unsupportedIterableToArray(r, a) {
	if (r) {
		if ("string" == typeof r) {
			return _arrayLikeToArray(r, a);
		}
		var t = {}.toString.call(r).slice(8, -1);
		return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0;
	}
}
function _arrayLikeToArray(r, a) {
	(null == a || a > r.length) && (a = r.length);
	for (var e = 0, n = Array(a); e < a; e++) {
		n[e] = r[e];
	}
	return n;
}
function _iterableToArrayLimit(r, l) {
	var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
	if (null != t) {
		var e,
			n,
			i,
			u,
			a = [],
			f = !0,
			o = !1;
		try {
			if (i = (t = t.call(r)).next, 0 === l) {
				if (Object(t) !== t) {
					return;
				}
				f = !1;
			} else {
				for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0) {
					;
				}
			}
		} catch (r) {
			o = !0, n = r;
		} finally {
			try {
				if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) {
					return;
				}
			} finally {
				if (o) {
					throw n;
				}
			}
		}
		return a;
	}
}
function _arrayWithHoles(r) {
	if (Array.isArray(r)) {
		return r;
	}
}
var SimpleSet = function SimpleSet() {
	this.items = {};
	this.has = function (item) {
		return this.items.hasOwnProperty(item);
	};
	this.add = function (item) {
		if (!this.has(item)) {
			this.items[item] = true;
		}
	};
};
var PuzzleManager = function PuzzleManager() {
	var self = this;
	// Properties
	self.currentLevel = 1;
	self.maxLevels = 30;
	self.grid = [];
	self.gridSize = 4;
	self.selectedTile = null;
	self.waterFlowing = false;
	self.isComplete = false;
	// Level configurations
	self.levelConfigs = {
		1: {
			tiles: [['start', 'straightPipeV', 'straightPipeV', 'cornerPipe'], [null, null, null, 'straightPipeH'], [null, null, 'straightPipeH', null], [null, null, null, 'end']],
			rotations: {
				'0,3': 'left',
				'3,3': 'left'
			},
			fixedTiles: ['0,0', '0,1', '0,2', '0,3', '1,3', '3,3'] // All tiles fixed except 2,2
		},
		2: {
			tiles: [['start', 'straightPipeH', null, null], [null, 'cornerPipe', null, null], [null, 'straightPipeV', 'cornerPipe', null], [null, null, null, 'end']],
			rotations: {
				'0,1': 'right',
				'1,1': 'down',
				'2,2': 'left'
			}
		}
		// Add more levels here
	};
	self.initPuzzle = function () {
		log("Initializing puzzle for level", self.currentLevel);
		// Clear existing grid
		self.grid = [];
		// Get level config
		var config = self.levelConfigs[self.currentLevel];
		if (!config) {
			log("No configuration for level", self.currentLevel);
			return;
		}
		// Initialize grid
		for (var i = 0; i < self.gridSize; i++) {
			self.grid[i] = [];
			for (var j = 0; j < self.gridSize; j++) {
				var tile = new Tile();
				if (config.tiles[i] && config.tiles[i][j]) {
					tile.setType(config.tiles[i][j], i, j);
				}
				tile.updatePosition(i, j);
				self.grid[i][j] = tile;
				game.addChild(tile);
			}
		}
		// Apply rotations
		if (config.rotations) {
			for (var pos in config.rotations) {
				var _pos$split$map = pos.split(',').map(Number),
					_pos$split$map2 = _slicedToArray(_pos$split$map, 2),
					x = _pos$split$map2[0],
					y = _pos$split$map2[1];
				self.grid[x][y].setRotation(config.rotations[pos]);
			}
		}
	};
	self.selectTile = function (x, y) {
		// Convert screen coordinates to grid coordinates
		if (!isPlaying) {
			return;
		}
		// Adjust coordinate calculation to use grid board position and size
		var boardX = gridBoard.x - gridBoard.width / 2;
		var boardY = gridBoard.y - gridBoard.height / 2;
		var gridX = Math.floor((x - boardX) / tileSize);
		var gridY = Math.floor((y - boardY) / tileSize);
		log("Grid coordinates:", gridX, gridY);
		// Check if coordinates are within grid
		if (gridX >= 0 && gridX < self.gridSize && gridY >= 0 && gridY < self.gridSize) {
			var tile = self.grid[gridX][gridY];
			var key = gridX + ',' + gridY;
			// Check if tile exists, is not empty, not start/end, and not fixed
			if (tile && tile.type !== 'empty' && tile.type !== 'start' && tile.type !== 'end' && (!self.levelConfigs[self.currentLevel].fixedTiles || !self.levelConfigs[self.currentLevel].fixedTiles.includes(key))) {
				self.selectedTile = {
					x: gridX,
					y: gridY,
					tile: tile
				};
				// Check possible moves
				self.checkPossibleMoves();
			}
		}
	};
	self.checkPossibleMoves = function () {
		if (!self.selectedTile) {
			return;
		}
		var x = self.selectedTile.x;
		var y = self.selectedTile.y;
		var possibleMoves = [];
		// Check each direction
		// Right
		if (x < self.gridSize - 1 && self.grid[x + 1][y].type === 'empty') {
			possibleMoves.push('right');
		}
		// Left
		if (x > 0 && self.grid[x - 1][y].type === 'empty') {
			possibleMoves.push('left');
		}
		// Down
		if (y < self.gridSize - 1 && self.grid[x][y + 1].type === 'empty') {
			possibleMoves.push('down');
		}
		// Up
		if (y > 0 && self.grid[x][y - 1].type === 'empty') {
			possibleMoves.push('up');
		}
		self.selectedTile.possibleMoves = possibleMoves;
	};
	self.moveTile = function (direction) {
		if (!isPlaying || !self.selectedTile || !self.selectedTile.possibleMoves.includes(direction)) {
			return;
		}
		var oldX = self.selectedTile.x;
		var oldY = self.selectedTile.y;
		var newX = oldX;
		var newY = oldY;
		// Calculate new position
		switch (direction) {
			case 'right':
				newX++;
				break;
			case 'left':
				newX--;
				break;
			case 'down':
				newY++;
				break;
			case 'up':
				newY--;
				break;
		}
		// Swap tiles
		var movingTile = self.grid[oldX][oldY];
		var emptyTile = self.grid[newX][newY];
		// Update grid
		self.grid[newX][newY] = movingTile;
		self.grid[oldX][oldY] = emptyTile;
		// Update positions
		movingTile.updatePosition(newX, newY);
		emptyTile.updatePosition(oldX, oldY);
		// Clear selection
		self.selectedTile = null;
		// Check if puzzle is solved
		if (self.checkWinCondition()) {
			self.isComplete = true;
			self.startWaterFlow();
			levelText.setText('Level: ' + self.currentLevel + ' Solved!');
			isPlaying = false;
		}
	};
	self.startWaterFlow = function () {
		if (self.waterFlowing) {
			return;
		}
		self.waterFlowing = true;
		// Find start position
		var startX = -1,
			startY = -1;
		for (var i = 0; i < self.gridSize; i++) {
			for (var j = 0; j < self.gridSize; j++) {
				if (self.grid[i][j].type === 'start') {
					startX = i;
					startY = j;
					break;
				}
			}
			if (startX !== -1) {
				break;
			}
		}
		// Start the flow animation from the start tile
		if (startX !== -1) {
			var startTile = self.grid[startX][startY];
			startTile.flow = true;
			startTile.startFlowTicks = 0;
			// Start valve animation
			if (startTile.valve) {
				startTile.valve.rotationSpeed = 0.1;
			}
			// Start flowing through pipes
			self.flowThroughPipe(startX, startY + 1, [startX + ',' + startY]);
		}
	};
	self.flowThroughPipe = function (x, y, visited) {
		if (x < 0 || x >= self.gridSize || y < 0 || y >= self.gridSize) {
			return;
		}
		var key = x + ',' + y;
		if (visited.includes(key)) {
			return;
		}
		visited.push(key);
		var tile = self.grid[x][y];
		if (!tile || tile.type === 'empty') {
			return;
		}
		// Start flow animation for this tile
		tile.flow = true;
		tile.startFlowTicks = visited.length * 30; // Delay based on distance from start
		// Get next positions to flow to
		var nextPositions = [];
		switch (tile.type) {
			case 'straightPipeV':
				nextPositions.push([x, y - 1], [x, y + 1]); // Up and down
				break;
			case 'straightPipeH':
				nextPositions.push([x - 1, y], [x + 1, y]); // Left and right
				break;
			case 'cornerPipe':
				switch (tile.rotation) {
					case 'up':
						// โ
						nextPositions.push([x, y - 1], [x + 1, y]); // Up and right
						break;
					case 'right':
						// โ
						nextPositions.push([x + 1, y], [x, y + 1]); // Right and down
						break;
					case 'down':
						// โ
						nextPositions.push([x - 1, y], [x, y + 1]); // Left and down
						break;
					case 'left':
						// โ
						nextPositions.push([x - 1, y], [x, y - 1]); // Left and up
						break;
				}
				break;
			case 'end':
				// Create water drops effect
				createWaterDrops(tile.x, tile.y + 100, game);
				break;
		}
		// Continue flow to next positions
		for (var i = 0; i < nextPositions.length; i++) {
			self.flowThroughPipe(nextPositions[i][0], nextPositions[i][1], visited);
		}
	};
	self.reset = function () {
		self.currentLevel = 1;
		self.selectedTile = null;
		self.isComplete = false;
		self.waterFlowing = false;
		self.initPuzzle();
	};
	self.checkWinCondition = function () {
		// Find start position
		log("Checking win condition");
		log("Start position search initiated.");
		var startX = -1,
			startY = -1;
		for (var i = 0; i < self.gridSize; i++) {
			for (var j = 0; j < self.gridSize; j++) {
				if (self.grid[i][j].type === 'start') {
					startX = i;
					startY = j;
					log("Start position found at:", startX, startY);
					break;
				}
			}
			if (startX !== -1) {
				break;
			}
		}
		// Use array to track visited positions (simpler than Set)
		var visited = [];
		// Start flowing down from start
		var result = self.canReachEnd(startX, startY + 1, visited);
		log("Visited tiles during win check:", visited);
		return result;
	};
	self.canReachEnd = function (x, y, visited) {
		// Check bounds
		log("canReachEnd called with coordinates:", x, y);
		if (x < 0 || x >= self.gridSize || y < 0 || y >= self.gridSize) {
			return false;
		}
		// Create position key
		var key = x + ',' + y;
		if (visited.includes(key)) {
			return false;
		}
		visited.push(key);
		var tile = self.grid[x][y];
		if (!tile || tile.type === 'empty') {
			return false;
		}
		// If we reached the end, success!
		if (tile.type === 'end') {
			return true;
		}
		// Get next possible positions based on current tile type and rotation
		var nextPositions = [];
		switch (tile.type) {
			case 'straightPipeV':
				nextPositions.push([x, y - 1], [x, y + 1]); // Up and down
				break;
			case 'straightPipeH':
				nextPositions.push([x - 1, y], [x + 1, y]); // Left and right
				break;
			case 'cornerPipe':
				switch (tile.rotation) {
					case 'up':
						// โ
						nextPositions.push([x, y - 1], [x + 1, y]); // Up and right
						break;
					case 'right':
						// โ
						nextPositions.push([x + 1, y], [x, y + 1]); // Right and down
						break;
					case 'down':
						// โ
						nextPositions.push([x - 1, y], [x, y + 1]); // Left and down
						break;
					case 'left':
						// โ
						nextPositions.push([x - 1, y], [x, y - 1]); // Left and up
						break;
				}
				break;
		}
		// Try each possible next position
		for (var i = 0; i < nextPositions.length; i++) {
			var nextX = nextPositions[i][0];
			var nextY = nextPositions[i][1];
			if (self.canReachEnd(nextX, nextY, visited)) {
				log("canReachEnd result:", true);
				return true;
			}
		}
		log("canReachEnd result:", false);
		return false;
	};
	return this;
};
/**** 
* Game Variables
****/ 
var debug = true;
function log() {
	if (debug) {
		console.log.apply(console, arguments);
	}
}
// Game constants
var tileSize = 400;
var boardOffsetX = 90;
var boardOffsetY = -100;
// Game state variables
var GAME_STATE = {
	INIT: 'INIT',
	MENU: 'MENU',
	NEW_ROUND: 'NEW_ROUND',
	PLAYING: 'PLAYING',
	SCORE: 'SCORE'
};
var currentState = GAME_STATE.INIT;
var isPlaying = true;
var gridBoard;
var isMouseDown = false;
var startX = 0;
var startY = 0;
var selectedTile = null;
var dragThreshold = 20;
var levelText;
var waterDrops = [];
var waterDropInterval;
var puzzleManager;
/**** 
* Helper Functions
****/ 
function createWaterDrops(x, y, game) {
	for (var i = 0; i < 10; i++) {
		var waterDrop = waterDrops.find(function (drop) {
			return !drop.visible;
		});
		if (!waterDrop) {
			waterDrop = new WaterDrop();
			waterDrops.push(waterDrop);
			game.addChild(waterDrop);
		}
		waterDrop.x = x;
		waterDrop.y = y;
		var angle = Math.random() * Math.PI * 2;
		var speed = Math.random() * 3 + 3;
		var easeFactor = Math.random() * 0.05 + 0.95; // Random easing factor between 0.95 and 1.0
		waterDrop.vx = Math.cos(angle) * speed * easeFactor;
		waterDrop.vy = Math.sin(angle) * speed * easeFactor;
		waterDrop.life = 120;
		waterDrop.visible = true;
	}
}
/**** 
* Game State Management
****/ 
function initializeGame() {
	// Initialize game assets and variables
	puzzleManager = new PuzzleManager();
	// Initialize level text
	levelText = new Text2("Level 1", {
		size: 100,
		fill: "#ffffff"
	});
	levelText.x = 2048 / 2;
	levelText.y = 200;
	levelText.anchorX = 0.5;
	// Add the level text to the game
	game.addChild(levelText);
	// Initialize grid board
	gridBoard = LK.getAsset('gridBoard', {
		anchorX: 0.5,
		anchorY: 0.5
	});
	gridBoard.x = 2048 / 2;
	gridBoard.y = 2732 / 2;
	game.addChild(gridBoard);
	// Transition to menu state
	changeGameState(GAME_STATE.MENU);
}
function initMenuState() {
	// Show level selection UI
	console.log("Entering Menu State");
	isPlaying = false;
	levelText.visible = true;
	levelText.text = "Level 1\nTap to Start";
}
function handleMenuLoop() {
	// Update any menu animations here
}
function cleanMenuState() {
	levelText.visible = true;
	levelText.text = "Level 1";
}
function initNewRoundState() {
	// Reset puzzle manager for new round
	console.log("Entering New Round State");
	if (puzzleManager) {
		puzzleManager.reset();
	}
	// After a short delay, transition to PLAYING state
	LK.setTimeout(function () {
		changeGameState(GAME_STATE.PLAYING);
	}, 1000);
}
function handleNewRoundLoop() {
	// Any pre-game animations can go here
}
function cleanNewRoundState() {
	// Clean up any new round state
}
function initPlayingState() {
	// Start the gameplay
	console.log("Entering Playing State");
	isPlaying = true;
}
function handlePlayingLoop() {
	// Update game logic
	if (puzzleManager) {
		puzzleManager.update();
		// Check if level is complete
		if (puzzleManager.isComplete) {
			changeGameState(GAME_STATE.SCORE);
		}
	}
}
function cleanPlayingState() {
	isPlaying = false;
}
function initScoreState() {
	// Show score screen
	console.log("Entering Score State");
	levelText.visible = true;
	levelText.text = "Level Complete!\nTap to continue";
}
function handleScoreLoop() {
	// Update any score animations
	if (puzzleManager) {
		puzzleManager.update();
	}
}
function cleanScoreState() {
	levelText.visible = false;
}
function changeGameState(newState) {
	// Clean up current state
	console.log("Changing state from", currentState, "to", newState);
	switch (currentState) {
		case GAME_STATE.MENU:
			cleanMenuState();
			break;
		case GAME_STATE.NEW_ROUND:
			cleanNewRoundState();
			break;
		case GAME_STATE.PLAYING:
			cleanPlayingState();
			break;
		case GAME_STATE.SCORE:
			cleanScoreState();
			break;
	}
	// Initialize new state
	currentState = newState;
	switch (newState) {
		case GAME_STATE.MENU:
			initMenuState();
			break;
		case GAME_STATE.NEW_ROUND:
			initNewRoundState();
			break;
		case GAME_STATE.PLAYING:
			initPlayingState();
			break;
		case GAME_STATE.SCORE:
			initScoreState();
			break;
	}
}
/**** 
* Event Handlers
****/ 
game.down = function (x, y, obj) {
	switch (currentState) {
		case GAME_STATE.MENU:
			changeGameState(GAME_STATE.NEW_ROUND);
			break;
		case GAME_STATE.PLAYING:
			startX = x;
			startY = y;
			isMouseDown = true;
			if (puzzleManager) {
				puzzleManager.selectTile(x, y);
			}
			break;
		case GAME_STATE.SCORE:
			changeGameState(GAME_STATE.MENU);
			break;
	}
};
game.move = function (x, y, obj) {
	if (currentState !== GAME_STATE.PLAYING || !isMouseDown || !puzzleManager || !puzzleManager.selectedTile) {
		return;
	}
	var deltaX = x - startX;
	var deltaY = y - startY;
	// Only move if drag distance exceeds threshold
	if (Math.abs(deltaX) > dragThreshold || Math.abs(deltaY) > dragThreshold) {
		var direction = null;
		if (Math.abs(deltaX) > Math.abs(deltaY)) {
			direction = deltaX > 0 ? 'right' : 'left';
		} else {
			direction = deltaY > 0 ? 'down' : 'up';
		}
		puzzleManager.moveTile(direction);
		isMouseDown = false; // Reset after move
	}
};
game.up = function (x, y, obj) {
	isMouseDown = false;
	if (currentState === GAME_STATE.PLAYING && puzzleManager) {
		puzzleManager.selectedTile = null;
	}
};
/**** 
* Main Update Loop
****/ 
function update() {
	// Handle state-specific updates
	switch (currentState) {
		case GAME_STATE.MENU:
			handleMenuLoop();
			break;
		case GAME_STATE.NEW_ROUND:
			handleNewRoundLoop();
			break;
		case GAME_STATE.PLAYING:
			handlePlayingLoop();
			break;
		case GAME_STATE.SCORE:
			handleScoreLoop();
			break;
	}
	// Update water drops
	for (var i = waterDrops.length - 1; i >= 0; i--) {
		if (waterDrops[i].visible) {
			waterDrops[i].update();
		}
	}
}
// Start the game
initializeGame();
:quality(85)/https://cdn.frvr.ai/675ee824eb1e8cb9a4112d39.png%3F3) 
 :quality(85)/https://cdn.frvr.ai/675efc2dc09b2ac5a2d5e69c.png%3F3) 
 :quality(85)/https://cdn.frvr.ai/675f0079c09b2ac5a2d5e6b6.png%3F3) 
 :quality(85)/https://cdn.frvr.ai/67608dd1dd0ea71dc49cb892.png%3F3) 
 :quality(85)/https://cdn.frvr.ai/676091b3dd0ea71dc49cb8d6.png%3F3) 
 :quality(85)/https://cdn.frvr.ai/67609314dd0ea71dc49cb8dd.png%3F3) 
 :quality(85)/https://cdn.frvr.ai/67609417dd0ea71dc49cb8e6.png%3F3) 
 :quality(85)/https://cdn.frvr.ai/67609c5bdd0ea71dc49cb922.png%3F3) 
 :quality(85)/https://cdn.frvr.ai/6763c93400d0b55d46b5c989.png%3F3) 
 straigth zenith view square light wooden pallet. Single Game Texture. In-Game asset. 2d. Blank background. High contrast. No shadows.
:quality(85)/https://cdn.frvr.ai/6763cda800d0b55d46b5c99a.png%3F3) 
 straigth zenith view square wooden pallet with big screws in each corner Single Game Texture. In-Game asset. 2d. Blank background. High contrast. No shadows.
:quality(85)/https://cdn.frvr.ai/6771626fb7d7d61ce947a750.png%3F3) 
 :quality(85)/https://cdn.frvr.ai/67716e32b7d7d61ce947a785.png%3F3) 
 :quality(85)/https://cdn.frvr.ai/6771b052f22179f74e2f8688.png%3F3) 
 :quality(85)/https://cdn.frvr.ai/6771b2bbf22179f74e2f86bd.png%3F3) 
 :quality(85)/https://cdn.frvr.ai/6775704d09f127fede9ecc8c.png%3F3) 
 :quality(85)/https://cdn.frvr.ai/677572d509f127fede9eccc2.png%3F3) 
 simple yellow rating star. Modern video game style
:quality(85)/https://cdn.frvr.ai/6775b1194092767f3c012b3a.png%3F3) 
 :quality(85)/https://cdn.frvr.ai/677667743ed42f57c4b74968.png%3F3) 
 :quality(85)/https://cdn.frvr.ai/677668033ed42f57c4b74970.png%3F3) 
 :quality(85)/https://cdn.frvr.ai/677668423ed42f57c4b74975.png%3F3) 
 :quality(85)/https://cdn.frvr.ai/677668c13ed42f57c4b7497c.png%3F3) 
 :quality(85)/https://cdn.frvr.ai/677803e49a90e8c7f345394a.png%3F3) 
 :quality(85)/https://cdn.frvr.ai/6784033d5446b29dfd6758af.png%3F3) 
 :quality(85)/https://cdn.frvr.ai/6784080d5446b29dfd67594b.png%3F3) 
 tileSlide
Sound effect
levelWon
Sound effect
tileBlocked
Sound effect
fountain
Sound effect
waterInPipe
Sound effect
bgMusic
Music
logoBounce
Sound effect
levelStart
Sound effect
bgMusic2
Music
flowerPop
Sound effect
roundResult
Sound effect
gameWon
Sound effect
resetSound
Sound effect
birds
Sound effect
birds2
Sound effect
birds3
Sound effect