What seems to be the issue with this 3D array not functioning properly?

Game Code Overview

The following code pertains to a grid-based game that I am currently developing, primarily for educational purposes. This game is played on an 8 x 8 grid where the player navigates from one cell to another while encountering obstacles such as walls.

Key Game Variables

The Player Object This object holds the current position of the player within the game.

var player = {
    location: {
        x: 3,
        y: 3
    }
}

The Grid

board[x][y]   // Represents an individual cell in the game

Directions

const NORTH = 0;
const EAST = 1;
const SOUTH = 2;
const WEST = 3;

Obstacles (Walls)

board[x][y][NORTH] = 1;   // Indicates a wall along the north side of the cell

Initial Testing Phase

During the initial testing phase, everything was progressing smoothly while checking if the player moved off the board. However, challenges arose when implementing checks for obstacles like walls.

To begin the testing process, I reset the game board and removed all walls. It appears that this action might be causing an error message:

https://i.sstatic.net/8FStx.png

https://i.sstatic.net/yJ7an.png

Code Snippet

const NORTH = 0;
const EAST = 1;
const SOUTH = 2;
const WEST = 3;

const ROOMWIDTH = 7; // Zero-indexed array
const ROOMHEIGHT = 7;

var moveResonse = {
    valid: 0,
    reason: "",
    helpText: ""
}

var player = {
    location: {
        x: 3,
        y: 3
    }

}

var board = [];

for(var x=0; x<8; x++){
    for(y=0; y<8; y++){
       for(var d=0; d<4;d++){
           board[x][y][d] = 0;
       }  
    }
}


// Initial TESTING: Place a WALL on the west side of cell [3,3]
board[3][3][0] = 0;
board[3][3][1] = 0;
board[3][3][2] = 0;
board[3][3][3] = 1;

// Another WALL added to the east side of cell [2,3]
board[2][3][0] = 0;
board[2][3][1] = 1;
board[2][3][2] = 0;
board[2][3][3] = 0;


function move(direction) {
    // 1. Check if the user is moving outside the board boundaries
    switch (direction) {
        case NORTH:
            if (player.location.y - 1 < 0) {
                moveResponse = {
                    valid: 0,
                    reason: "Out of bounds",
                    helpText: "You can't move NORTH beyond the grid!"
                }
            }
            return moveResponse;
            break;

        case EAST:
            if (player.location.x + 1 > ROOMWIDTH) {
                moveResponse = {
                    valid: 0,
                    reason: "Out of bounds",
                    helpText: "You can't move EAST beyond the grid!"
                }
            }
            return moveResponse;
            break;

        case SOUTH:
            if (player.location.y + 1 > ROOMHEIGHT) {
                moveResponse = {
                    valid: 0,
                    reason: "Out of bounds",
                    helpText: "You can't move SOUTH beyond the grid!"
                }
            }
            return moveResponse;
            break;

        case WEST:
            if (player.location.x - 1 < 0) {
                moveResponse = {
                    valid: 0,
                    reason: "Out of bounds",
                    helpText: "You can't move WEST beyond the grid!"
                }
            }
            return moveResponse;
            break;
    }

    // 2. Check for any obstacles present (walls)
    if(board[player.location.x][player.location.y][direction] == 1){
        moveResponse = {
            valid: 0,
            reason: "Obstacle",
            helpText: "You can't proceed in that direction, there's a WALL blocking your path!"
        }
        return moveResponse;  
    }

}

alert(`Attempting to move WEST: ${move(WEST).helpText}`);

Previously, a question of mine was closed due to being perceived as opinion-based. My intention is not to seek opinions but rather assistance in resolving technical issues. If that entails exploring different approaches, I am open to learning and improving. Your support in this journey is greatly valued.

Visual Representation of Game Board

https://i.sstatic.net/lZxh2.jpg

Answer №1

When creating a board using a 1-dimensional array by declaring var board = [];

for(var x=0; x<8; x++){
    board[x] = [];          // To create an empty array, this line is added
    for(var y=0; y<8; y++){ 
       board[x][y] = [];    // This line creates another empty array
       for(var d=0; d<4;d++){
           board[x][y][d] = 0;
       }  
    }
}

It's important to note that not including var in the second for loop can turn it into a global variable.

Answer №2

https://i.sstatic.net/vM7Hx.png

From what I gather, the error message indicates that the variable board has not been properly set as a three-dimensional array.

A quick glance at your code confirms this suspicion.

var board = [];

for(var x=0; x<8; x++){
    for(y=0; y<8; y++){
       for(var d=0; d<4;d++){
           board[x][y][d] = 0;
       }  
    }
}

The problem lies in defining board as a regular array instead of a 3-d array. This results in the error because the line board[x][y][d] is being interpreted sequentially. Initially, it tries to access board[0], but since board is empty, it returns null. Subsequently, attempting [0] on null triggers an error.

To resolve this issue, ensure that you create the 3-d array either during the initialization of board or within each iteration of the loop.

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

Determining the Clicked Button in React When Multiple Buttons are Present

Within my functional component, I have a table with rows that each contain an edit button. However, when I click on one edit button, changes are applied to all of them simultaneously. How can I identify which specific button was clicked and only apply chan ...

I'm puzzled as to why I am unable to retrieve the values from this array or parse the JSON data

When I make a call to an API, I am expecting a JSON array as the response. Here is what I receive: Array ( [0] => {"msg_id":"0t5OxT1ZP9VcF45L2","_text":"I want to reserve","entities":{"intent":[{"confidence":1,"value":"make_reservation","type":"val ...

Invoke a Node.js script from a Spring Boot application to pass a Java object to the script. The script will modify the object and then return it back to the originating class

class Services { Address address = new Address(....); /* Invoke NodeJs script and pass address object In the js script modify address object var address = getAddress() Modify address object Return address obj ...

Is there a way to create an infinite fade in/out effect for this?

Is there a way to ensure that the method runs after the "click" event in this code snippet? The code currently fades in and out the div #shape while the start variable is true, but when I call the "start" method from the "click" event, the browser stops wo ...

The insertion of field mapping outcomes into a MySQL database has been successfully completed

I am currently in the process of finalizing the last function within a script that is responsible for syncing data added to a Facebook lead form with a MySQL database. My goal is to map MySQL columns to Facebook lead form fields so that when a new entry is ...

EventBus emitting multiple times until the page is refreshed

Trying to make use of the EventBus in Vue.js to transfer data from one method to another. In my setup, I've got two methods named one() and two(). Here's how I'm implementing the EventBus: one() { EventBus.$emit("this:that", data); } And ...

There is an array present with data filled in, but unfortunately, I am unable to retrieve specific elements

As I work on my WordPress 4.7.2 website, I find myself making an AJAX call. The PHP function handling this call returns an array using wp_json_encode(). When I view the data array in the success callback of the AJAX function, everything looks just as expec ...

hasOwnProperty function yields no results

I need help displaying a table from JSON data. Can someone assist me with the code below? <th> { x.amountForQuantity.filter((remaining) => { return remaining.hasOwnProperty(cost.key); })[cost.key] } </th> ...

PhoneGap fails to fire the ondeviceready event within 5 seconds

Currently, I am in the process of debugging my PhoneGap app using Weinre and facing some persistent errors... The 'deviceready' event has not fired even after 5 seconds. Channels are not firing: onPluginsReady, onCordovaReady, onCordovaConnecti ...

Using HTML5 input type number along with a regular expression pattern

In order to display only numbers and forward slashes in the input field with regex pattern, I attempted the following code: <input type="number" pattern="[0-9\/]*"> However, this code only shows the number pad from 0 to 9. How can I modify the ...

Ways to manage your javascript variables

Here is the code snippet I am working with: var json = jQuery.parseJSON(data); console.log(json) When I run this code, the output looks like this: Object {sql: "SELECT venta.cliente_tipodoc,count(*) AS cantidad FROM venta venta", results: Array[1], ...

Is it better to modify attributes during the ng-repeat cycle or after the cycle ends?

Consider a scenario where a simple directive is defined as follows: app.directive('seo', function() { return { template: '<meta ng-repeat="tag in data" {{tag.attribute}}="{{tag.name}}" content="{{tag.content}}" />', ...

Why doesn't Mongoose automatically generate an _id for my array elements when I push them in?

I am looking for a way to have mongoose automatically add an _id field to the objects I push into my array. Here is my mongoose schema: var playerModel = new Schema({ user: { type: mongoose.Schema.Types.ObjectId, ref: "Users", }, cl ...

Step-by-step guide on triggering a button using another button

I have a unique question that sets it apart from others because I am looking to activate the button, not just fire it. Here is my syntax: $("#second_btn").click(function(){ $('#first_btn').addClass('active'); }) #first_btn ...

Error Message: TypeError - Unable to access property 'method' as it is not defined

I've just started working on a new node project and I've encountered an issue that I can't seem to figure out. :\Users\RTECH\Desktop\work\aumentedreality\modelViewerwithExpress\node_modules\express&b ...

Learning how to access JavaScript variables within a Ruby on Rails view

Our team has been working on a javascript code that captures the URL of a selected image and stores it in a JavaScript variable called "src". The goal is to access this variable within a Rails view in order to obtain the ID of the selected image. We attemp ...

Encountering a blank page issue with react-router-dom v6 Routes

I am attempting to route a page to the root, but it keeps showing up as a blank page regardless of which JavaScript file I use. It seems like React Router DOM has been updated and no longer uses Switch. I haven't used React since last year, so I' ...

Utilizing Selenium with Python to choose a specific option from a dropdown selection

I am currently experimenting with using Selenium in Python to choose the option "Custom date" from the dropdown menu displayed in the image below: https://i.sstatic.net/ASHU2.png The hierarchy of divs is structured as shown here: https://i.sstatic.net/xtA ...

Invoke the URL with a query string and obtain the response from the specified web page

How can I make a button on my user.php page call action.php?name=john&id=10 without refreshing the page? The action.php page needs to process the query string data (name=john & id=10), execute some action, and then send a message back. Here is an ...

Troubleshooting AngularJS form submission with missing data

Is there a way to modify AngularJS to save form data into a database using PHP as the backend? Below is the HTML form code: <form ng-submit="newContactSubmit()"> <label>FirstName<input type="text" name="contact_firstname" required n ...