Code edit (1 edits merged)
Please save this source code
Code edit (1 edits merged)
Please save this source code
Code edit (1 edits merged)
Please save this source code
Code edit (1 edits merged)
Please save this source code
Code edit (1 edits merged)
Please save this source code
Code edit (8 edits merged)
Please save this source code
User prompt
add a random rotation to flowers when spawning
Code edit (2 edits merged)
Please save this source code
User prompt
Please fix the bug: 'ReferenceError: finalScaleX is not defined' in or related to this line: 'if (flowerGraphics.scaleX < finalScaleX) {' Line Number: 62
User prompt
also when spawning Flower, make them grow in size from 0 to their final size
User prompt
when spawning Flower, make them fade in with an alpha anim from 0 to 1, (don't use tween for that)
Code edit (7 edits merged)
Please save this source code
User prompt
when spawning Flower, make them fade in with an alpha anim from 0 to 1
Code edit (1 edits merged)
Please save this source code
Code edit (1 edits merged)
Please save this source code
Code edit (1 edits merged)
Please save this source code
User prompt
in self.updateCornerPipeThirdPhase add logs for self.waterH x, y and dir
User prompt
add plenty of logs in updateCornerPipeFirstPhase and updateCornerPipeThirdPhase
Code edit (8 edits merged)
Please save this source code
User prompt
Please fix the bug: 'Timeout.tick error: Cannot read properties of undefined (reading '0')' in or related to this line: 'var tileStr = level[row][col];' Line Number: 1149
Code edit (1 edits merged)
Please save this source code
User prompt
in flower class, make size random from 100% to 100% + sizeRatioRange %
Code edit (1 edits merged)
Please save this source code
User prompt
in flower class make position random around x,y within positionOffset range
User prompt
in Flower class, make assetId random from 1 to maxIndex (keep prefix 'flower')
/****
* Plugins
****/
var tween = LK.import("@upit/tween.v1");
/****
* Classes
****/
var Flower = Container.expand(function (maxIndex, x, y) {
var self = Container.call(this);
var positionOffset = 100;
var assetId = 'flower' + Math.floor(Math.random() * maxIndex + 1);
var flowerGraphics = self.attachAsset(assetId, {
anchorX: 0.5,
anchorY: 0.5,
x: x,
y: y
});
return self;
});
// Removed the import statement for the tween plugin as it is causing an error
// Removed the import statement for the tween plugin as it is causing an error
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
****/
function assetExists(assetId) {
try {
LK.getAsset(assetId, {});
return true;
} catch (e) {
return false;
}
}
function _slicedToArray5(r, e) {
return _arrayWithHoles5(r) || _iterableToArrayLimit5(r, e) || _unsupportedIterableToArray5(r, e) || _nonIterableRest5();
}
function _arrayWithHoles5(r) {
if (Array.isArray(r)) {
return r;
}
}
function _iterableToArrayLimit5(r, l) {
var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
if (null != t) {
var e,
n,
i,
u,
a = [],
f = !0,
o = !1;
try {
if (i = (t = t.call(r)).next, 0 === l) {
if (Object(t) !== t) {
return;
}
f = !1;
} else {
for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0) {
;
}
}
} catch (r) {
o = !0, n = r;
} finally {
try {
if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) {
return;
}
} finally {
if (o) {
throw n;
}
}
}
return a;
}
}
function _unsupportedIterableToArray5(r, a) {
if (r) {
if ("string" == typeof r) {
return _arrayLikeToArray5(r, a);
}
var t = {}.toString.call(r).slice(8, -1);
return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray5(r, a) : void 0;
}
}
function _arrayLikeToArray5(r, a) {
(null == a || a > r.length) && (a = r.length);
for (var e = 0, n = Array(a); e < a; e++) {
n[e] = r[e];
}
return n;
}
function _nonIterableRest5() {
throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _createForOfIteratorHelper(o, allowArrayLike) {
var it;
if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) {
if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
if (it) {
o = it;
}
var i = 0;
var F = function F() {};
return {
s: F,
n: function n() {
if (i >= o.length) {
return {
done: true
};
}
return {
done: false,
value: o[i++]
};
},
e: function e(_e) {
throw _e;
},
f: F
};
}
throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
var normalCompletion = true,
didErr = false,
err;
return {
s: function s() {
it = o[Symbol.iterator]();
},
n: function n() {
var step = it.next();
normalCompletion = step.done;
return step;
},
e: function e(_e2) {
didErr = true;
err = _e2;
},
f: function f() {
try {
if (!normalCompletion && it["return"] != null) {
it["return"]();
}
} finally {
if (didErr) {
throw err;
}
}
}
};
}
/****
* 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;
}
}
function _slicedToArray4(r, e) {
return _arrayWithHoles4(r) || _iterableToArrayLimit4(r, e) || _unsupportedIterableToArray4(r, e) || _nonIterableRest4();
}
function _nonIterableRest4() {
throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _unsupportedIterableToArray4(r, a) {
if (r) {
if ("string" == typeof r) {
return _arrayLikeToArray4(r, a);
}
var t = {}.toString.call(r).slice(8, -1);
return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray4(r, a) : void 0;
}
}
function _arrayLikeToArray4(r, a) {
(null == a || a > r.length) && (a = r.length);
for (var e = 0, n = Array(a); e < a; e++) {
n[e] = r[e];
}
return n;
}
function _iterableToArrayLimit4(r, l) {
var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
if (null != t) {
var e,
n,
i,
u,
a = [],
f = !0,
o = !1;
try {
if (i = (t = t.call(r)).next, 0 === l) {
if (Object(t) !== t) {
return;
}
f = !1;
} else {
for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0) {
;
}
}
} catch (r) {
o = !0, n = r;
} finally {
try {
if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) {
return;
}
} finally {
if (o) {
throw n;
}
}
}
return a;
}
}
function _arrayWithHoles4(r) {
if (Array.isArray(r)) {
return r;
}
}
function Tile() {
var self = this;
Container.call(self);
self.type = null;
self.fixed = false;
self.gridRow = -1;
self.gridCol = -1;
self.flow = false;
self.startFlowTicks = 0;
self.baseTint = 0xaaaaaa;
self.baseTintLight = 0xaaaaaa;
self.maxWaterSize = 260;
self.flowSpeed = 12;
self.pipeContainer = new Container();
//self.addChild(self.pipeContainer);
self.createStartPipe = 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.createEndPipe = 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.createStraightPipe = function (isVertical) {
if (isVertical) {
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'
});
} else {
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.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.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.setType = function (type, row, col, fixed) {
self.type = type;
self.gridRow = row;
self.gridCol = col;
// Add base tile last so it appears under the pipes
var baseTileAsset = fixed ? 'baseTile' : 'baseMobileTile';
log("setType : setting baseTile...");
self.baseTile = self.attachAsset(baseTileAsset, {
anchorX: 0.5,
anchorY: 0.5,
width: tileSize,
height: tileSize,
tint: 0xFFFFFF
});
self.addChild(self.pipeContainer);
// Clear existing pipe graphics
while (self.pipeContainer.children.length > 0) {
self.pipeContainer.removeChildAt(0);
}
// Create pipe graphics based on type
switch (type) {
case TileFormat.TYPES.START:
self.createStartPipe();
break;
case TileFormat.TYPES.END:
self.createEndPipe();
break;
case TileFormat.TYPES.VERTICAL:
self.createStraightPipe(true);
break;
case TileFormat.TYPES.HORIZONTAL:
self.createStraightPipe(false);
break;
case TileFormat.TYPES.CORNER:
self.createCornerPipe();
break;
case TileFormat.TYPES.CROSS:
self.createCrossPipe();
break;
}
};
self.getNextPositions = function (col, row, rotation, type, incomingDirection) {
var positions = [];
//var normalizedIncoming = (incomingDirection + Math.PI) % (2 * Math.PI);
//var normalizedIncoming = getFlowDirection(puzzleManager.grid[row][col], incomingDirection);
log("Getting next position for tile at", row, col, "type:", type, "rotation:", rotation, "incoming direction:", incomingDirection); //, "normalizedIncoming::", normalizedIncoming);
//incomingDirection = normalizedIncoming;
switch (type) {
case TileFormat.TYPES.START:
// Start pipe flows in direction of rotation
var dx = -Math.sin(rotation);
var dy = Math.cos(rotation);
positions.push([col + Math.round(dx), row + Math.round(dy)]);
log("START: flowing in direction dx:", dx, "dy:", dy);
break;
case TileFormat.TYPES.VERTICAL:
// For vertical pipes, we flow in the opposite direction of incoming
// If water comes from top (Ï€/2), we flow down
// If water comes from bottom (3Ï€/2), we flow up
if (Math.abs(incomingDirection - 3 * Math.PI / 2) < 0.1) {
positions.push([col, row + 1]); // Flow down
log("VERTICAL: incoming from top, flowing down");
} else if (Math.abs(incomingDirection - Math.PI / 2) < 0.1) {
positions.push([col, row - 1]); // Flow up
log("VERTICAL: incoming from bottom, flowing up");
} else if (incomingDirection === 0) {
// Initial flow from start - flow down
positions.push([col, row + 1]);
log("VERTICAL: initial flow, going down");
}
break;
case TileFormat.TYPES.HORIZONTAL:
// For horizontal pipes, we flow in the opposite direction of incoming
// If water comes from left (0), we flow right
// If water comes from right (Ï€), we flow left
if (Math.abs(incomingDirection) < 0.1) {
positions.push([col + 1, row]); // Flow right
log("HORIZONTAL: incoming from left, flowing right");
} else if (Math.abs(incomingDirection - Math.PI) < 0.1 || incomingDirection === 0) {
positions.push([col - 1, row]); // Flow left
log("HORIZONTAL: incoming from right, flowing left");
} else {
log("ERROR HORIZONTAL: incoming not matching!");
}
break;
case TileFormat.TYPES.CORNER:
var outgoingDirection;
var normalizedRotation = (rotation + Math.PI / 2) % (2 * Math.PI);
log("CORNER PIE with rotation:", rotation, " normalized rotation:", normalizedRotation, " with incoming:", incomingDirection);
var acceptAngle1 = Math.sin(rotation) ? rotation + Math.PI / 2 : rotation;
var acceptAngle2 = Math.sin(rotation) ? rotation + Math.PI : rotation - Math.PI / 2;
log("Checking if incoming match pipe entry:", acceptAngle1, " or ", acceptAngle2, " vs ", incomingDirection);
if (Math.abs(incomingDirection - acceptAngle1) < 0.1) {
outgoingDirection = acceptAngle2 + Math.PI;
}
if (Math.abs(incomingDirection - acceptAngle2) < 0.1) {
outgoingDirection = acceptAngle1 + Math.PI;
}
log("CORNER: turning from", incomingDirection, "to", outgoingDirection);
//log("if so, turn 90° or -90° depending on incoming and rotation...");
// For corner pipes, we turn 90° based on the incoming direction
// If incoming matches pipe entry point, turn 90° clockwise
/*
if (Math.abs(incomingDirection - normalizedRotation) < 0.1) {
outgoingDirection = (incomingDirection + Math.PI / 2) % (2 * Math.PI);
log("CORNER: turning clockwise from", incomingDirection, "to", outgoingDirection);
}
// If incoming is 90° from pipe entry, turn 90° counterclockwise
else if (Math.abs(incomingDirection - (normalizedRotation + Math.PI / 2) % (2 * Math.PI)) < 0.1) {
outgoingDirection = (incomingDirection - Math.PI / 2 + 2 * Math.PI) % (2 * Math.PI);
log("CORNER: turning counterclockwise from", incomingDirection, "to", outgoingDirection);
}
*/
if (outgoingDirection !== undefined) {
// Convert angle to grid movement
var dx = Math.round(Math.cos(outgoingDirection));
var dy = -Math.round(Math.sin(outgoingDirection));
positions.push([col + dx, row + dy]);
log("CORNER: moving dx:", dx, "dy:", dy);
} else {
log("ERROR CORNER: incoming not matching!");
}
break;
case TileFormat.TYPES.END:
// End tile doesn't flow anywhere
log("END: no next position");
break;
}
log("Final next positions:", positions);
return positions;
};
self.normalizeRotation = function (rotation) {
while (rotation < 0) {
rotation += 2 * Math.PI;
}
return rotation % (2 * Math.PI);
};
self.setRotation = function (rotation) {
if (typeof rotation === 'number') {
self.pipeContainer.rotation = self.normalizeRotation(rotation); //* Math.PI / 2 DBO
} else {
// Handle string rotations (legacy support)
switch (rotation) {
case 'up':
self.pipeContainer.rotation = 0;
break;
case 'right':
self.pipeContainer.rotation = Math.PI / 2;
break;
case 'down':
self.pipeContainer.rotation = Math.PI;
break;
case 'left':
self.pipeContainer.rotation = 3 * Math.PI / 2;
break;
}
}
};
self.updatePosition = function (row, col) {
self.gridRow = row;
self.gridCol = col;
//self.x = col * tileSize + gridBoard.x - gridBoard.width / 2;
//self.y = row * tileSize + gridBoard.y - gridBoard.height / 2;
self.x = col * tileSize + gridBoard.x - gridBoard.width / 2 + tileSize / 2 + boardOffsetX;
self.y = row * tileSize + gridBoard.y - gridBoard.height / 2 + tileSize / 2 + boardOffsetY;
log('Tile row,col:', row, col, 'Tile position:', self.x, self.y, 'Tile dimensions:', self.width, self.height, ' self:', self);
//log('pipeContainer:', self.pipeContainer.x, self.pipeContainer.y, ' child:', self.pipeContainer.children[0].x, self.pipeContainer.children[0].y);
// log('gridBoard :', gridBoard.x, gridBoard.y, ' size:', gridBoard.width, gridBoard.height);
};
// Water flow update methods
self.updateStartTile = function () {
if (self.valve) {
var rotationValue = (LK.ticks - self.startFlowTicks) * 0.1;
self.valve.rotation = rotationValue;
if (rotationValue >= Math.PI * 3) {
self.flow = false;
}
}
};
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 + 100, game);
waterDropInterval = LK.setInterval(function () {
createWaterDrops(self.x, self.y + 100, game);
}, 500 + Math.random() * 500);
}
}
}
};
self.updateRegularPipe = function () {
if (self.water) {
var heightValue = (LK.ticks - self.startFlowTicks) * self.flowSpeed;
if (heightValue < self.maxWaterSize) {
log("updateRegularPipe ", self.water.dir, self.rotation, self.pipeContainer.rotation, self);
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') {
log("=> bt", self.rotation, self.pipeContainer.rotation, self);
self.water.height = heightValue;
self.water.y = 130;
self.water.scaleY = -1;
} else {
self.water.height = heightValue;
}
} else {
self.flow = false;
}
}
};
self.updateCornerPipe = function () {
var progress = (LK.ticks - self.startFlowTicks) * self.flowSpeed;
var thirdSize = self.maxWaterSize / 3;
if (progress < thirdSize) {
self.updateCornerPipeFirstPhase(progress, thirdSize);
} else if (progress < thirdSize * 2) {
self.updateCornerPipeSecondPhase(progress, thirdSize);
} else {
self.updateCornerPipeThirdPhase(progress, thirdSize);
}
if (progress >= self.maxWaterSize) {
self.flow = false;
}
};
self.updateCornerPipeFirstPhase = function (progress, thirdSize) {
if (self.waterV) {
self.waterV.visible = true;
self.waterV.height = progress;
}
};
self.updateCornerPipeSecondPhase = function (progress, thirdSize) {
if (self.waterCorner) {
self.waterCorner.visible = true;
self.waterCorner.alpha = (progress - thirdSize) / thirdSize;
var rotationProgress = (progress - thirdSize) / thirdSize;
self.waterCorner.rotation = -Math.PI / 2 - rotationProgress * Math.PI / 2;
}
if (self.waterCornerCover) {
self.waterCornerCover.visible = true;
self.waterCornerCover.alpha = (progress - thirdSize) / thirdSize;
}
};
self.updateCornerPipeThirdPhase = function (progress, thirdSize) {
if (self.waterH) {
self.waterH.visible = true;
self.waterH.width = progress - thirdSize * 2;
self.waterH.rotation = self.pipeContainer.rotation ? self.pipeContainer.rotation : 3 * Math.PI / 2;
}
};
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 TileFormat.TYPES.START:
self.updateStartTile();
break;
case TileFormat.TYPES.END:
self.updateEndTile();
break;
case TileFormat.TYPES.CORNER:
self.updateCornerPipe();
break;
default:
self.updateRegularPipe();
break;
}
}
// Animate end tile fountain
if (self.type === TileFormat.TYPES.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;
}
};
}
Tile.prototype = Object.create(Container.prototype);
function _slicedToArray3(r, e) {
return _arrayWithHoles3(r) || _iterableToArrayLimit3(r, e) || _unsupportedIterableToArray3(r, e) || _nonIterableRest3();
}
function _nonIterableRest3() {
throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _unsupportedIterableToArray3(r, a) {
if (r) {
if ("string" == typeof r) {
return _arrayLikeToArray3(r, a);
}
var t = {}.toString.call(r).slice(8, -1);
return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray3(r, a) : void 0;
}
}
function _arrayLikeToArray3(r, a) {
(null == a || a > r.length) && (a = r.length);
for (var e = 0, n = Array(a); e < a; e++) {
n[e] = r[e];
}
return n;
}
function _iterableToArrayLimit3(r, l) {
var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
if (null != t) {
var e,
n,
i,
u,
a = [],
f = !0,
o = !1;
try {
if (i = (t = t.call(r)).next, 0 === l) {
if (Object(t) !== t) {
return;
}
f = !1;
} else {
for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0) {
;
}
}
} catch (r) {
o = !0, n = r;
} finally {
try {
if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) {
return;
}
} finally {
if (o) {
throw n;
}
}
}
return a;
}
}
function _arrayWithHoles3(r) {
if (Array.isArray(r)) {
return r;
}
}
function _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(game) {
var self = this;
self.game = game;
self.grid = [];
self.gridSize = 4;
self.selectedTile = null;
self.isComplete = false;
self.waterFlowing = false;
self.solutionPath = null; // Store the solution path for water flow
self.reset = function () {
// Clear grid
for (var row = 0; row < self.gridSize; row++) {
if (!self.grid[row]) {
self.grid[row] = [];
}
for (var col = 0; col < self.gridSize; col++) {
if (self.grid[row][col]) {
self.grid[row][col].destroy();
}
self.grid[row][col] = null;
}
}
// Reset state
self.selectedTile = null;
// Remove all flowers
for (var i = flowers.length - 1; i >= 0; i--) {
if (flowers[i].parent) {
flowers[i].parent.removeChild(flowers[i]);
}
}
flowers = [];
self.waterFlowing = false;
// Clear water drops
if (waterDropInterval) {
LK.clearInterval(waterDropInterval);
waterDropInterval = null;
}
// Reset water particles
if (game.waterParticles) {
for (var i = game.waterParticles.length - 1; i >= 0; i--) {
var particle = game.waterParticles[i];
if (particle && particle.parent) {
particle.parent.removeChild(particle);
}
}
game.waterParticles = [];
}
if (self.isComplete) {
self.currentLevel++;
} else {
self.currentLevel = self.currentLevel || 1;
}
self.isComplete = false;
};
self.initPuzzle = function () {
self.reset();
var level = levelConfigs[self.currentLevel];
// Initialize grid with tiles from level configuration
for (var row = 0; row < self.gridSize; row++) {
self.grid[row] = [];
for (var col = 0; col < self.gridSize; col++) {
var tileStr = level[row][col];
var tile = createTile(tileStr, row, col);
if (tile) {
//gridBoard.addChild(tile);
game.addChild(tile);
self.grid[row][col] = tile;
}
}
}
};
self.checkWinCondition = function () {
log("=== Starting Win Condition Check ===");
log("Grid state:");
for (var row = 0; row < self.gridSize; row++) {
var rowStr = [];
for (var col = 0; col < self.gridSize; col++) {
var tile = self.grid[row][col];
if (tile) {
var rotIndex = TileFormat.getRotationIndex(tile.normalizeRotation(tile.pipeContainer.rotation));
rowStr.push("".concat(tile.fixed ? 'F' : 'M', "-").concat(tile.type, "-").concat(rotIndex));
} else {
rowStr.push('empty');
}
}
log("Row ".concat(row, ":"), rowStr.join(' | '));
}
// Find start tile
var startTile = null;
var startRow = -1,
startCol = -1;
for (var row = 0; row < self.gridSize; row++) {
for (var col = 0; col < self.gridSize; col++) {
if (self.grid[row][col] && self.grid[row][col].type === TileFormat.TYPES.START) {
startTile = self.grid[row][col];
startRow = row;
startCol = col;
break;
}
}
if (startTile) {
break;
}
}
if (!startTile) {
log("No start tile found!");
return false;
}
log("Found start tile at row:", startRow, "col:", startCol);
var visited = new SimpleSet();
var startDir = getFlowDirection(startTile);
var toCheck = [[startRow, startCol, startDir]];
var pathMap = {}; // Store the path for each visited position
// Store start position
pathMap[startRow + "," + startCol] = {
row: startRow,
col: startCol,
flowDirection: null,
// Start doesn't have incoming //startDir,
prevKey: null
};
while (toCheck.length > 0) {
var _toCheck$pop = toCheck.pop(),
_toCheck$pop2 = _slicedToArray2(_toCheck$pop, 3),
row = _toCheck$pop2[0],
col = _toCheck$pop2[1],
flowDirection = _toCheck$pop2[2];
var key = "".concat(row, ",").concat(col);
if (visited.has(key)) {
continue;
}
visited.add(key);
log("======================= Checking position - row:", row, "col:", col, "=========================");
// Store current position in path map
//pathMap.set(key, { row, col, flowDirection });
// Check if coordinates are within grid
if (row < 0 || row >= self.gridSize || col < 0 || col >= self.gridSize) {
log("Position out of bounds");
continue;
}
var currentTile = self.grid[row][col];
if (!currentTile) {
log("No tile at position");
continue;
}
var normalizedRotation = currentTile.normalizeRotation(currentTile.pipeContainer.rotation);
log("Checking tile:", currentTile.type, "rotation:", TileFormat.getRotationIndex(normalizedRotation));
if (currentTile.type == TileFormat.TYPES.START) {
flowDirection = null; // Start doesn't have incoming flow
}
var nextPositions = currentTile.getNextPositions(col, row, normalizedRotation, currentTile.type, flowDirection);
log("Next positions to check:", nextPositions);
var _iterator = _createForOfIteratorHelper(nextPositions),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var nextPos = _step.value;
var _nextPos = nextPos,
_nextPos2 = _slicedToArray2(_nextPos, 2),
nextCol = _nextPos2[0],
nextRow = _nextPos2[1];
log("Trying next position - row:", nextRow, "col:", nextCol);
if (nextRow < 0 || nextRow >= self.gridSize || nextCol < 0 || nextCol >= self.gridSize) {
log("Next position out of bounds");
continue;
}
var nextTile = self.grid[nextRow][nextCol];
if (!nextTile) {
log("No tile at next position");
continue;
}
var incomingDirection = Math.atan2(nextRow - row, col - nextCol);
if (!canAcceptFlowFromDirection(nextTile, incomingDirection)) {
log("Tile at row:", nextRow, "col:", nextCol, "cannot accept flow from direction:", incomingDirection);
continue;
}
log("== OK. Prepare next tile with previous tile at ", incomingDirection, " (", nextRow, row, nextCol, col, ")");
// Update nextTile.water.dir depending on incomingDirection
if (nextTile.water) {
log("Updating water direction for tile at row:", nextRow, "col:", nextCol);
if (nextTile.type === TileFormat.TYPES.VERTICAL) {
if (Math.abs(incomingDirection - Math.PI / 2) < 0.1) {
nextTile.water.dir = 'tb'; // Top to Bottom
log("Set water direction to 'tb' (Top to Bottom)");
} else {
//if (Math.abs(incomingDirection - 3 * Math.PI / 2) < 0.1)
nextTile.water.dir = 'bt'; // Bottom to Top
log("Set water direction to 'bt' (Bottom to Top)");
}
} else if (nextTile.type === TileFormat.TYPES.HORIZONTAL) {
if (Math.abs(incomingDirection - Math.PI) < 0.1) {
nextTile.water.dir = 'lr'; // Left to Right
log("Set water direction to 'lr' (Left to Right)");
} else {
// if (Math.abs(incomingDirection) < 0.1)
nextTile.water.dir = 'rl'; // Right to Left
log("Set water direction to 'rl' (Right to Left)");
}
}
}
if (nextTile.type === TileFormat.TYPES.END) {
log("Found path to end!");
// Start reconstruction from the end position
self.solutionPath = [];
// Add all tiles from pathMap to solution path
Object.keys(pathMap).forEach(function (key) {
var _key$split$map = key.split(",").map(Number),
_key$split$map2 = _slicedToArray5(_key$split$map, 2),
row = _key$split$map2[0],
col = _key$split$map2[1];
var tile = self.grid[row][col];
if (tile) {
self.solutionPath.push({
row: row,
col: col,
flowDirection: tile.normalizeRotation(tile.pipeContainer.rotation),
tile: tile
});
log("Added tile from pathMap:", row, col);
}
});
// Add the end tile
self.solutionPath.push({
row: nextRow,
col: nextCol,
flowDirection: nextTile.normalizeRotation(nextTile.pipeContainer.rotation),
tile: nextTile
});
log("Added end tile:", nextRow, nextCol);
log("Solution path reconstructed with", self.solutionPath.length, "tiles");
return true;
}
//var nextFlowDirection = getFlowDirection(nextTile, incomingDirection);
var nextFlowDirection = getFlowDirection(currentTile, flowDirection); // incomingDirection);
var nextKey = nextRow + "," + nextCol;
log("Set next tile ", nextKey, " flow dir:", nextFlowDirection);
toCheck.push([nextRow, nextCol, nextFlowDirection]);
pathMap[nextKey] = {
row: nextRow,
col: nextCol,
flowDirection: nextFlowDirection,
prevKey: key
};
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
}
log("No valid path found");
return false;
};
self.selectTile = function (x, y) {
if (!isPlaying) {
return;
}
// Convert screen coordinates to grid coordinates
var boardX = gridBoard.x - gridBoard.width / 2 + boardOffsetX;
var boardY = gridBoard.y - gridBoard.height / 2 + boardOffsetY;
var row = Math.floor((y - boardY) / tileSize);
var col = Math.floor((x - boardX) / tileSize);
log("Click at ", x, ",", y, " => Grid coordinates - row:", row, "col:", col);
// Check if coordinates are within grid
if (row >= 0 && row < this.gridSize && col >= 0 && col < this.gridSize) {
var tile = this.grid[row][col];
log("Clicked tile ", tile);
// Check if tile exists, is mobile, and not start/end
if (tile && !tile.fixed && tile.type !== TileFormat.TYPES.START && tile.type !== TileFormat.TYPES.END) {
this.selectedTile = {
row: row,
col: col,
tile: tile
};
log("Selected tile row:", this.selectedTile.row, "col:", this.selectedTile.col, this.selectedTile.tile);
// Check possible moves
this.checkPossibleMoves();
}
}
// If no tile is found, search nearby tiles using tapOffset
if (!this.selectedTile) {
var nearbyOffsets = [{
dx: tapOffset,
dy: 0
}, {
dx: -tapOffset,
dy: 0
}, {
dx: 0,
dy: tapOffset
}, {
dx: 0,
dy: -tapOffset
}];
for (var _i = 0, _nearbyOffsets = nearbyOffsets; _i < _nearbyOffsets.length; _i++) {
var offset = _nearbyOffsets[_i];
var nearbyRow = Math.floor((y - boardY + offset.dy) / tileSize);
var nearbyCol = Math.floor((x - boardX + offset.dx) / tileSize);
if (nearbyRow >= 0 && nearbyRow < this.gridSize && nearbyCol >= 0 && nearbyCol < this.gridSize) {
var nearbyTile = this.grid[nearbyRow][nearbyCol];
if (nearbyTile && !nearbyTile.fixed && nearbyTile.type !== TileFormat.TYPES.START && nearbyTile.type !== TileFormat.TYPES.END) {
this.selectedTile = {
row: nearbyRow,
col: nearbyCol,
tile: nearbyTile
};
log("Selected nearby tile row:", this.selectedTile.row, "col:", this.selectedTile.col, this.selectedTile.tile);
this.checkPossibleMoves();
break;
}
}
}
}
};
self.checkPossibleMoves = function () {
if (!this.selectedTile) {
return;
}
var row = this.selectedTile.row;
var col = this.selectedTile.col;
var possibleMoves = [];
// Check each direction
// Right
if (col < this.gridSize - 1 && !this.grid[row][col + 1]) {
possibleMoves.push('right');
}
// Left
if (col > 0 && !this.grid[row][col - 1]) {
possibleMoves.push('left');
}
// Down
if (row < this.gridSize - 1 && !this.grid[row + 1][col]) {
possibleMoves.push('down');
}
// Up
if (row > 0 && !this.grid[row - 1][col]) {
possibleMoves.push('up');
}
this.selectedTile.possibleMoves = possibleMoves;
};
self.moveTile = function (direction) {
if (!isPlaying || !this.selectedTile || !this.selectedTile.possibleMoves.includes(direction)) {
LK.getSound('tileBlocked').play();
log("Invalid move attempt in direction:", direction);
return;
}
var oldRow = this.selectedTile.row;
var oldCol = this.selectedTile.col;
var newRow = oldRow;
var newCol = oldCol;
// Calculate new position
switch (direction) {
case 'right':
newCol++;
break;
case 'left':
newCol--;
break;
case 'down':
newRow++;
break;
case 'up':
newRow--;
break;
}
// Play tile slide sound
LK.getSound('tileSlide').play();
// Move tile with tween animation
var movingTile = this.grid[oldRow][oldCol];
this.grid[oldRow][oldCol] = null;
this.grid[newRow][newCol] = movingTile;
// Use tween to animate the tile movement
tween(movingTile, {
x: newCol * tileSize + gridBoard.x - gridBoard.width / 2 + tileSize / 2 + boardOffsetX,
y: newRow * tileSize + gridBoard.y - gridBoard.height / 2 + tileSize / 2 + boardOffsetY
}, {
duration: 300,
easing: tween.easeInOut,
onFinish: function onFinish() {
// Update tile position after animation completes
movingTile.updatePosition(newRow, newCol);
}
});
// Clear selection
this.selectedTile = null;
// Check if puzzle is solved
if (this.checkWinCondition()) {
this.isComplete = true;
isPlaying = false;
LK.setTimeout(function () {
puzzleManager.startWaterFlow();
LK.getSound('levelWon').play();
}, 300);
}
};
self.startWaterFlow = function () {
if (!self.solutionPath || self.solutionPath.length === 0) {
log("No solution path available!");
return false;
}
// Reset any existing flow states
for (var row = 0; row < self.gridSize; row++) {
for (var col = 0; col < self.gridSize; col++) {
if (self.grid[row][col]) {
self.grid[row][col].flow = false;
if (self.grid[row][col].water) {
self.grid[row][col].water.visible = false;
}
if (self.grid[row][col].waterV) {
self.grid[row][col].waterV.visible = false;
}
if (self.grid[row][col].waterH) {
self.grid[row][col].waterH.visible = false;
}
}
}
}
self.waterFlowing = true;
log("Starting water flow through solution path:", self.solutionPath.length, "tiles");
var currentIndex = 0;
function animateNextTile() {
if (currentIndex >= self.solutionPath.length) {
// End of path reached - start end game sequence
LK.setTimeout(function () {
animateSoil();
}, 300);
return;
}
var currentTile = self.solutionPath[currentIndex].tile;
currentTile.flow = true;
// Show appropriate water animation based on tile type
if (currentTile.water) {
currentTile.water.visible = true;
}
if (currentTile.waterV) {
currentTile.waterV.visible = true;
}
if (currentTile.waterH) {
currentTile.waterH.visible = true;
// Set water flow direction based on path
if (currentIndex > 0) {
var prevTile = self.solutionPath[currentIndex - 1].tile;
currentTile.waterH.scaleX = prevTile.gridCol < currentTile.gridCol ? 1 : -1;
}
}
// Special handling for start tile
if (currentTile.type === TileFormat.TYPES.START) {
LK.getSound('waterInPipe').play();
}
// Special handling for end tile
if (currentTile.type === TileFormat.TYPES.END) {
createWaterDrops(currentTile.x, currentTile.y + 100, game);
}
currentIndex++;
LK.setTimeout(animateNextTile, 300);
}
// Start the animation
animateNextTile();
return true;
};
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 = 100; // Lower threshold for easier movement detection
var tapOffset = 50; // Offset for searching nearby tiles when no tile is found
var levelText;
var waterDrops = [];
var flowers = [];
var waterDropInterval;
var logo;
var puzzleManager;
// Initialize the game
initializeGame();
/****
* Helper Functions
****/
function getFlowDirection(tile, incomingDirection) {
//var rotation = tile.normalizeRotation(tile.pipeContainer.rotation);
var flowDir; //(incomingDirection + Math.PI) % (2 * Math.PI);
log("Get Output flow dir:", tile.type, "Rotation:", tile.pipeContainer.rotation, "incomingDirection:", incomingDirection); //, "Normalized incoming:", rotation);
switch (tile.type) {
case TileFormat.TYPES.START:
log("Start detail: ", Math.PI * 2, " + ", tile.pipeContainer.rotation, " + ", Math.PI / 2, " * (", Math.abs(Math.sin(tile.pipeContainer.rotation)), " - ", Math.abs(Math.cos(tile.pipeContainer.rotation)), ")");
flowDir = Math.PI * 2 + tile.pipeContainer.rotation + Math.PI / 2 * (Math.abs(Math.sin(tile.pipeContainer.rotation)) - Math.abs(Math.cos(tile.pipeContainer.rotation)));
break;
case TileFormat.TYPES.CORNER:
if (Math.abs(tile.pipeContainer.rotation - incomingDirection) < 0.1 || Math.abs(tile.pipeContainer.rotation + Math.PI - incomingDirection) < 0.1) {
flowDir = incomingDirection + Math.PI / 2;
} else {
flowDir = incomingDirection - Math.PI / 2;
}
break;
default:
flowDir = incomingDirection; // + Math.PI; // From side to oposite side
break;
}
flowDir = flowDir % (2 * Math.PI);
log("Returned output flow direction:", flowDir);
return flowDir;
}
function canAcceptFlowFromDirection(tile, incomingDirection) {
var normalizedIncoming = (incomingDirection + Math.PI) % (2 * Math.PI);
var tileRotation = tile.normalizeRotation(tile.pipeContainer.rotation);
log("Checking if tile can accept flow. Tile type:", tile.type, "Tile rotation:", tileRotation, " previous tile at:", incomingDirection, " => Incoming flow dir:", normalizedIncoming);
var angleDiff = null;
switch (tile.type) {
case TileFormat.TYPES.START:
log("No => Tile type is START. Cannot accept flow.");
return false;
case TileFormat.TYPES.END:
angleDiff = (normalizedIncoming - tileRotation - Math.PI / 2) % (2 * Math.PI);
log("Yes => Tile type is END.");
return angleDiff < 0.1;
case TileFormat.TYPES.VERTICAL:
angleDiff = Math.abs(normalizedIncoming - Math.PI / 2) % (2 * Math.PI);
log("Yes => Tile type is VERTICAL");
return angleDiff < 0.1 || Math.abs(angleDiff - Math.PI) < 0.1;
case TileFormat.TYPES.HORIZONTAL:
angleDiff = normalizedIncoming % (2 * Math.PI);
log("Yes => Tile type is HORIZONTAL");
return angleDiff < 0.1 || Math.abs(angleDiff - Math.PI) < 0.1;
case TileFormat.TYPES.CORNER:
angleDiff = (normalizedIncoming - tileRotation - Math.PI) % (2 * Math.PI);
log("Yes => Tile type is CORNER.");
return angleDiff < 0.1 || Math.abs(angleDiff - Math.PI / 2) < 0.1;
default:
log("No => Tile type is unknown. Cannot accept flow.");
return false;
}
}
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) {
log("animate tile:", tile);
if (tile && tile.baseTile) {
tile.baseTile.alpha = 1;
LK.setInterval(function () {
if (tile.baseTile.alpha > 0) {
tile.baseTile.alpha -= alphaIncrement;
}
}, 30);
}
});
});
var soilAnimation = LK.setInterval(function () {
if (gridBoardSoil.alpha < 1) {
gridBoardSoil.alpha += alphaIncrement;
} else {
LK.clearInterval(soilAnimation);
growGrass.visible = true;
// Spawn a Flower in each grid cell
for (var i = 0; i < puzzleManager.gridSize; i++) {
for (var j = 0; j < puzzleManager.gridSize; j++) {
var x = i * tileSize + gridBoard.x - gridBoard.width / 2 + tileSize / 2 + boardOffsetX;
var y = j * tileSize + gridBoard.y - gridBoard.height / 2 + tileSize / 2 + boardOffsetY;
var flower = new Flower(puzzleManager.currentLevel, x, y);
flowers.push(flower);
game.addChild(flower);
}
}
// 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);
}
}, 80); // Adjust the interval for desired speed
}
}, 30); // 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;
gridBoardSoil.y = 2732 / 2;
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(game);
// 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
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
// Define a simple tween function to animate the logo
function simpleTween(target, properties, config) {
var startValues = {};
var endValues = properties;
var duration = config.duration || 1000;
var easing = config.easing || function (t) {
return t;
};
var startTime = Date.now();
for (var prop in endValues) {
startValues[prop] = target[prop];
}
function animate() {
var currentTime = Date.now();
var time = Math.min(1, (currentTime - startTime) / duration);
var easedTime = easing(time);
for (var prop in endValues) {
target[prop] = startValues[prop] + (endValues[prop] - startValues[prop]) * easedTime;
}
if (time < 1) {
LK.setTimeout(animate, 16); // Approximately 60 FPS
} else if (config.onFinish) {
config.onFinish();
}
}
animate();
}
// Use the simpleTween function to animate the logo
simpleTween(logo, {
x: 2048 / 2,
// Center horizontally
y: 2732 / 2 - 50 // Center vertically with offset
}, {
duration: 1000,
easing: function easing(t) {
return t * (2 - t);
} // Simple ease-out 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
log("Entering New Round State");
if (puzzleManager) {
puzzleManager.initPuzzle();
}
// 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
log("Entering Playing State");
isPlaying = true;
}
function handlePlayingLoop() {
// Update game logic
if (puzzleManager) {
puzzleManager.grid.forEach(function (row) {
row.forEach(function (tile) {
if (tile) {
tile.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
log("Entering Score State");
levelText.visible = true;
levelText.text = "Level Complete!\nTap to continue";
}
function handleScoreLoop() {
// Update any score animations
if (puzzleManager) {
puzzleManager.grid.forEach(function (row) {
row.forEach(function (tile) {
if (tile) {
tile.update();
}
});
});
}
}
function cleanScoreState() {
levelText.visible = false;
}
function changeGameState(newState) {
// Clean up current state
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) {
log("Down at ", x, y);
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;
log("Move at ", x, y, " => dx,dy: ", deltaX, deltaY);
// 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)) {
// Allow some vertical drag for horizontal moves
direction = deltaX > 0 ? 'right' : 'left';
} else if (Math.abs(deltaY) > Math.abs(deltaX)) {
// Allow some horizontal drag for vertical moves
direction = deltaY > 0 ? 'down' : 'up';
}
log("=> Move Tile to direction:", direction);
puzzleManager.moveTile(direction);
isMouseDown = false; // Reset after move
}
};
game.up = function (x, y, obj) {
isMouseDown = false;
if (currentState === GAME_STATE.PLAYING && puzzleManager) {
log("Up at ", x, y);
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();
}
}
}
// Tile Format Utilities
var TileFormat = {
// Constants
FIXED: 'F',
MOBILE: 'M',
TYPES: {
START: 'S',
END: 'E',
VERTICAL: 'V',
HORIZONTAL: 'H',
CORNER: 'C',
CROSS: 'X',
BLANK: 'B'
},
// Parse a tile string into its components
parse: function parse(tileStr) {
if (!tileStr || tileStr === "") {
return null;
}
var parts = tileStr.split('-');
if (parts.length !== 3) {
log("ERROR !!! Invalid tile format:", tileStr);
return null;
}
return {
fixed: parts[0] === this.FIXED,
type: parts[1],
rotation: parseInt(parts[2]) * (Math.PI / 2) // Convert to radians
};
},
// Create a tile string from components
create: function create(fixed, type, rotationIndex) {
return "".concat(fixed ? this.FIXED : this.MOBILE, "-").concat(type, "-").concat(rotationIndex);
},
// Convert old tile type to new format
convertOldType: function convertOldType(oldType) {
switch (oldType) {
case 'start':
return this.TYPES.START;
case 'end':
return this.TYPES.END;
case 'straightPipeV':
return this.TYPES.VERTICAL;
case 'straightPipeH':
return this.TYPES.HORIZONTAL;
case 'cornerPipe':
return this.TYPES.CORNER;
default:
return this.TYPES.BLANK;
}
},
// Convert rotation in radians to index (0-3)
getRotationIndex: function getRotationIndex(radians) {
if (typeof radians !== 'number') {
return 0;
}
return Math.round(radians % (2 * Math.PI) / (Math.PI / 2)) % 4;
},
// Convert old level format to new format
convertOldLevel: function convertOldLevel(oldLevel) {
var newGrid = [];
for (var row = 0; row < 4; row++) {
newGrid[row] = [];
for (var col = 0; col < 4; col++) {
var oldTile = oldLevel.tiles[row][col];
if (!oldTile) {
newGrid[row][col] = "";
continue;
}
var isFixed = oldLevel.fixedTiles && oldLevel.fixedTiles.includes("".concat(row, ",").concat(col));
var type = this.convertOldType(oldTile);
var rotation = oldLevel.rotations["".concat(row, ",").concat(col)] || 'up';
var rotationIndex = this.getRotationIndex(rotation);
newGrid[row][col] = this.create(isFixed, type, rotationIndex);
}
}
return newGrid;
}
};
// Update tile creation to use new format
function createTile(tileStr, row, col) {
if (!tileStr || tileStr === "") {
return null;
}
var tileData = TileFormat.parse(tileStr);
if (!tileData) {
return null;
}
var tile = new Tile();
tile.type = tileData.type;
tile.fixed = tileData.fixed;
tile.gridRow = row;
tile.gridCol = col;
// Set type and create pipe graphics
tile.setType(tileData.type, row, col, tileData.fixed);
// Set initial rotation
tile.setRotation(tileData.rotation);
// Set position
tile.updatePosition(row, col);
return tile;
}
var levelConfigs = {
1: [["F-S-0", "", "", ""], ["F-V-0", "", "", ""], ["F-V-0", "", "M-H-0", ""], ["F-C-1", "F-H-0", "", "F-E-1"]],
2: [["", "M-V-0", "F-E-0", ""], ["", "M-C-0", "F-V-0", ""], ["", "", "", ""], ["F-S-3", "F-H-0", "", ""]],
3: [["F-C-2", "", "", "M-V-0"], ["F-C-1", "F-E-1", "", "F-H-0"], ["", "", "", ""], ["", "", "F-V-0", "F-S-1"]]
};
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