/**** 
* Classes
****/ 
// Food Class
var Food = Container.expand(function () {
	var self = Container.call(this);
	var foodGraphics = self.attachAsset('food', {
		anchorX: 0.5,
		anchorY: 0.5
	});
});
// Assets are automatically created based on usage in the code.
// Snake Segment Class
var SnakeSegment = Container.expand(function () {
	var self = Container.call(this);
	var segmentGraphics = self.attachAsset('snakeSegment', {
		anchorX: 0.5,
		anchorY: 0.5
	});
	// Method to check if the next move is valid
	self.isValidMove = function (nextX, nextY) {
		// Check if the next move would result in the snake's head moving onto one of its body segments
		for (var i = 0; i < snake.length; i++) {
			if (snake[i].x === nextX && snake[i].y === nextY) {
				return false;
			}
		}
		return true;
	};
});
/**** 
* Initialize Game
****/ 
var game = new LK.Game({
	backgroundColor: 0x000000 // Init game with black background 
});
/**** 
* Game Code
****/ 
// Global variables
var snake = [];
var food;
var direction = {
	x: 0,
	y: -1
}; // Initial direction: up
var nextDirection = {
	x: 0,
	y: -1
};
var snakeSpeed = 5; // How many frames before the snake moves one block
var frameCounter = 0;
var gridSize = 100;
var score = 0;
// Initialize snake
function initSnake() {
	var initialLength = 5;
	for (var i = 0; i < initialLength; i++) {
		var segment = game.addChild(new SnakeSegment());
		segment.x = 1024; // Center of the screen width
		segment.y = 1366 + i * gridSize; // Center of the screen height, plus offset for initial length
		snake.push(segment);
	}
}
// Initialize food
function placeFood() {
	if (food) {
		food.destroy();
	} // Remove old food if it exists
	food = game.addChild(new Food());
	// Random position for food
	do {
		food.x = Math.floor(Math.random() * (2048 / gridSize)) * gridSize + gridSize / 2;
		food.y = Math.floor(Math.random() * (2732 / gridSize)) * gridSize + gridSize / 2;
	} while (food.x > 2048 - 3 * gridSize && food.y < 3 * gridSize); // Prevent food from overlapping with the scoreboard
}
// Check collision with food
function checkFoodCollision() {
	if (snake[0].intersects(food)) {
		score += 10; // Increase score
		scoreText.setText('Score: ' + score); // Update score text
		growSnake(); // Grow snake
		placeFood(); // Place new food
	}
}
// Grow snake by adding a segment at the end
function growSnake() {
	var lastSegment = snake[snake.length - 1];
	var newSegment = game.addChild(new SnakeSegment());
	newSegment.x = lastSegment.x - direction.x * gridSize;
	newSegment.y = lastSegment.y - direction.y * gridSize;
	snake.push(newSegment);
}
// Check collision with walls or self
function checkCollision() {
	var head = snake[0];
	// Wall collision
	if (head.x < 0 || head.x > 2048 || head.y < 0 || head.y > 2732) {
		LK.showGameOver();
	}
	// Self collision
	for (var i = 4; i < snake.length; i++) {
		if (head.intersects(snake[i]) && i != snake.length - 1) {
			LK.showGameOver();
		}
	}
}
// Move snake
function moveSnake() {
	// Move each segment to the position of the previous segment
	for (var i = snake.length - 1; i > 0; i--) {
		snake[i].x = snake[i - 1].x;
		snake[i].y = snake[i - 1].y;
	}
	// Move head in the current direction
	snake[0].x += direction.x * gridSize;
	snake[0].y += direction.y * gridSize;
}
// Game tick
LK.on('tick', function () {
	frameCounter++;
	if (frameCounter >= snakeSpeed) {
		frameCounter = 0;
		direction = nextDirection; // Update direction
		moveSnake();
		checkFoodCollision();
		checkCollision();
	}
});
// Touch controls
game.on('down', function (obj) {
	var touchPos = obj.event.getLocalPosition(game);
	// Calculate touch direction relative to snake head
	var diffX = touchPos.x - snake[0].x;
	var diffY = touchPos.y - snake[0].y;
	// If snake is moving horizontally, prioritize vertical movements
	if (direction.x !== 0) {
		if (diffY < 0 && direction.y !== 1) {
			nextDirection = {
				x: 0,
				y: -1
			}; // Move up if not moving down
		} else if (diffY > 0 && direction.y !== -1) {
			nextDirection = {
				x: 0,
				y: 1
			}; // Move down if not moving up
		}
	}
	// If snake is moving vertically, prioritize horizontal movements
	if (direction.y !== 0) {
		if (diffX > 0 && direction.x !== -1) {
			nextDirection = {
				x: 1,
				y: 0
			}; // Move right if not moving left
		} else if (diffX < 0 && direction.x !== 1) {
			nextDirection = {
				x: -1,
				y: 0
			}; // Move left if not moving right
		}
	}
	// If the snake is not already moving in the determined direction
	var nextX = snake[0].x + nextDirection.x * gridSize;
	var nextY = snake[0].y + nextDirection.y * gridSize;
	if (!snake[0].isValidMove(nextX, nextY)) {
		// If the next move is not valid, keep the current direction
		nextDirection = {
			x: direction.x,
			y: direction.y
		};
	}
});
// Initialize game elements
initSnake();
placeFood();
// Create a new Text2 object to display the score
var scoreText = new Text2('Score: 0', {
	size: 50,
	fill: "#ffffff"
});
scoreText.anchor.set(1, 0);
LK.gui.topRight.addChild(scoreText); /**** 
* Classes
****/ 
// Food Class
var Food = Container.expand(function () {
	var self = Container.call(this);
	var foodGraphics = self.attachAsset('food', {
		anchorX: 0.5,
		anchorY: 0.5
	});
});
// Assets are automatically created based on usage in the code.
// Snake Segment Class
var SnakeSegment = Container.expand(function () {
	var self = Container.call(this);
	var segmentGraphics = self.attachAsset('snakeSegment', {
		anchorX: 0.5,
		anchorY: 0.5
	});
	// Method to check if the next move is valid
	self.isValidMove = function (nextX, nextY) {
		// Check if the next move would result in the snake's head moving onto one of its body segments
		for (var i = 0; i < snake.length; i++) {
			if (snake[i].x === nextX && snake[i].y === nextY) {
				return false;
			}
		}
		return true;
	};
});
/**** 
* Initialize Game
****/ 
var game = new LK.Game({
	backgroundColor: 0x000000 // Init game with black background 
});
/**** 
* Game Code
****/ 
// Global variables
var snake = [];
var food;
var direction = {
	x: 0,
	y: -1
}; // Initial direction: up
var nextDirection = {
	x: 0,
	y: -1
};
var snakeSpeed = 5; // How many frames before the snake moves one block
var frameCounter = 0;
var gridSize = 100;
var score = 0;
// Initialize snake
function initSnake() {
	var initialLength = 5;
	for (var i = 0; i < initialLength; i++) {
		var segment = game.addChild(new SnakeSegment());
		segment.x = 1024; // Center of the screen width
		segment.y = 1366 + i * gridSize; // Center of the screen height, plus offset for initial length
		snake.push(segment);
	}
}
// Initialize food
function placeFood() {
	if (food) {
		food.destroy();
	} // Remove old food if it exists
	food = game.addChild(new Food());
	// Random position for food
	do {
		food.x = Math.floor(Math.random() * (2048 / gridSize)) * gridSize + gridSize / 2;
		food.y = Math.floor(Math.random() * (2732 / gridSize)) * gridSize + gridSize / 2;
	} while (food.x > 2048 - 3 * gridSize && food.y < 3 * gridSize); // Prevent food from overlapping with the scoreboard
}
// Check collision with food
function checkFoodCollision() {
	if (snake[0].intersects(food)) {
		score += 10; // Increase score
		scoreText.setText('Score: ' + score); // Update score text
		growSnake(); // Grow snake
		placeFood(); // Place new food
	}
}
// Grow snake by adding a segment at the end
function growSnake() {
	var lastSegment = snake[snake.length - 1];
	var newSegment = game.addChild(new SnakeSegment());
	newSegment.x = lastSegment.x - direction.x * gridSize;
	newSegment.y = lastSegment.y - direction.y * gridSize;
	snake.push(newSegment);
}
// Check collision with walls or self
function checkCollision() {
	var head = snake[0];
	// Wall collision
	if (head.x < 0 || head.x > 2048 || head.y < 0 || head.y > 2732) {
		LK.showGameOver();
	}
	// Self collision
	for (var i = 4; i < snake.length; i++) {
		if (head.intersects(snake[i]) && i != snake.length - 1) {
			LK.showGameOver();
		}
	}
}
// Move snake
function moveSnake() {
	// Move each segment to the position of the previous segment
	for (var i = snake.length - 1; i > 0; i--) {
		snake[i].x = snake[i - 1].x;
		snake[i].y = snake[i - 1].y;
	}
	// Move head in the current direction
	snake[0].x += direction.x * gridSize;
	snake[0].y += direction.y * gridSize;
}
// Game tick
LK.on('tick', function () {
	frameCounter++;
	if (frameCounter >= snakeSpeed) {
		frameCounter = 0;
		direction = nextDirection; // Update direction
		moveSnake();
		checkFoodCollision();
		checkCollision();
	}
});
// Touch controls
game.on('down', function (obj) {
	var touchPos = obj.event.getLocalPosition(game);
	// Calculate touch direction relative to snake head
	var diffX = touchPos.x - snake[0].x;
	var diffY = touchPos.y - snake[0].y;
	// If snake is moving horizontally, prioritize vertical movements
	if (direction.x !== 0) {
		if (diffY < 0 && direction.y !== 1) {
			nextDirection = {
				x: 0,
				y: -1
			}; // Move up if not moving down
		} else if (diffY > 0 && direction.y !== -1) {
			nextDirection = {
				x: 0,
				y: 1
			}; // Move down if not moving up
		}
	}
	// If snake is moving vertically, prioritize horizontal movements
	if (direction.y !== 0) {
		if (diffX > 0 && direction.x !== -1) {
			nextDirection = {
				x: 1,
				y: 0
			}; // Move right if not moving left
		} else if (diffX < 0 && direction.x !== 1) {
			nextDirection = {
				x: -1,
				y: 0
			}; // Move left if not moving right
		}
	}
	// If the snake is not already moving in the determined direction
	var nextX = snake[0].x + nextDirection.x * gridSize;
	var nextY = snake[0].y + nextDirection.y * gridSize;
	if (!snake[0].isValidMove(nextX, nextY)) {
		// If the next move is not valid, keep the current direction
		nextDirection = {
			x: direction.x,
			y: direction.y
		};
	}
});
// Initialize game elements
initSnake();
placeFood();
// Create a new Text2 object to display the score
var scoreText = new Text2('Score: 0', {
	size: 50,
	fill: "#ffffff"
});
scoreText.anchor.set(1, 0);
LK.gui.topRight.addChild(scoreText);