What could be the reason for the malfunction of the "includes" function in my JavaScript snake game

As a beginner in JavaScript, I've been learning CSS and HTML as well. I decided to practice my skills by creating a snake game without following any tutorials. I know my code might not be the best and lacks good practices, but I'm just doing this for fun.

let playerXpos =0;
let playerYpos =0;

let coordArray = [[playerXpos, playerYpos]];

//player movement
document.addEventListener('keydown', (e) => playerMove(e.key));
function playerMove (key) {
    clearInterval(playerRightInterval);
    clearInterval(playerLeftInterval);
    clearInterval(playerUpInterval);
    clearInterval(playerDownInterval);
    switch(key) {
        case "ArrowRight":
            playerRightInterval = setInterval(function () {
                if (playerXpos > 67.5) {deathFunction();} else {
                    playerXpos += 1.5;
                    playerGrowth();
                }
            }, 90);
        break;     
        case "ArrowLeft":
            playerLeftInterval = setInterval(function () {
                if (playerXpos <= 0) {deathFunction();} else {
                    playerXpos -= 1.5;
                    playerGrowth();
                }
            }, 90);
        break;
        case "ArrowDown":
            playerDownInterval = setInterval(function () {
                if (playerYpos > 57.5) {deathFunction();} else {
                    playerYpos += 1.5;
                    playerGrowth();
                }
            }, 90);
            break;
        case "ArrowUp":
            playerUpInterval = setInterval(function () {
                if (playerYpos <= 0) {deathFunction();} else {
                    playerYpos -= 1.5;
                    playerGrowth();
                }
            }, 90);
            break;
    }
}

//player growing & more moving
function playerGrowth () {
    if (coordArray.includes([playerXpos, playerYpos])) {
        console.log("ya dead lol");
    }
    coordArray.unshift([playerXpos, playerYpos]);
    if (playerXpos == appleX && playerYpos == appleY) {
        playerArray.push(document.createElement("div"));
        playerArray[playerArray.length-1].className = "player";
        wholeSnake.appendChild(playerArray[playerArray.length-1]);
        playerArray[playerArray.length-1].style.backgroundColor = colourArray[(playerArray.length -1)-(Math.floor((playerArray.length -1)/6)*6)];
        appleMove();
    } else {
        coordArray.pop();
    }
    for (let i=0; i < coordArray.length; i++) {
        playerArray[i].style.marginLeft = coordArray[i][0] + "vh";
        playerArray[i].style.marginTop = coordArray[i][1] + "vh";
    }
}

I've stored the positions of the "snake pieces" in an array and updated them with .unshift and .pop as the snake moves. To check if the snake hits itself, I attempted to see if the next position is already in the coordinate array. However, I'm facing issues with this logic.

The problematic line is right under the comment section "player growing & more moving."

I've been struggling with this problem for a while, any assistance would be greatly appreciated!

Answer №1

if (coordArray.includes([playerXpos, playerYpos])) {

When working with JavaScript, variables can hold different types of values. There are primitive values like numbers and strings, and reference values like objects, functions, and arrays. The distinction lies in how these values are compared. If you try to compare two reference values, even if they have the same data, they will not be considered equal.

3 === 3; // true
[3] === [3]; // false

Think of arrays and objects as containers that hold a label pointing to the memory location of their data. So when you use includes with a new array, it won't work because it's a different reference.

To solve this, you can create a custom function to compare your coordinate data. One option is to use the find method.

For instance:

if (coordArray.find(
  (coords) => 
    coords[0] === playerXpos &&
    coords[1] === playerYpos
) {

This way, you compare the individual x and y coordinates directly, allowing you to search for the desired data effectively.

The find method doesn't return a boolean value like includes does. Instead, it returns either the found element or undefined. In an if condition, both outcomes work since undefined is considered falsy.


EDIT: Another approach is using the some method, which is similar to find but returns a boolean value.

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

Guide to using Ajax to send a form and receive text in response

Check out my code on Fiddle: $("form.signupform").submit(function(e) { e.preventDefault(); var data = $(this).serialize(); var url = $(this).attr("action"); var form = $(this); // Added this line for reference $.post(url, data, function(data) { $(for ...

Transforming the AngularJS $http GET method to OPTION and including custom headers

var users= $resource('http://myapp.herokuapp.com/users', {}); users.get(); The change in the HTTP GET method to OPTION occurred after implementing a header method. var users= $resource('http://myapp.herokuapp.com/users', {}, { get ...

Can you restrict the selection of text to only the current element?

<div class="container"> <div class="item1">text text text in div element 1</div> <div class="item2">text text text in div element 2</div> </div> Is there a way using HTML nodes, CSS, or JavaScript to restrict the select ...

What is the process for configuring environment variables in a React application?

I have set up my React app to run on http://localhost:3000, and now I am looking to configure environment variables for different environments such as development, production, staging, and local. These are the URLs for my React app in various environments ...

Arrange the columns in Angular Material Table in various directions

Is there a way to sort all columns in an Angular material table by descending order, while keeping the active column sorted in ascending order? I have been trying to achieve this using the code below: @ViewChild(MatSort) sort: MatSort; <table matSort ...

Guide on organizing items into rows with 3 columns through iteration

Click on the provided JSFiddle link to view a dropdown menu that filters items into categories. Each item is stored as an object in an array for its respective category. Currently, all items are displayed in one column and I want to divide them into three ...

Indicate specific colors for every link within a force-directed network using networkD3::forceNetwork()

How can we assign different colors to links based on their weight using the networkD3::forceNetwork function in R? For example, using the color Blue for links with a weight greater than 1 and dark for links with a weight less than 1. Here is an example co ...

Nested array in jQuery

Can someone verify the correctness of this array within an array declaration? If it is correct, can someone suggest how I can display or at least alert all the contents in chkArray? var chkArray = { tv_type[],screen_size[],connectivity[],features[]}; va ...

Exploring the ideal scenarios for utilizing propTypes in React

When creating in-house components that require specific props to function properly, I believe it is best to conduct prop requirement checks during testing rather than including propTypes in the production code. This is especially important for components t ...

The jQuery selector is unable to locate the IMG element using its unique ID

I'm experiencing an issue with a webpage that includes the following code snippet: <img class="img-qrcode" id="img_123.000.00.01" src="http://localhost:7777/data/code_img\123.000.00.01.png" alt="./data/code_img\123.000.00.01. ...

Utilizing Regular Expressions in Express.js Routes

Is there a way to extract a specific value from my URL using Express? For example, my URL structure is as follows: host/:value.schema I need to retrieve the value from this URL. Here's an example: host/horse.schema (In this case, the value wo ...

Incorrectly loading static images in React SSR

I am currently working on a React SSR app and my folder structure looks like this: https://i.sstatic.net/RA2H2.png My static express middleware successfully handles static files and images in the tag on the client side: https://i.sstatic.net/Zhzf2.png ...

Having trouble fetching data using $http and promises in AngularJS

I'm having trouble connecting to my RESTful API within my AngularJS application. Despite my efforts, I'm not seeing any data being displayed on the screen. It seems like I might be misunderstanding the usage of $http with promises. Any suggestio ...

After employing URLSession.shared.dataTask, my JSON format was altered by an apple

I am new to using Swift 3. I am attempting to transfer data between a MySQL server and an iOS device by establishing a connection using URLSession.shared.dataTask. However, I have encountered an issue with the data format. The format shown on the web: [{ ...

Issue with the demo code for Vue Stripe Checkout

As I delve into the world of Vue-Stripe-Checkout, I encountered a snag right from the start with the demo code provided. The issue arises when utilizing the Vue Stripe Elements component. Has anyone else experienced this problem? There are no errors displa ...

Using the defer attribute on my script tag has caused a delay in loading my script due to its

Whenever I include the defer and async attributes in my <script src="/all.js" async defer></script> tags, the script within the HTML page stops functioning properly due to jQuery being loaded with defer as well. To work around this issue, I hav ...

Having trouble with implementing the Drag API Function alongside Javascript Arrow Functions?

I've searched extensively for a similar question but couldn't find one, so I hope this is not a duplicate. Recently, I created a factory function to assist me with drag and drop functionality in my current project. However, I noticed varied beha ...

Update picture using Vanilla Javascript for mobile display

I am looking to change my logo color to white when viewed on mobile devices. Currently, I have the following code for changing the logo on scroll using vanilla JavaScript. The code toggles between a dark and light logo based on the scroll position. Howev ...

Visitors may not immediately notice the CSS/JavaScript modifications in their browsers

Currently, I am working on a web application utilizing Spring MVC and Hibernate, deploying it on Apache Tomcat 8. Most of my users access the app using Google Chrome. However, I have encountered an issue where whenever I update the CSS or JavaScript files ...

Ruby is unable to add data to a JSON file

I've been attempting to append a JSON object to an existing JSON file, but I'm having trouble finding a solution. I've searched through StackOverflow and Google, but I can't seem to find an answer. Here is the code I'm currently us ...