/****
* Classes
****/
var Background = Container.expand(function () {
var self = Container.call(this);
var bgGraphics = self.attachAsset('background', {
anchorX: 0.5,
anchorY: 0.5
});
self.speed = -1;
self.update = function () {
self.x += self.speed;
if (self.x <= -2048) {
self.x = 2048;
}
};
});
//<Assets used in the game will automatically appear here>
// Define the FlappyBird class
var FlappyBird = Container.expand(function () {
var self = Container.call(this);
// Create and attach the bird asset
var birdGraphics = self.attachAsset('bird', {
anchorX: 0.5,
anchorY: 0.5
});
self.velocity = 0;
self.gravity = 0.5;
self.lift = -10;
// Update function for the bird
self.update = function () {
self.velocity += self.gravity;
self.y += self.velocity;
// Prevent the bird from going off the screen
if (self.y > 2732 - birdGraphics.height / 2) {
self.y = 2732 - birdGraphics.height / 2;
self.velocity = 0;
}
if (self.y < birdGraphics.height / 2) {
self.y = birdGraphics.height / 2;
self.velocity = 0;
}
};
// Function to make the bird jump
self.jump = function () {
self.velocity = self.lift;
LK.getSound('jump').play();
};
});
var Pipe = Container.expand(function () {
var self = Container.call(this);
var pipeGraphics = self.attachAsset('pipe', {
anchorX: 0.5,
anchorY: 0.5
});
self.speed = -5;
self.update = function () {
self.x += self.speed;
if (self.x < -pipeGraphics.width / 2) {
self.destroy();
}
};
});
/****
* Initialize Game
****/
var game = new LK.Game({
backgroundColor: 0x87CEEB // Init game with sky blue background
});
/****
* Game Code
****/
// Initialize game variables
var bird;
var score = 0;
var scoreTxt;
var pipes = [];
function createPipe() {
var pipe = new Pipe();
pipe.x = 2048;
var pipeGraphics = LK.getAsset('pipe', {});
pipe.y = Math.random() < 0.5 ? 0 : 2732 - pipeGraphics.height;
pipes.push(pipe);
game.addChild(pipe);
}
// Function to handle game over
function gameOver() {
LK.effects.flashScreen(0xff0000, 1000);
LK.showGameOver();
}
// Initialize the background
var background1 = new Background();
background1.x = 2048 / 2;
background1.y = 2732 / 2;
game.addChild(background1);
var background2 = new Background();
background2.x = 2048 + 2048 / 2;
background2.y = 2732 / 2;
game.addChild(background2);
// Initialize the bird
bird = new FlappyBird();
bird.x = 2048 / 4;
bird.y = 2732 / 2;
game.addChild(bird);
// Initialize the score text
scoreTxt = new Text2('0', {
size: 150,
fill: "#ffffff"
});
scoreTxt.anchor.set(0.5, 0);
LK.gui.top.addChild(scoreTxt);
// Set up the game update function
game.update = function () {
background1.update();
background2.update();
bird.update();
for (var i = pipes.length - 1; i >= 0; i--) {
pipes[i].update();
if (bird.intersects(pipes[i])) {
gameOver();
}
if (pipes[i].x < -pipes[i].width / 2) {
pipes.splice(i, 1);
}
}
if (LK.ticks % 90 == 0) {
createPipe();
}
};
// Set up the game down event to make the bird jump
game.down = function (x, y, obj) {
bird.jump();
};