User prompt
I fixed the checkWinCondition and the sub functions it uses. Now level win is detected properly from start to end. Analyze then Adapt the startWaterFlow and sub functions accordingly so that the flow works from start to end.
User prompt
Please fix the bug: 'Uncaught ReferenceError: currentLevel is not defined' in or related to this line: 'levelText.setText('Level: ' + currentLevel + ' Solved!');' Line Number: 1135
Code edit (3 edits merged)
Please save this source code
User prompt
Add detailled log in function canAcceptFlowFromDirection(tile, incomingDirection)
Code edit (16 edits merged)
Please save this source code
User prompt
add detailed logs (using log() ) to getNextPositions function
Code edit (1 edits merged)
Please save this source code
User prompt
Please fix the bug: 'Uncaught ReferenceError: x is not defined' in or related to this line: 'self.x = x * tileSize + gridBoard.x - gridBoard.width / 2 + tileSize / 2 + boardOffsetX;' Line Number: 510
Code edit (8 edits merged)
Please save this source code
User prompt
Please fix the bug: 'Uncaught TypeError: Cannot read properties of undefined (reading 'undefined')' in or related to this line: 'var currentTile = self.grid[y][x];' Line Number: 1511
User prompt
Please fix the bug: 'Uncaught TypeError: Cannot read properties of undefined (reading 'undefined')' in or related to this line: 'var currentTile = self.grid[y][x];' Line Number: 1508
User prompt
Please fix the bug: 'Uncaught TypeError: Cannot read properties of undefined (reading 'undefined')' in or related to this line: 'var currentTile = self.grid[y][x];' Line Number: 1505
User prompt
Please fix the bug: 'Uncaught TypeError: Cannot read properties of undefined (reading 'undefined')' in or related to this line: 'var currentTile = self.grid[y][x];' Line Number: 1502
User prompt
Please fix the bug: 'Uncaught ReferenceError: startTile is not defined' in or related to this line: 'var toCheck = [[startTile.gridX, startTile.gridY, getFlowDirection(startTile)]];' Line Number: 1439
User prompt
Please fix the bug: 'Uncaught TypeError: Set is not a constructor' in or related to this line: 'var visited = new Set();' Line Number: 1438
Code edit (1 edits merged)
Please save this source code
User prompt
Please fix the bug: 'tween is not defined' in or related to this line: 'tween(logo, {' Line Number: 1843 ↪💡 Consider importing and using the following plugins: @upit/tween.v1
User prompt
Please fix the bug: 'Unable to load plugin: @upit/tween.v1' in or related to this line: 'var tween = LK.import("@upit/tween.v1");' Line Number: 34
User prompt
Please fix the bug: 'tween is not defined' in or related to this line: 'tween(logo, {' Line Number: 1843 ↪💡 Consider importing and using the following plugins: @upit/tween.v1
User prompt
Please fix the bug: 'Unable to load plugin: @upit/tween.v1' in or related to this line: 'var tween = LK.import("@upit/tween.v1");' Line Number: 34
Code edit (10 edits merged)
Please save this source code
User prompt
Please fix the bug: 'Cannot read properties of undefined (reading 'parse')' in or related to this line: 'validConfig = JSON.parse(JSON.stringify(currentConfig));' Line Number: 1596
Code edit (7 edits merged)
Please save this source code
User prompt
Please fix the bug: 'Cannot read properties of undefined (reading 'stringify')' in or related to this line: 'return result;' Line Number: 1657
User prompt
Please fix the bug: 'Cannot read properties of undefined (reading 'stringify')' in or related to this line: 'console.log("Converted Level:", JSON.stringify(convertedLevel, null, 2));' Line Number: 2038
/****
* Plugins
****/
var tween = LK.import("@upit/tween.v1");
/****
* Classes
****/
var Tile = Container.expand(function () {
var self = Container.call(this);
self.pipeContainer = new Container();
// Properties
self.type = 'empty';
self.baseTint = 0xaaaaaa;
self.baseTintLight = 0xaaaaaa;
self.maxWaterSize = 260;
self.flowSpeed = 12;
self.startFlowTicks = 0;
self.flow = false;
self.connections = [];
self.position = {
x: 0,
y: 0
};
self.rotation = 0;
self.normalizedRotation = 0;
// Methods
self.createStartTile = function () {
self.pipeContainer.attachAsset('startPipeAsset', {
anchorX: 0.5,
anchorY: 0.5,
x: 20,
y: 40,
tint: self.baseTint
});
self.valve = self.pipeContainer.attachAsset('vane', {
anchorX: 0.5,
anchorY: 0.5,
x: 20,
y: -8,
tint: self.baseTint
});
self.water = self.pipeContainer.attachAsset('waterV', {
anchorX: 0.5,
anchorY: 0,
x: -0,
y: -120,
height: 0,
visible: false,
dir: ''
});
};
self.createEndTile = function () {
self.pipeContainer.attachAsset('endPipeAsset', {
anchorX: 0.5,
anchorY: 0.5,
x: 0,
y: 55,
tint: self.baseTint
});
self.water = self.pipeContainer.attachAsset('waterV', {
anchorX: 0.5,
anchorY: 0,
x: -0,
y: -120,
height: 0,
visible: false,
dir: ''
});
self.fountain = self.pipeContainer.attachAsset('fontain', {
anchorX: 0.5,
anchorY: 0.5,
x: 0,
y: 0,
width: 0,
height: 0,
visible: false
});
};
self.createCrossPipe = function () {
self.pipeContainer.attachAsset('straightPipeHAsset', {
anchorX: 0.5,
anchorY: 0.5,
y: -40,
tint: self.baseTint
});
self.pipeContainer.attachAsset('straightPipeHAsset', {
anchorX: 0.5,
anchorY: 0.5,
scaleY: -1,
y: 30,
tint: self.baseTint
});
self.pipeContainer.attachAsset('straightPipeVAsset', {
anchorX: 0.5,
anchorY: 0.5,
x: -30,
tint: self.baseTint
});
self.pipeContainer.attachAsset('straightPipeVAsset', {
anchorX: 0.5,
anchorY: 0.5,
scaleX: -1,
x: 30,
tint: self.baseTint
});
self.water = self.pipeContainer.attachAsset('waterV', {
anchorX: 0.5,
anchorY: 0,
x: -0,
y: -120,
height: 0,
visible: false,
dir: ''
});
};
self.createStraightPipeH = function () {
self.pipeContainer.attachAsset('straightPipeHAsset', {
anchorX: 0.5,
anchorY: 0.5,
y: -40,
tint: self.baseTint
});
self.pipeContainer.attachAsset('straightPipeHAsset', {
anchorX: 0.5,
anchorY: 0.5,
scaleY: -1,
y: 30,
tint: self.baseTint
});
self.water = self.pipeContainer.attachAsset('waterH', {
anchorX: 0,
anchorY: 0.5,
x: -130,
y: -5,
width: 0,
visible: false,
dir: 'lr'
});
};
self.createStraightPipeV = function () {
self.pipeContainer.attachAsset('straightPipeVAsset', {
anchorX: 0.5,
anchorY: 0.5,
x: -30,
tint: self.baseTint
});
self.pipeContainer.attachAsset('straightPipeVAsset', {
anchorX: 0.5,
anchorY: 0.5,
scaleX: -1,
x: 30,
tint: self.baseTint
});
self.water = self.pipeContainer.attachAsset('waterV', {
anchorX: 0.5,
anchorY: 0,
x: -0,
y: -120,
height: 0,
visible: false,
dir: 'tb'
});
};
self.createCornerPipe = function () {
self.pipeContainer.attachAsset('cornerPipeAsset', {
anchorX: 0.5,
anchorY: 0.5,
x: -60,
y: -60,
tint: self.baseTintLight
});
self.waterCorner = self.pipeContainer.attachAsset('waterCorner', {
anchorX: 1,
anchorY: 1,
width: 108,
height: 108,
x: -65,
y: -65,
rotation: -Math.PI / 2,
visible: false,
dir: ''
});
self.waterV = self.pipeContainer.attachAsset('waterV', {
anchorX: 0.5,
anchorY: 0,
width: 110,
x: -120,
y: -5,
rotation: -Math.PI / 2,
height: 0,
visible: false,
dir: ''
});
self.waterH = self.pipeContainer.attachAsset('waterH', {
anchorX: 0,
anchorY: 0.5,
x: -5,
y: -50,
width: 0,
height: 112,
rotation: -Math.PI / 2,
visible: false,
dir: ''
});
self.waterCornerCover = self.pipeContainer.attachAsset('waterCorner', {
anchorX: 1,
anchorY: 1,
width: 108,
height: 108,
x: -65,
y: -65,
rotation: -Math.PI,
visible: false,
alpha: 0,
dir: ''
});
self.pipeContainer.attachAsset('cornerPipeSection', {
anchorX: 0.5,
anchorY: 0.5,
width: 148,
height: 148,
x: -0,
y: -0,
tint: self.baseTintLight
});
self.pipeContainer.attachAsset('pipeRing', {
anchorX: 0.5,
anchorY: 0.5,
width: 144,
height: 30,
x: 0,
y: -80,
rotation: Math.PI * 0,
tint: self.baseTintLight
});
self.pipeContainer.attachAsset('pipeRing', {
anchorX: 0.5,
anchorY: 0.5,
width: 144,
height: 30,
x: -80,
y: -5,
rotation: Math.PI * 0.5,
tint: self.baseTintLight
});
};
self.getCornerPipeConfig = function () {
// Define the water flow configuration based on normalized rotation
var configs = _defineProperty(_defineProperty(_defineProperty(_defineProperty({}, Math.PI / 2, {
// right
primaryWater: 'waterV',
secondaryWater: 'waterH',
primaryGrowth: {
property: 'height',
direction: 1,
position: {
x: -120,
y: -5
},
rotation: -Math.PI / 2
},
secondaryGrowth: {
property: 'width',
direction: 1,
position: {
x: -5,
y: -50
},
rotation: -Math.PI / 2
},
cornerPosition: {
x: -65,
y: -65
}
}), 0, {
// up
primaryWater: 'waterH',
secondaryWater: 'waterV',
primaryGrowth: {
property: 'width',
direction: -1,
position: {
x: -5,
y: -50
},
rotation: -Math.PI / 2
},
secondaryGrowth: {
property: 'height',
direction: 1,
position: {
x: -120,
y: -5
},
rotation: -Math.PI / 2
},
cornerPosition: {
x: -65,
y: -65
}
}), Math.PI, {
// down
primaryWater: 'waterH',
secondaryWater: 'waterV',
primaryGrowth: {
property: 'width',
direction: 1,
position: {
x: -5,
y: -50
},
rotation: -Math.PI / 2
},
secondaryGrowth: {
property: 'height',
direction: -1,
position: {
x: -120,
y: -5
},
rotation: -Math.PI / 2
},
cornerPosition: {
x: -65,
y: -65
}
}), Math.PI * 1.5, {
// left
primaryWater: 'waterV',
secondaryWater: 'waterH',
primaryGrowth: {
property: 'height',
direction: -1,
position: {
x: -120,
y: -5
},
rotation: -Math.PI / 2
},
secondaryGrowth: {
property: 'width',
direction: -1,
position: {
x: -5,
y: -50
},
rotation: -Math.PI / 2
},
cornerPosition: {
x: -65,
y: -65
}
});
return configs[self.normalizedRotation] || configs[0];
};
self.updateCornerPipeFirstPhase = function (progress, thirdSize) {
log("Progress in first third:", progress);
var config = self.getCornerPipeConfig();
var primary = self[config.primaryWater];
if (primary) {
primary.visible = true;
primary[config.primaryGrowth.property] = progress * config.primaryGrowth.direction;
primary.x = config.primaryGrowth.position.x;
primary.y = config.primaryGrowth.position.y;
primary.rotation = config.primaryGrowth.rotation;
if (config.primaryGrowth.direction < 0) {
primary['scale' + (config.primaryGrowth.property === 'width' ? 'X' : 'Y')] = -1;
}
log("Primary water set to:", primary[config.primaryGrowth.property]);
}
};
self.updateCornerPipeSecondPhase = function (progress, thirdSize) {
log("Progress in second third:", progress);
var config = self.getCornerPipeConfig();
var primary = self[config.primaryWater];
// Keep primary at max
if (primary) {
primary[config.primaryGrowth.property] = thirdSize * config.primaryGrowth.direction;
log("Primary water at max:", primary[config.primaryGrowth.property]);
}
// Update corner water
if (self.waterCorner) {
self.waterCorner.visible = true;
self.waterCorner.x = config.cornerPosition.x;
self.waterCorner.y = config.cornerPosition.y;
self.waterCorner.alpha = Math.min(Math.max(0, ((progress - thirdSize) / thirdSize - 0.5) * 2, 0), 1);
var rotationProgress = (progress - thirdSize) / thirdSize;
self.waterCorner.rotation = -Math.PI / 2 - rotationProgress * Math.PI / 2;
log("WaterCorner visible with alpha:", self.waterCorner.alpha, "and rotation:", self.waterCorner.rotation);
}
};
self.updateCornerPipeThirdPhase = function (progress, thirdSize, sidesSize) {
log("Progress in final third:", progress);
var config = self.getCornerPipeConfig();
var primary = self[config.primaryWater];
var secondary = self[config.secondaryWater];
// Keep primary at max
if (primary) {
primary[config.primaryGrowth.property] = thirdSize * config.primaryGrowth.direction;
log("Primary water at max:", primary[config.primaryGrowth.property]);
}
// Set corner to final state
if (self.waterCorner) {
self.waterCorner.visible = true;
self.waterCorner.x = config.cornerPosition.x;
self.waterCorner.y = config.cornerPosition.y;
self.waterCorner.alpha = 1;
self.waterCorner.rotation = -Math.PI;
log("WaterCorner fully visible with rotation:", self.waterCorner.rotation);
}
// Grow secondary pipe
if (secondary) {
secondary.visible = true;
secondary[config.secondaryGrowth.property] = Math.min(progress - thirdSize * 2, sidesSize) * config.secondaryGrowth.direction;
secondary.x = config.secondaryGrowth.position.x;
secondary.y = config.secondaryGrowth.position.y;
if (config.secondaryGrowth.direction < 0) {
secondary['scale' + (config.secondaryGrowth.property === 'width' ? 'X' : 'Y')] = -1;
}
log("Secondary water visible with size:", secondary[config.secondaryGrowth.property]);
}
};
self.updateEndTile = function () {
if (self.fountain) {
var sizeValue = (LK.ticks - self.startFlowTicks) * self.flowSpeed;
if (sizeValue < self.maxWaterSize) {
self.fountain.width = sizeValue;
self.fountain.height = sizeValue;
if (!self.fountain.visible) {
self.fountain.visible = true;
LK.getSound('fountain').play();
}
} 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);
animateSoil();
}
}
}
};
self.updateRegularPipe = function () {
if (self.water) {
var heightValue = (LK.ticks - self.startFlowTicks) * self.flowSpeed;
if (heightValue < self.maxWaterSize) {
self.water.visible = true;
if (self.water.dir === 'lr') {
self.water.width = heightValue;
self.water.x = -130;
self.water.scaleX = 1;
} else if (self.water.dir === 'rl') {
self.water.width = heightValue;
self.water.x = 130;
self.water.scaleX = -1;
} else if (self.water.dir === 'tb') {
self.water.height = heightValue;
self.water.y = -130;
self.water.scaleY = 1;
} else if (self.water.dir === 'bt') {
self.water.height = heightValue;
self.water.y = 130;
self.water.scaleY = -1;
} else {
self.water.height = heightValue;
}
} else {
self.flow = false;
}
}
};
self.updateEndTileAnimation = function () {
if (self.type === 'end' && self.fountain && self.fountain.visible) {
self.fountain.rotation += 0.1;
var sizeVariation = 30 * Math.sin(LK.ticks * 0.1);
self.fountain.width = 250 + sizeVariation;
self.fountain.height = 250 + sizeVariation;
}
};
self.updateCornerPipe = function () {
var progress = (LK.ticks - self.startFlowTicks) * self.flowSpeed;
var thirdSize = self.maxWaterSize / 3 - 10;
var sidesSize = self.maxWaterSize / 3;
if (progress < thirdSize) {
self.updateCornerPipeFirstPhase(progress, thirdSize);
} else if (progress < thirdSize * 2) {
self.updateCornerPipeSecondPhase(progress, thirdSize);
} else {
self.updateCornerPipeThirdPhase(progress, thirdSize, sidesSize);
}
if (progress >= self.maxWaterSize) {
self.flow = false;
}
};
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;
}
}
switch (self.type) {
case 'start':
self.updateStartTile();
break;
case 'cornerPipe':
self.updateCornerPipe();
break;
case 'end':
self.updateEndTile();
break;
default:
self.updateRegularPipe();
break;
}
}
self.updateEndTileAnimation();
};
self.setType = function (type, x, y) {
self.type = type;
var baseTileAsset = type == 'start' || type == 'end' || puzzleManager && puzzleManager.levelConfigs && puzzleManager.levelConfigs[puzzleManager.currentLevel] && puzzleManager.levelConfigs[puzzleManager.currentLevel].fixedTiles && 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.addChild(self.pipeContainer);
self.width = tileSize;
self.height = tileSize;
// Create tile based on type
switch (type) {
case 'start':
self.createStartTile();
break;
case 'end':
self.createEndTile();
break;
case 'crossPipe':
self.createCrossPipe();
break;
case 'straightPipeH':
self.createStraightPipeH();
break;
case 'straightPipeV':
self.createStraightPipeV();
break;
case 'cornerPipe':
self.createCornerPipe();
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') {
switch (self.type) {
case 'cornerPipe':
// Convert radians to our direction system
// 0 = up
// π/2 = right
// π = down
// 3Ï€/2 = left
var angle = rotation % (2 * Math.PI);
if (angle < 0) {
angle += 2 * Math.PI;
}
if (angle < Math.PI / 4 || angle > 7 * Math.PI / 4) {
log("Corner normalize ", angle, " => up");
return 'left'; //'up';
}
if (angle < 3 * Math.PI / 4) {
log("Corner normalize ", angle, " => right");
return 'right';
}
if (angle < 5 * Math.PI / 4) {
log("Corner normalize ", angle, " => down");
return 'down';
}
log("Corner normalize ", angle, " => left");
return 'up'; //'left';
break;
default:
// Convert radians to our direction system
// 0 = up
// π/2 = right
// π = down
// 3Ï€/2 = left
var angle = rotation % (2 * Math.PI);
if (angle < 0) {
angle += 2 * Math.PI;
}
if (angle < Math.PI / 4 || angle > 7 * Math.PI / 4) {
return 'down'; //'up';
}
if (angle < 3 * Math.PI / 4) {
return 'right';
}
if (angle < 5 * Math.PI / 4) {
return 'up'; // 'down';
}
return 'left';
break;
}
}
return rotation || 'down';
};
self.setRotation = function (direction) {
switch (self.type) {
case 'cornerPipe':
switch (direction) {
case 'left':
self.pipeContainer.rotation = 0;
self.normalizedRotation = 0;
break;
case 'right':
self.pipeContainer.rotation = Math.PI * 0.5;
self.normalizedRotation = Math.PI * 0.5;
break;
case 'up':
self.pipeContainer.rotation = Math.PI;
self.normalizedRotation = Math.PI;
break;
case 'down':
self.pipeContainer.rotation = Math.PI * 1.5;
self.normalizedRotation = Math.PI * 1.5;
break;
}
log("Corner Set rot ", direction, " => ", self.pipeContainer.rotation);
break;
default:
switch (direction) {
case 'left':
self.pipeContainer.rotation = -Math.PI * 1.5;
break;
case 'right':
self.pipeContainer.rotation = -Math.PI * 0.5;
break;
case 'up':
self.pipeContainer.rotation = Math.PI;
break;
case 'down':
self.pipeContainer.rotation = 0;
break;
}
break;
}
log('Tile position:', self.x, self.y, 'Tile rotation:', self.pipeContainer.rotation);
};
self.getNextPositions = function (x, y, type, normalizedRotation) {
var nextPositions = [];
switch (type) {
case 'start':
switch (normalizedRotation) {
case 'down':
nextPositions.push([x, y + 1]); // Down
break;
case 'up':
nextPositions.push([x, y - 1]); // Up
break;
case 'left':
nextPositions.push([x - 1, y]); // Left
break;
case 'right':
nextPositions.push([x + 1, y]); // Right
break;
}
break;
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 (normalizedRotation) {
case 'up':
nextPositions.push([x - 1, y], [x, y + 1]); // 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;
}
return nextPositions;
};
self.updateStartTile = function () {
var rotationValue = (LK.ticks - self.startFlowTicks) * 0.1;
if (self.valve) {
self.valve.rotation = rotationValue;
}
if (rotationValue >= Math.PI * 3) {
self.flow = false;
}
};
self.updateCornerPipeFirstPhase = function (progress, thirdSize) {
log("Progress in first third:", progress);
var config = self.getCornerPipeConfig();
var primary = self[config.primaryWater];
if (primary) {
primary[config.primaryGrowth.property] = progress * config.primaryGrowth.direction;
primary.x = config.primaryGrowth.position.x;
primary.y = config.primaryGrowth.position.y;
if (config.primaryGrowth.direction < 0) {
primary['scale' + (config.primaryGrowth.property === 'width' ? 'X' : 'Y')] = -1;
}
log("Primary water set to:", primary[config.primaryGrowth.property]);
}
};
self.updateCornerPipeSecondPhase = function (progress, thirdSize) {
log("Progress in second third:", progress);
var config = self.getCornerPipeConfig();
var primary = self[config.primaryWater];
// Keep primary at max
if (primary) {
primary[config.primaryGrowth.property] = thirdSize * config.primaryGrowth.direction;
log("Primary water at max:", primary[config.primaryGrowth.property]);
}
// Update corner water
if (self.waterCorner) {
self.waterCorner.visible = true;
self.waterCorner.alpha = Math.min(Math.max(0, ((progress - thirdSize) / thirdSize - 0.5) * 2, 0), 1);
var rotationProgress = (progress - thirdSize) / thirdSize;
self.waterCorner.rotation = -Math.PI / 2 - rotationProgress * Math.PI / 2;
log("WaterCorner visible with alpha:", self.waterCorner.alpha, "and rotation:", self.waterCorner.rotation);
}
};
self.updateCornerPipeThirdPhase = function (progress, thirdSize, sidesSize) {
log("Progress in final third:", progress);
var config = self.getCornerPipeConfig();
var primary = self[config.primaryWater];
var secondary = self[config.secondaryWater];
// Keep primary at max
if (primary) {
primary[config.primaryGrowth.property] = thirdSize * config.primaryGrowth.direction;
log("Primary water at max:", primary[config.primaryGrowth.property]);
}
// Set corner to final state
if (self.waterCorner) {
self.waterCorner.visible = true;
self.waterCorner.alpha = 1;
self.waterCorner.rotation = -Math.PI;
log("WaterCorner fully visible with rotation:", self.waterCorner.rotation);
}
// Grow secondary pipe
if (secondary) {
secondary.visible = true;
secondary[config.secondaryGrowth.property] = Math.min(progress - thirdSize * 2, sidesSize) * config.secondaryGrowth.direction;
secondary.x = config.secondaryGrowth.position.x;
secondary.y = config.secondaryGrowth.position.y;
if (config.secondaryGrowth.direction < 0) {
secondary['scale' + (config.secondaryGrowth.property === 'width' ? 'X' : 'Y')] = -1;
}
log("Secondary water visible with size:", secondary[config.secondaryGrowth.property]);
}
};
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
****/
/****
* Global level configurations
****/
var game = new LK.Game({
backgroundColor: 0x000000
});
/****
* Game Code
****/
/****
* Global level configurations
****/
function _slicedToArray2(r, e) {
return _arrayWithHoles2(r) || _iterableToArrayLimit2(r, e) || _unsupportedIterableToArray2(r, e) || _nonIterableRest2();
}
function _nonIterableRest2() {
throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _unsupportedIterableToArray2(r, a) {
if (r) {
if ("string" == typeof r) {
return _arrayLikeToArray2(r, a);
}
var t = {}.toString.call(r).slice(8, -1);
return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray2(r, a) : void 0;
}
}
function _arrayLikeToArray2(r, a) {
(null == a || a > r.length) && (a = r.length);
for (var e = 0, n = Array(a); e < a; e++) {
n[e] = r[e];
}
return n;
}
function _iterableToArrayLimit2(r, l) {
var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
if (null != t) {
var e,
n,
i,
u,
a = [],
f = !0,
o = !1;
try {
if (i = (t = t.call(r)).next, 0 === l) {
if (Object(t) !== t) {
return;
}
f = !1;
} else {
for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0) {
;
}
}
} catch (r) {
o = !0, n = r;
} finally {
try {
if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) {
return;
}
} finally {
if (o) {
throw n;
}
}
}
return a;
}
}
function _arrayWithHoles2(r) {
if (Array.isArray(r)) {
return r;
}
}
var levelConfigs = {
1: {
tiles: [['start', 'straightPipeV', 'straightPipeV', 'cornerPipe'], [null, null, null, 'straightPipeH'], [null, null, 'straightPipeH', null], [null, null, null, 'end']],
rotations: {
'0,3': 'right',
'3,3': 'left'
},
fixedTiles: ['0,0', '0,1', '0,2', '0,3', '1,3', '3,3']
},
2: {
tiles: [[null, 'straightPipeH', 'end', null], [null, 'cornerPipe', 'straightPipeH', null], [null, null, null, null], ['start', 'straightPipeV', null, null]],
rotations: {
'0,2': 'right',
'1,1': 'left'
},
fixedTiles: ['3,0', '3,1', '0,2', '1,2']
}
};
function _typeof(o) {
"@babel/helpers - typeof";
return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) {
return typeof o;
} : function (o) {
return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
}, _typeof(o);
}
function _defineProperty(e, r, t) {
return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
value: t,
enumerable: !0,
configurable: !0,
writable: !0
}) : e[r] = t, e;
}
function _toPropertyKey(t) {
var i = _toPrimitive(t, "string");
return "symbol" == _typeof(i) ? i : i + "";
}
function _toPrimitive(t, r) {
if ("object" != _typeof(t) || !t) {
return t;
}
var e = t[Symbol.toPrimitive];
if (void 0 !== e) {
var i = e.call(t, r || "default");
if ("object" != _typeof(i)) {
return i;
}
throw new TypeError("@@toPrimitive must return a primitive value.");
}
return ("string" === r ? String : Number)(t);
}
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 = levelConfigs;
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]);*/
var _pos$split$map = pos.split(',').map(Number),
x = _pos$split$map[0],
y = _pos$split$map[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] && self.grid[gridX][gridY] ? self.grid[gridX][gridY] : undefined;
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)) {
LK.getSound('tileBlocked').play(); // Play tileBlocked sound
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];
// Play tile slide sound
LK.getSound('tileSlide').play();
// 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();
LK.getSound('levelWon').play(); // Play levelWon sound
levelText.setText('Level: ' + self.currentLevel + ' Solved!');
isPlaying = false;
}
};
self.startWaterFlow = function () {
log("Starting water flow...");
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
var startDirection = startTile.normalizeRotation(startTile.pipeContainer.rotation);
self.flowThroughPipe(startX, startY, [], startDirection);
}
};
self.flowThroughPipe = function (x, y, visited, fromDir) {
log("Entering flowThroughPipe at position:", x, y, "Visited:", visited, "From:", fromDir);
if (x < 0 || x >= self.gridSize || y < 0 || y >= self.gridSize) {
log("Invalid position.");
return;
}
var key = x + ',' + y;
if (visited.includes(key)) {
log("Already visited...");
return;
}
visited.push(key);
var tile = self.grid[x][y];
log("Will pass :", tile ? tile.type : "none", " from ", fromDir);
if (!tile || tile.type === 'empty') {
return;
}
// Start flow animation for this tile
tile.flow = true;
if (tile.water) {
tile.water.visible = true;
// Set water direction based on pipe type and incoming direction
if (tile.type === 'straightPipeH') {
if (fromDir === 'right') {
tile.water.dir = 'rl'; // right to left
} else {
tile.water.dir = 'lr'; // left to right
}
}
if (tile.type === 'straightPipeV') {
if (fromDir === 'down') {
tile.water.dir = 'bt'; // top to bottom
} else {
tile.water.dir = 'tb'; // bottom to top
}
}
}
if (tile.waterV) {
tile.waterV.visible = true;
}
if (tile.waterH) {
tile.waterH.visible = true;
if (fromDir === 'right') {
tile.waterH.scaleX = -1; // Flow right to left
} else {
tile.waterH.scaleX = 1; // Flow left to right
}
}
if (tile.type === 'end') {
createWaterDrops(tile.x, tile.y + 100, game);
return;
}
var normalizedRotation = tile.normalizeRotation(tile.pipeContainer.rotation);
var nextPositions = tile.getNextPositions(x, y, tile.type, normalizedRotation);
// Wait for flow animation to complete before moving to next tiles
LK.setTimeout(function () {
for (var i = 0; i < nextPositions.length; i++) {
var nextX = nextPositions[i][0];
var nextY = nextPositions[i][1];
// Determine flow direction for next tile
var nextDir;
if (nextX > x) {
nextDir = 'left';
} // Coming from left
else if (nextX < x) {
nextDir = 'right';
} // Coming from right
else if (nextY > y) {
nextDir = 'up';
} // Coming from up
else {
nextDir = 'down';
} // Coming from down
self.flowThroughPipe(nextX, nextY, visited, nextDir);
}
}, 300);
};
self.reset = function () {
self.selectedTile = null;
if (self.isComplete) {
self.currentLevel++;
} else {
self.currentLevel = self.currentLevel || 1;
}
self.isComplete = false;
self.waterFlowing = false;
// Remove previous level tiles
self.grid.forEach(function (row) {
row.forEach(function (tile) {
if (tile) {
tile.destroy();
}
});
});
self.initPuzzle();
};
self.checkWinCondition = function () {
// Find start position
log("=== Starting Win Condition Check ===");
log("Grid state:");
for (var i = 0; i < self.gridSize; i++) {
var row = [];
for (var j = 0; j < self.gridSize; j++) {
var tile = self.grid[i][j];
row.push(tile ? "".concat(tile.type, "(").concat(tile.rotation, ")") : 'empty');
}
log("Row", i + ":", row.join(' | '));
}
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 tile found at:", startX, startY);
break;
}
}
if (startX !== -1) {
break;
}
}
// Use array to track visited positions
var visited = [];
log("Starting path check from:", startX, startY);
// Start flowing down from start
var result = self.canReachEnd(startX, startY, visited);
log("Path check complete. Result:", result);
log("Visited positions:", visited);
log("=== Win Condition Check Complete ===");
return result;
};
self.canReachEnd = function (x, y, visited) {
log("Checking position:", x, y);
if (x < 0 || x >= self.gridSize || y < 0 || y >= self.gridSize) {
log("Position out of bounds");
return false;
}
var key = x + ',' + y;
if (visited.includes(key)) {
log("Position already visited:", key);
return false;
}
visited.push(key);
var tile = self.grid[x][y];
if (!tile || tile.type === 'empty') {
log("No tile or empty tile at position:", x, y);
return false;
}
if (tile.type === 'end') {
log("Found end tile!");
return true;
}
var normalizedRotation = tile.normalizeRotation(tile.pipeContainer.rotation);
log("Checking tile:", tile.type, "with normalized rotation:", normalizedRotation, "at position:", x, y);
var nextPositions = tile.getNextPositions(x, y, tile.type, normalizedRotation);
log("Next positions to check:", nextPositions);
for (var i = 0; i < nextPositions.length; i++) {
var nextPos = nextPositions[i];
log("Trying next position:", nextPos);
if (self.canReachEnd(nextPos[0], nextPos[1], visited)) {
return true;
}
}
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 = 100;
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 backgroundLayer;
var middleLayer;
var gridBoard;
var gridBoardSoil;
var growGrass;
var isMouseDown = false;
var startX = 0;
var startY = 0;
var selectedTile = null;
var dragThreshold = 20;
var levelText;
var waterDrops = [];
var waterDropInterval;
var logo;
var puzzleManager;
// Initialize the game
initializeGame();
/****
* Level Generator and Converter Code
****/
// Convert ASCII art to level configuration with automatic rotations
var stringToLevel = function stringToLevel(levelString) {
var lines = levelString.trim().split('\n').map(function (line) {
return line.trim();
});
var gridSize = 4;
var tiles = [];
var rotations = {};
var fixedTiles = [];
var startPos = null;
var endPos = null;
var cornerPipes = [];
// Initialize tiles array
for (var i = 0; i < gridSize; i++) {
tiles[i] = [];
for (var j = 0; j < gridSize; j++) {
tiles[i][j] = null;
}
}
// First pass: Place all tiles except rotations
for (var y = 0; y < lines.length && y < gridSize; y++) {
var chars = lines[y].split('');
for (var x = 0; x < chars.length && x < gridSize; x++) {
var _char = chars[x];
switch (_char) {
case 'S':
tiles[y][x] = 'start';
fixedTiles.push(y + ',' + x);
startPos = [y, x];
break;
case 'E':
tiles[y][x] = 'end';
fixedTiles.push(y + ',' + x);
endPos = [y, x];
break;
case '|':
tiles[y][x] = 'straightPipeV';
break;
case '-':
tiles[y][x] = 'straightPipeH';
break;
case 'C':
tiles[y][x] = 'cornerPipe';
cornerPipes.push([y, x]);
break;
case 'F':
// Fixed straight pipe vertical
tiles[y][x] = 'straightPipeV';
fixedTiles.push(y + ',' + x);
break;
case '=':
// Fixed straight pipe horizontal
tiles[y][x] = 'straightPipeH';
fixedTiles.push(y + ',' + x);
break;
case '.':
case ' ':
tiles[y][x] = null;
break;
}
}
}
// Helper function to check if a path exists from start to end
function isValidPath(config) {
var visited = [];
var startRotation = config.rotations[startPos[0] + ',' + startPos[1]] || 'down';
function canReachEnd(x, y, fromDir) {
if (x < 0 || x >= gridSize || y < 0 || y >= gridSize) {
return false;
}
var key = x + ',' + y;
if (visited.includes(key)) {
return false;
}
visited.push(key);
var tile = config.tiles[x][y];
if (!tile) {
return false;
}
if (tile === 'end') {
return true;
}
var rotation = config.rotations[key] || 'down';
var nextPositions = [];
switch (tile) {
case 'start':
switch (rotation) {
case 'down':
nextPositions.push([x, y + 1]);
break;
case 'up':
nextPositions.push([x, y - 1]);
break;
case 'left':
nextPositions.push([x - 1, y]);
break;
case 'right':
nextPositions.push([x + 1, y]);
break;
}
break;
case 'straightPipeV':
nextPositions.push([x, y - 1], [x, y + 1]);
break;
case 'straightPipeH':
nextPositions.push([x - 1, y], [x + 1, y]);
break;
case 'cornerPipe':
switch (rotation) {
case 'up':
nextPositions.push([x - 1, y], [x, y + 1]);
break;
case 'right':
nextPositions.push([x + 1, y], [x, y + 1]);
break;
case 'down':
nextPositions.push([x + 1, y], [x, y - 1]);
break;
case 'left':
nextPositions.push([x - 1, y], [x, y - 1]);
break;
}
break;
}
for (var i = 0; i < nextPositions.length; i++) {
if (canReachEnd(nextPositions[i][0], nextPositions[i][1])) {
return true;
}
}
return false;
}
return canReachEnd(startPos[0], startPos[1]);
}
// Try all possible rotations
var possibleRotations = ['up', 'right', 'down', 'left'];
var validConfig = null;
function tryRotations(currentConfig, index) {
if (index >= cornerPipes.length + 2) {
// +2 for start and end tiles
if (isValidPath(currentConfig)) {
validConfig = JSON.parse(JSON.stringify(currentConfig));
return true;
}
return false;
}
var pos;
var isStartOrEnd = index < 2;
if (isStartOrEnd) {
pos = index === 0 ? startPos : endPos;
} else {
pos = cornerPipes[index - 2];
}
for (var i = 0; i < possibleRotations.length; i++) {
var rotation = possibleRotations[i];
var key = pos[0] + ',' + pos[1];
currentConfig.rotations[key] = rotation;
if (tryRotations(currentConfig, index + 1)) {
return true;
}
}
return false;
}
var baseConfig = {
tiles: tiles,
rotations: {},
fixedTiles: fixedTiles
};
tryRotations(baseConfig, 0);
return validConfig || baseConfig;
};
// Convert level configuration to ASCII art
var levelToString = function levelToString(level) {
var result = '';
for (var y = 0; y < level.tiles.length; y++) {
for (var x = 0; x < level.tiles[y].length; x++) {
var tile = level.tiles[y][x];
var isFixed = level.fixedTiles.includes(y + ',' + x);
if (!tile) {
result += '.';
} else {
switch (tile) {
case 'start':
result += 'S';
break;
case 'end':
result += 'E';
break;
case 'straightPipeV':
result += isFixed ? 'F' : '|';
break;
case 'straightPipeH':
result += isFixed ? '=' : '-';
break;
case 'cornerPipe':
result += 'C';
break;
}
}
}
result += '\n';
}
return result;
};
// Generate next level using string-based representation
var generateNextLevel = function generateNextLevel(existingLevels) {
var lastLevel = existingLevels[existingLevels.length - 1];
var levelStr = levelToString(lastLevel);
// For now, just add some random pipes to empty spaces
var lines = levelStr.split('\n');
var emptySpaces = [];
// Find empty spaces
for (var y = 0; y < lines.length; y++) {
for (var x = 0; x < lines[y].length; x++) {
if (lines[y][x] === '.') {
emptySpaces.push([x, y]);
}
}
}
// Add 1-2 new pipes
var numNewPipes = Math.min(1 + Math.floor(Math.random() * 2), emptySpaces.length);
var pipeTypes = ['|', '-', 'C'];
for (var i = 0; i < numNewPipes; i++) {
var spaceIndex = Math.floor(Math.random() * emptySpaces.length);
var _emptySpaces$spaceInd = _slicedToArray2(emptySpaces[spaceIndex], 2),
x = _emptySpaces$spaceInd[0],
y = _emptySpaces$spaceInd[1];
emptySpaces.splice(spaceIndex, 1);
// Add new pipe
var newPipe = pipeTypes[Math.floor(Math.random() * pipeTypes.length)];
lines[y] = lines[y].substring(0, x) + newPipe + lines[y].substring(x + 1);
}
return stringToLevel(lines.join('\n'));
};
/****
* Helper Functions
****/
function createWaterDrops(x, y, game) {
for (var i = 0; i < 30; 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 = 250;
waterDrop.visible = true;
}
}
function animateSoil() {
log("Animate soil...");
gridBoardSoil.visible = true;
gridBoardSoil.alpha = 0;
var alphaIncrement = 0.05; // Adjust the increment for desired speed
// Animate all baseTile tiles' alpha from 1 to 0
puzzleManager.grid.forEach(function (row) {
row.forEach(function (tile) {
if (tile.baseTile) {
tile.baseTile.alpha = 1;
LK.setInterval(function () {
if (tile.baseTile.alpha > 0) {
tile.baseTile.alpha -= alphaIncrement;
}
}, 50);
}
});
});
var soilAnimation = LK.setInterval(function () {
if (gridBoardSoil.alpha < 1) {
gridBoardSoil.alpha += alphaIncrement;
} else {
LK.clearInterval(soilAnimation);
growGrass.visible = true;
// Animate growGrass alpha from 0 to 1
var grassAnimation = LK.setInterval(function () {
if (growGrass.alpha < 1) {
growGrass.alpha += 0.05; // Adjust the increment for desired speed
} else {
LK.clearInterval(grassAnimation);
LK.setTimeout(function () {
cleanPlayingState();
initNewRoundState();
}, 2000);
}
}, 75); // Adjust the interval for desired speed
}
}, 50); // Adjust the interval for desired speed
}
/****
* Game State Management
****/
function initializeGame() {
// Init and Add backgroundLayer
backgroundLayer = new Container();
middleLayer = new Container();
game.addChild(backgroundLayer);
// Initialize grid board
gridBoard = LK.getAsset('gridBoard', {
anchorX: 0.5,
anchorY: 0.5,
visible: false
});
gridBoard.x = 2048 / 2;
gridBoard.y = 2732 / 2;
game.addChild(gridBoard);
// Initialize grid board soil
gridBoardSoil = LK.getAsset('gridBoardSoil', {
anchorX: 0.5,
anchorY: 0.5,
visible: false,
alpha: 0
});
gridBoardSoil.x = 2048 / 2 + 20;
gridBoardSoil.y = 2732 / 2 - 20;
game.addChild(gridBoardSoil);
game.addChild(middleLayer);
// Create growGrass asset
growGrass = LK.getAsset('growGrass', {
anchorX: 0.5,
anchorY: 0.5,
visible: false,
alpha: 0
});
growGrass.x = 2048 / 2 + 20;
growGrass.y = 2732 / 2;
middleLayer.addChild(growGrass);
// Initialize game assets and variables
puzzleManager = new PuzzleManager();
// Initialize level text
levelText = new Text2("Level 1", {
size: 100,
fill: 0xFFFFFF
});
levelText.x = 2048 / 2;
levelText.y = 200;
levelText.anchorX = 0.5;
levelText.visible = false;
// Add the level text to the game
game.addChild(levelText);
// Transition to menu state
changeGameState(GAME_STATE.MENU);
}
function initMenuState() {
// Show level selection UI
console.log("Entering Menu State");
isPlaying = false;
// Add backgroundPlaying1 to the menu state
var backgroundPlaying1 = LK.getAsset('backgroundPlaying1', {
anchorX: 0.5,
anchorY: 0.5
});
backgroundPlaying1.x = 2048 / 2;
backgroundPlaying1.y = 2732 / 2;
backgroundLayer.addChild(backgroundPlaying1);
// Add logo to the menu state
logo = LK.getAsset('logo', {
anchorX: 0.5,
anchorY: 0.5,
width: 1480,
height: 1480
});
logo.x = 2048 / 2;
logo.y = -logo.height; // Initialize logo out of screen
middleLayer.addChild(logo);
// Update any menu animations here
tween(logo, {
x: 2048 / 2,
// Center horizontally
y: 2732 / 2 - 50 // Center vertically with offset
}, {
duration: 1000,
easing: tween.bounceOut // Use predefined bounceOut easing function
});
}
function handleMenuLoop() {}
function cleanMenuState() {
if (logo) {
logo.visible = false;
game.removeChild(logo);
}
}
function initNewRoundState() {
// Create and add backgroundPlaying1 to backgroundLayer
var backgroundPlaying1 = LK.getAsset('backgroundPlaying1', {
anchorX: 0.5,
anchorY: 0.5
});
backgroundPlaying1.x = 2048 / 2;
backgroundPlaying1.y = 2732 / 2;
backgroundLayer.addChild(backgroundPlaying1);
levelText.visible = true;
levelText.text = "Level 1";
// Reset puzzle manager for new round
console.log("Entering New Round State");
if (puzzleManager) {
puzzleManager.reset();
}
// Show gridBoard
gridBoard.visible = true;
// 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;
// Reset gridBoardSoil visibility and alpha
if (gridBoardSoil) {
gridBoardSoil.visible = false;
gridBoardSoil.alpha = 0;
}
// Hide growGrass
if (growGrass) {
growGrass.visible = false;
growGrass.alpha = 0;
}
// Stop waterdrops animations if any
if (waterDropInterval) {
LK.clearInterval(waterDropInterval);
waterDropInterval = null;
}
// Remove remaining waterdrops if any
for (var i = waterDrops.length - 1; i >= 0; i--) {
if (waterDrops[i].visible) {
waterDrops[i].destroy();
waterDrops.splice(i, 1);
}
}
}
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();
}
}
}
// Test the level converter
var testAsciiLevel = "\nS-C.\n.|..\n.C-E\n....\n";
console.log("Testing ASCII to Level conversion:");
var convertedLevel = stringToLevel(testAsciiLevel);
if (typeof JSON !== 'undefined' && JSON.stringify) {
console.log("Converted Level:", JSON.stringify(convertedLevel, null, 2));
} else {
console.log("JSON.stringify is not available.");
}
console.log("\nTesting Level to ASCII conversion:");
var backToAscii = levelToString(convertedLevel);
console.log("Back to ASCII:\n" + backToAscii);
// Test generating a new level
console.log("\nTesting level generation:");
var generatedLevel = generateNextLevel([convertedLevel]);
console.log("Generated Level ASCII:\n" + levelToString(generatedLevel));
straigth zenith view square light wooden pallet. Single Game Texture. In-Game asset. 2d. Blank background. High contrast. No shadows.
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.
simple yellow rating star. Modern video game style
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