Code edit (1 edits merged)
Please save this source code
Code edit (5 edits merged)
Please save this source code
User prompt
Please fix the bug: 'Uncaught TypeError: Cannot read properties of undefined (reading '0')' in or related to this line: 'if (self.grid[row] && self.grid[row][col]) {' Line Number: 612
User prompt
Please fix the bug: 'Uncaught TypeError: Cannot read properties of undefined (reading '0')' in or related to this line: 'var normalizedIncoming = getFlowDirection(self.grid[row][col], incomingDirection);' Line Number: 612
Code edit (3 edits merged)
Please save this source code
User prompt
Please fix the bug: 'requestAnimationFrame is not a function' in or related to this line: 'requestAnimationFrame(animate);' Line Number: 1683
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: 1662 ↪💡 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 (6 edits merged)
Please save this source code
User prompt
Please fix the bug: 'Uncaught TypeError: self.getFlowDirection is not a function' in or related to this line: 'var normalizedIncoming = self.getFlowDirection(self, incomingDirection);' Line Number: 614
Code edit (1 edits merged)
Please save this source code
Code edit (3 edits merged)
Please save this source code
User prompt
in getFlowDirection, log type, rotation , normalized rotation and returned direction
Code edit (2 edits merged)
Please save this source code
User prompt
Please fix the bug: 'Uncaught TypeError: TypeError is not a constructor' in or related to this line: '_iterator.f();' Line Number: 1256
User prompt
Please fix the bug: 'Uncaught TypeError: TypeError is not a constructor' in or related to this line: '_iterator.f();' Line Number: 1256
User prompt
Please fix the bug: 'Uncaught TypeError: TypeError is not a constructor' in or related to this line: '_iterator.f();' Line Number: 1256
User prompt
Please fix the bug: 'Uncaught TypeError: TypeError is not a constructor' in or related to this line: '_iterator.f();' Line Number: 1255
User prompt
Analyze then Optimize getNextPositions() function by passing the incoming direction so that you just return one unique next position
User prompt
in ``` if (nextTile.water) { if (nextTile.type === TileFormat.TYPES.VERTICAL) { if (Math.abs(incomingDirection - Math.PI / 2) < 0.1) { nextTile.water.dir = 'tb'; // Top to Bottom } else if (Math.abs(incomingDirection - 3 * Math.PI / 2) < 0.1) { nextTile.water.dir = 'bt'; // Bottom to Top } } else if (nextTile.type === TileFormat.TYPES.HORIZONTAL) { if (Math.abs(incomingDirection) < 0.1) { nextTile.water.dir = 'lr'; // Left to Right } else if (Math.abs(incomingDirection - Math.PI) < 0.1) { nextTile.water.dir = 'rl'; // Right to Left } } } ``` add detailed logs
User prompt
in ``` if (nextTile.water) { if (Math.abs(incomingDirection - Math.PI / 2) < 0.1) { nextTile.water.dir = 'tb'; // Top to Bottom } else if (Math.abs(incomingDirection - 3 * Math.PI / 2) < 0.1) { nextTile.water.dir = 'bt'; // Bottom to Top } else if (Math.abs(incomingDirection) < 0.1) { nextTile.water.dir = 'lr'; // Left to Right } else if (Math.abs(incomingDirection - Math.PI) < 0.1) { nextTile.water.dir = 'rl'; // Right to Left } } ``` differenciate beween horizontal and vertical pipes
Code edit (1 edits merged)
Please save this source code
User prompt
in checkWinCondition, after ``` if (!canAcceptFlowFromDirection(nextTile, incomingDirection)) { log("Tile at row:", nextRow, "col:", nextCol, "cannot accept flow from direction:", incomingDirection); continue; } ``` under the comment `// HERE UPDATE nextTile.waterXXX.dir depending on incomingDirection` implement the UPDATE of nextTile.waterXXX.dir depending on incomingDirection
User prompt
implement "// HERE UPDATE nextTile.waterXXX.dir depending on incomingDirection"
/****
* Plugins
****/
var tween = LK.import("@upit/tween.v1");
/****
* Classes
****/
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 _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';
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, type, rotation) {
var positions = [];
log("getNextPositions called with col:", col, "row:", row, "type:", type, "rotation:", rotation);
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("dx:", dx, "dy:", dy);
log("Calculated positions for START:", positions);
break;
case TileFormat.TYPES.VERTICAL:
positions.push([col, row - 1]); // Up
positions.push([col, row + 1]); // Down
log("Calculated positions for VERTICAL:", positions);
break;
case TileFormat.TYPES.HORIZONTAL:
positions.push([col - 1, row]); // Left
positions.push([col + 1, row]); // Right
log("Calculated positions for HORIZONTAL:", positions);
break;
case TileFormat.TYPES.CORNER:
var angle = rotation % (2 * Math.PI);
if (angle < 0.1 || Math.abs(angle - Math.PI / 2) < 0.1) {
positions.push([col + 1, row]); // Right
positions.push([col, row - 1]); // Up
} else if (Math.abs(angle - Math.PI) < 0.1 || Math.abs(angle - 3 * Math.PI / 2) < 0.1) {
positions.push([col - 1, row]); // Left
positions.push([col, row + 1]); // Down
}
log("Calculated positions for CORNER:", positions);
break;
case TileFormat.TYPES.CROSS:
positions.push([col - 1, row]); // Left
positions.push([col + 1, row]); // Right
positions.push([col, row - 1]); // Up
positions.push([col, row + 1]); // Down
log("Calculated positions for CROSS:", positions);
break;
}
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;
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 ===");
if (Math.abs(incomingDirection - Math.PI / 2) < 0.1) {
nextTile.water.dir = 'tb'; // Top to Bottom
} else if (Math.abs(incomingDirection - 3 * Math.PI / 2) < 0.1) {
nextTile.water.dir = 'bt'; // Bottom to Top
} else if (Math.abs(incomingDirection) < 0.1) {
nextTile.water.dir = 'lr'; // Left to Right
} else if (Math.abs(incomingDirection - Math.PI) < 0.1) {
nextTile.water.dir = 'rl'; // Right to Left
}
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: 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));
var nextPositions = currentTile.getNextPositions(col, row, currentTile.type, normalizedRotation);
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, nextCol - col);
if (!canAcceptFlowFromDirection(nextTile, incomingDirection)) {
log("Tile at row:", nextRow, "col:", nextCol, "cannot accept flow from direction:", incomingDirection);
continue;
}
// HERE UPDATE nextTile.waterXXX.dir depending on incomingDirection
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);
var nextKey = nextRow + "," + nextCol;
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;
var boardY = gridBoard.y - gridBoard.height / 2;
var row = Math.floor((y - boardY) / tileSize);
var col = Math.floor((x - boardX) / tileSize);
log("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();
}
}
};
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();
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
var movingTile = this.grid[oldRow][oldCol];
this.grid[oldRow][oldCol] = null;
this.grid[newRow][newCol] = movingTile;
// Update tile position
movingTile.updatePosition(newRow, newCol);
// Clear selection
this.selectedTile = null;
// Check if puzzle is solved
if (this.checkWinCondition()) {
this.isComplete = true;
this.startWaterFlow();
LK.getSound('levelWon').play();
isPlaying = false;
}
};
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();
}, 1000);
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 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 = 20;
var levelText;
var waterDrops = [];
var waterDropInterval;
var logo;
var puzzleManager;
// Initialize the game
initializeGame();
/****
* Helper Functions
****/
function getFlowDirection(tile) {
var rotation = tile.normalizeRotation(tile.pipeContainer.rotation);
switch (tile.type) {
case TileFormat.TYPES.START:
return rotation;
case TileFormat.TYPES.CORNER:
return (rotation + Math.PI / 2) % (2 * Math.PI);
default:
return rotation;
}
}
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, "Incoming direction:", incomingDirection, "Normalized incoming:", normalizedIncoming, "Tile rotation:", tileRotation);
switch (tile.type) {
case TileFormat.TYPES.START:
log("Tile type is START. Cannot accept flow.");
return false;
case TileFormat.TYPES.END:
var angle = (normalizedIncoming - tileRotation - Math.PI / 2) % (2 * Math.PI);
log("Tile type is END. Calculated angle:", angle);
return angle < 0.1;
case TileFormat.TYPES.VERTICAL:
var angle = Math.abs(normalizedIncoming - Math.PI / 2) % (2 * Math.PI);
log("Tile type is VERTICAL. Calculated angle:", angle);
return angle < 0.1 || Math.abs(angle - Math.PI) < 0.1;
case TileFormat.TYPES.HORIZONTAL:
var angle = normalizedIncoming % (2 * Math.PI);
log("Tile type is HORIZONTAL. Calculated angle:", angle);
return angle < 0.1 || Math.abs(angle - Math.PI) < 0.1;
case TileFormat.TYPES.CORNER:
var angle = (normalizedIncoming - tileRotation - Math.PI) % (2 * Math.PI);
log("Tile type is CORNER. Calculated angle:", angle);
return angle < 0.1 || Math.abs(angle - Math.PI / 2) < 0.1;
default:
log("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) {
if (tile && 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(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
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.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
console.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
console.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
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();
}
}
}
// 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) {
console.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;
// Create base tile graphics
tile.baseTile = tile.attachAsset(tile.fixed ? 'baseTile' : 'baseMobileTile', {
anchorX: 0.5,
anchorY: 0.5,
width: tileSize,
height: tileSize,
tint: 0xFFFFFF
});
// 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