/****
* Classes
****/
// Food class
var Food = Container.expand(function () {
var self = Container.call(this);
var foodGraphic = self.attachAsset('food', {
anchorX: 0.5,
anchorY: 0.5
});
self.respawn = function () {
self.x = Math.random() * 2048;
self.y = Math.random() * 2732;
};
self.respawn();
});
//<Assets used in the game will automatically appear here>
// Snake class
var Snake = Container.expand(function () {
var self = Container.call(this);
self.segments = [];
self.direction = {
x: 1,
y: 0
};
self.speed = 5;
self.grow = false;
self.init = function () {
for (var i = 0; i < 5; i++) {
var segment = self.attachAsset('snakeSegment', {
anchorX: 0.5,
anchorY: 0.5
});
segment.x = 1024 - i * 20;
segment.y = 1366;
self.segments.push(segment);
}
};
self.update = function () {
var head = self.segments[0];
var newX = head.x + self.direction.x * self.speed;
var newY = head.y + self.direction.y * self.speed;
if (self.grow) {
var newSegment = self.attachAsset('snakeSegment', {
anchorX: 0.5,
anchorY: 0.5
});
self.segments.push(newSegment);
self.grow = false;
}
for (var i = self.segments.length - 1; i > 0; i--) {
self.segments[i].x = self.segments[i - 1].x;
self.segments[i].y = self.segments[i - 1].y;
}
head.x = newX;
head.y = newY;
};
self.changeDirection = function (newDirection) {
if ((newDirection.x !== -self.direction.x || newDirection.y !== -self.direction.y) && (newDirection.x !== self.direction.x || newDirection.y !== self.direction.y)) {
self.direction = newDirection;
}
};
self.init();
});
/****
* Initialize Game
****/
var game = new LK.Game({
backgroundColor: 0x000000 //Init game with black background
});
/****
* Game Code
****/
var snake = game.addChild(new Snake());
var food = game.addChild(new Food());
var score = 0;
var scoreTxt = new Text2('0', {
size: 150,
fill: "#ffffff"
});
scoreTxt.anchor.set(0.5, 0);
LK.gui.top.addChild(scoreTxt);
game.update = function () {
snake.update();
// Check for collision with food
if (snake.segments[0].intersects(food)) {
food.respawn();
snake.grow = true;
score += 1;
scoreTxt.setText(score);
}
// Check for collision with self or boundaries
var head = snake.segments[0];
if (head.x < 0 || head.x > 2048 || head.y < 0 || head.y > 2732) {
LK.showGameOver();
}
for (var i = 1; i < snake.segments.length; i++) {
if (head.intersects(snake.segments[i])) {
LK.showGameOver();
}
}
};
game.down = function (x, y, obj) {
var game_position = game.toLocal(obj.global);
var head = snake.segments[0];
if (Math.abs(game_position.x - head.x) > Math.abs(game_position.y - head.y)) {
if (game_position.x > head.x) {
snake.changeDirection({
x: 1,
y: 0
});
} else {
snake.changeDirection({
x: -1,
y: 0
});
}
} else {
if (game_position.y > head.y) {
snake.changeDirection({
x: 0,
y: 1
});
} else {
snake.changeDirection({
x: 0,
y: -1
});
}
}
};