I've created a snake game that is almost fully functional. The issue I'm facing is that when the snake eats food, the food changes location but the tail of the snake doesn't grow in size. I suspect that my understanding of arrays might be lacking and I could be implementing it incorrectly.
Below is the code snippet:
setSize(400, 400);
var background = new Rectangle(getWidth(), getHeight());
background.setPosition(0, 0);
background.setColor(Color.black);
add(background);
// ------------------------------------------------
var gameTime = 0;
var snakeX = (Randomizer.nextInt(0, 19)) * 20;
var snakeY = (Randomizer.nextInt(0, 19)) * 20;
var foodX;
var foodY;
var snakeFood = new Rectangle(20, 20);
snakeFood.setColor(Color.red);
var food_eaten = 0;
var snakeSpeed = 20;
var keyLeft = false;
var keyRight = false;
var keyUp = false;
var keyDown = false;
var snake_size = 10;
var snakeHead = new Rectangle(20, 20);
snakeHead.setColor(Color.green);
var snakes = [snakeHead];
// ------------------------------------------------
function start(){
setup();
keyDownMethod(checkKey);
setTimer(counter, 250);
}
function counter(){
gameTime += 0.25;
updateSnake();
}
function setup(){
foodX = (Randomizer.nextInt(0, 19)) * 20;
foodY = (Randomizer.nextInt(0, 19)) * 20;
snakeHead.setPosition(snakeX, snakeY);
add(snakeHead);
snakeFood.setPosition(foodX, foodY);
add(snakeFood);
}
function checkKey(e){
if(e.keyCode == Keyboard.LEFT){
keyRight = false;
keyUp = false;
keyDown = false;
keyLeft = true;
}else if(e.keyCode == Keyboard.RIGHT){
keyLeft = false;
keyUp = false;
keyDown = false;
keyRight = true;
}else if(e.keyCode == Keyboard.UP){
keyRight = false;
keyLeft = false;
keyDown = false;
keyUp = true;
}else if(e.keyCode == Keyboard.DOWN){
keyRight = false;
keyLeft = false;
keyUp = false;
keyDown = true;
}
}
function updateSnake(){
if(foodX == snakeX && foodY == snakeY){
eat();
}
var dirX = 0;
var dirY = 0;
if(keyLeft == true){
dirX = -(snakeSpeed);
dirY = 0;
}else if(keyRight == true){
dirX = snakeSpeed;
dirY = 0;
}else if(keyUp == true){
dirY = -(snakeSpeed);
dirX = 0;
}else if(keyDown == true){
dirY = snakeSpeed;
dirX = 0;
}
// moving the snake head
snakeHead.setPosition(snakeX + dirX, snakeY + dirY);
snakeX += dirX;
snakeY += dirY;
// moving the snake body
if(snakes.length > 1){
for(var i = 0; i < snakes.length; i++){
var curr_body = snakes[i];
curr_body.setPosition(snakeX + dirX, snakeY + dirY);
}
}
}
function eat(){
foodX = (Randomizer.nextInt(0, 19)) * 20;
foodY = (Randomizer.nextInt(0, 19)) * 20;
var tail = new Snake(snakeX, snakeY);
snakeFood.setPosition(foodX, foodY);
}
function Snake(x, y){
var snakeBody = new Rectangle(20, 20);
if(keyLeft == true){
snakeBody.setPosition(x + snake_size, y);
}if(keyRight == true){
snakeBody.setPosition(x - snake_size, y);
}if(keyUp == true){
snakeBody.setPosition(x, y + snake_size);
}if(keyDown == true){
snakeBody.setPosition(x, y - snake_size);
}
snakeBody.setColor(Color.green);
snakes.push(snakeBody);
add(snakeBody);
}