Javascript Snake: I am having trouble making my snake's tail grow longer

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);
}

Answer №1

Within the eat() function, there is a section where you create a new Snake object and assign it to a variable called tail. However, it seems that this newly created object is not being utilized further in your code. I would suggest adding it to your snakes array, which presumably holds all the segments of the snake.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring the basics of caching in Node.js and Express: a beginner's

Picture an application with numerous users and small sets of data (up to 10 name/value pairs), but the process to access this data involves complex calculations. The concept is based on a system with a 'history' state that is crucial for obtaini ...

NextJS: When attempting to serialize the `function` as JSON, an error occurs as it is not a JSON serializable data type

In my Firestore database, I have a collection named "mentor" that contains documents with three fields: "name", "email", and "linkedin". My goal is to fetch all the documents from this collection and pass them as props so that I can render their fields on ...

AngularJS Datepicker - calendar dropdown does not update when the model changes

I've been facing a challenge with the AngularJs datepicker in my project for some time now. Within my application, users have the option to either manually select a date using the calendar or click on "This Month" to automatically set the date to the ...

Regular expression: match all content up to a certain word(s)

I have two different versions of a string that look like this: The Student's Companion *Author: Alcock, Pete;May, Margaret;Wright, Sharon*MIL EAN/ISBN: 9781283333115 Java Programming: Java Expert*Author:Sarang, Poornachandra*MIL EAN/ISBN: 978128011 ...

Update your Selenium WebDriver Manager using npm

When attempting to update the selenium webdriver using the "webdriver-manager", an error occurred: Error: Got error Error: read ECONNRESET from https://selenium-release.storage.googleapis.com/2.48/selenium-server-standalone-2.48.2.jar Error: Got error Err ...

How can you style a two-item list in Material-UI React to display the items side by side?

I have a list that contains two items: 'label' and 'value'. This is the current layout: https://i.stack.imgur.com/HufX7.png How can I rearrange the items on the right to be positioned next to the label on the left? https://i.stack.im ...

Is there a way to access or delete a randomly generated document ID in Firestore?

Need help with code to delete an item (current method not working) const docRef = firebase.firestore().collection('users').doc(firebase.auth().currentUser.uid) docRef.collection('tasks').doc(this.task.id).delete() ...

Angular 5's external JavaScript library

After thoroughly researching this subject, I find myself still lacking comprehension. An example may be the key to understanding. As a newcomer to Angular, my goal is to create a mathematical application for mobile using Ionic. Despite investing two weeks ...

How to calculate the difference in months between two dates using JavaScript

Is there a way to calculate the number of months between two dates taking into account specific conditions, such as when the dates are not exact and may have different day counts? Here is an example using the moment library: var date1 = moment('202 ...

Save the HTML elements in an object and then use the ng-include directive to include the template

Currently experimenting with this code snippet: var CustomTable = function($elem) { this.properties.element = $elem; this.initialize(); }; CustomTable.prototype.PROPERTIE = { secondElement: $('.second') // this element ...

Unlocking the potential: Clicking on all ng-if elements with matching text using Chrome console

I am currently trying to determine how to automatically click on all elements that have a specific state. The page appears to be built using Angular, although I am unsure of the exact version being used. My approach involves using the console in Chrome t ...

JavaScript code to obscure

My goal is to create a JavaScript function where the "costCenter" object starts with visibility set to false. However, when the user clicks on the "computer" item in a dropdown list, the visibility of "costCenter" should change to true. This is my current ...

Steps for eliminating an element using jQuery from a variable filled with HTML code

I'm developing a forum where users have the ability to quote other users' comments. When a user clicks on "quote" for a comment, it captures the HTML of that comment and displays it in a box that says Quote: Original post by a member, similar t ...

Utilizing Asynchronous Values in a Different JavaScript Function

Currently delving into the world of destructuring arrays in Javascript, I find myself faced with the challenge of accessing these variables in other functions. I attempted to retrieve the array by calling a function and then using console.log(thermostatAr ...

The 'substr' property is not found in the type 'string | string[]'

Recently, I had a JavaScript code that was working fine. Now, I'm in the process of converting it to TypeScript. var ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress; if (ip.substr(0, 7) == "::ffff ...

What could be the reason for the selection box in my form not changing the items when togg

I'm having an issue with my form selection box code that used to work but is now not functioning properly. Could someone please help me identify where the error lies? Essentially, I have a form with the ID #main and a select box named #chart-type. Th ...

`Storing modified PDF containing interactive form elements using integrated Chrome viewer and transferring it to a remote server`

Our current setup utilizes the default embedded Chrome PDF viewer to showcase a PDF document with interactive form fields, enabling users to conveniently fill out the form. Once completed, they can click on the download button to save the form with or with ...

Utilizing AngularJS to create bound checkboxes

I am struggling with two checkboxes, one with Data Binding and the other without Data Binding. The code snippet below illustrates this: <html ng-app="notesApp"> <head><title>Notes App</title></head> <body ng-contro ...

react-datepicker displaying error message "Preventing default action not possible within a passive event listener invocation"

I've integrated the react-datepicker library in portal mode. While it functions well on browsers, I encounter an error when using mobile browser mode. An issue arises stating: "Unable to preventDefault inside passive event listener invocation" Des ...

What is the best way to create a dynamic graph in amcharts during runtime?

Below is the code for Multiple Value Axes: In this code, we aim to display a graph using dynamically generated random data. When executed, nothing will happen. <script> var chart; var chartData = []; // generate some random data within a different ...