/****
* Classes
****/
// The assets will be automatically created and loaded by the LK engine based on their usage in the code.
// We will use a fish shape and obstacles in the game.
// Fish class representing the player character
var Fish = Container.expand(function () {
var self = Container.call(this);
var fishGraphics = self.attachAsset('fish', {
anchorX: 0.5,
anchorY: 0.5
});
self.gravity = 0.5;
self.lift = -10;
self.velocity = 0;
// Update function to apply gravity and lift
self.update = function () {
self.velocity += self.gravity;
self.y += self.velocity;
// Prevent fish from going off the top of the screen
if (self.y < 0) {
self.y = 0;
self.velocity = 0;
}
};
// Function to make the fish jump
self.jump = function () {
self.velocity = self.lift;
};
});
// Obstacle class representing the obstacles the fish must avoid
var Obstacle = Container.expand(function () {
var self = Container.call(this);
var obstacleGraphics = self.attachAsset('obstacle', {
anchorX: 0.5,
anchorY: 0.5
});
self.speed = -5;
// Update function to move the obstacle
self.update = function () {
self.x += self.speed;
// Remove obstacle if it goes off screen
if (self.x < -obstacleGraphics.width) {
self.destroy();
}
};
});
/****
* Initialize Game
****/
var game = new LK.Game({
backgroundColor: 0x87CEEB // Light blue background to represent the sky
});
/****
* Game Code
****/
// Initialize game variables
var fish = game.addChild(new Fish());
fish.x = 2048 / 4; // Start fish at 1/4th of the screen width
fish.y = 2732 / 2; // Center fish vertically
var obstacles = [];
var score = 0;
var scoreTxt = new Text2('0', {
size: 150,
fill: "#ffffff"
});
scoreTxt.anchor.set(0.5, 0);
LK.gui.top.addChild(scoreTxt);
// Function to create a new obstacle
function createObstacle() {
var obstacle = new Obstacle();
obstacle.x = 2048;
obstacle.y = Math.random() * 2732; // Random vertical position
obstacles.push(obstacle);
game.addChild(obstacle);
}
// Handle game updates
game.update = function () {
fish.update();
// Check for collisions with obstacles
for (var i = obstacles.length - 1; i >= 0; i--) {
obstacles[i].update();
if (fish.intersects(obstacles[i])) {
LK.effects.flashScreen(0xff0000, 1000);
LK.showGameOver();
}
// Remove off-screen obstacles
if (obstacles[i].x < -obstacles[i].width) {
obstacles[i].destroy();
obstacles.splice(i, 1);
score++;
scoreTxt.setText(score);
}
}
// Create new obstacles periodically
if (LK.ticks % 120 == 0) {
createObstacle();
}
// Check if fish falls below the screen
if (fish.y > 2732) {
LK.effects.flashScreen(0xff0000, 1000);
LK.showGameOver();
}
};
// Handle touch events to make the fish jump
game.down = function (x, y, obj) {
fish.jump();
};