/****
* Classes
****/
// Ball class
var Ball = Container.expand(function () {
var self = Container.call(this);
var ballGraphics = self.attachAsset('ball', {
anchorX: 0.5,
anchorY: 0.5
});
self.speedX = 5;
self.speedY = 5;
self.speed = 10;
self.update = function () {
self.x += self.speedX;
self.y += self.speedY;
};
});
//<Assets used in the game will automatically appear here>
//<Write imports for supported plugins here>
// Paddle class for player and opponent
var Paddle = Container.expand(function () {
var self = Container.call(this);
var paddleGraphics = self.attachAsset('paddle', {
anchorX: 0.5,
anchorY: 0.5
});
self.width = 200;
self.height = 20;
self.update = function () {
// Paddle update logic if needed
};
});
/****
* Initialize Game
****/
var game = new LK.Game({
backgroundColor: 0x006400 //Init game with dark green background
});
/****
* Game Code
****/
// Initialize scores
var playerScore = 0;
var opponentScore = 0;
// Initialize paddles and ball
var playerPaddle = game.addChild(new Paddle());
var opponentPaddle = game.addChild(new Paddle());
var ball = game.addChild(new Ball());
// Position paddles and ball
playerPaddle.x = 2048 / 2;
playerPaddle.y = 2732 - 50;
opponentPaddle.x = 2048 / 2;
opponentPaddle.y = 50;
ball.x = 2048 / 2;
ball.y = 2732 / 2;
// Game update logic
game.update = function () {
// Ball movement
ball.update();
// Ball collision with walls
if (ball.x <= 0 || ball.x >= 2048) {
ball.speedX *= -1;
}
// Ball passes player's paddle
if (ball.y >= 2732) {
opponentScore += 1;
ball.x = 2048 / 2;
ball.y = 2732 / 2;
opponentScoreText.setText(opponentScore.toString());
ball.speedY *= -1;
}
// Ball passes opponent's paddle
if (ball.y <= 0) {
playerScore += 1;
ball.x = 2048 / 2;
ball.y = 2732 / 2;
playerScoreText.setText(playerScore.toString());
ball.speedY *= -1;
}
// Ball collision with paddles
if (ball.intersects(playerPaddle)) {
ball.speedY = -Math.abs(ball.speedY);
} else if (ball.intersects(opponentPaddle)) {
ball.speedY = Math.abs(ball.speedY);
}
// Opponent AI movement
if (ball.x < opponentPaddle.x) {
opponentPaddle.x -= 5;
} else if (ball.x > opponentPaddle.x) {
opponentPaddle.x += 5;
}
};
// Player paddle control
game.move = function (x, y, obj) {
playerPaddle.x = x;
};
// Display scores
var playerScoreText = new Text2(playerScore.toString(), {
size: 150,
fill: 0xFFFFFF
});
var opponentScoreText = new Text2(opponentScore.toString(), {
size: 150,
fill: 0xFFFFFF
});
LK.gui.top.addChild(playerScoreText);
LK.gui.bottom.addChild(opponentScoreText);