What is the best way to merge two arrays into a unified 3d array using JavaScript?

I've managed to get a text-based game up and running, featuring two arrays: the main array (mainArray) that contains information for displaying a bordered map, and a collision array (colArray) that prevents the player from walking off the map.

Everything seems to be working fine, except for one issue. I am trying to store the collision information in the mainArray as a 3D array instead of a 2D array, but every attempt I've made has failed.

I've been thinking that it should be as simple as adding another [] next to mainArray[i][j] within the if statements in the initMap function, something like mainArray[i][j][k], and then storing the "solid" strings there. However, this approach doesn't seem to work.

Here is a link to a different version where I'm attempting to implement the third dimension and test for it without checking for "solid," testing only for k instead

Below is the operational code of the game using 2D arrays mainArray and colArray, which I am looking to merge into a single 3D array. You can also run the code here. After running the code, you may need to click fullscreen to see what's going on.

function gameloop() {
  var mainArray = [];
  var colArray = [];
  var mapSizeX = 32;
  var mapSizeY = 128;
  var idPos = {
    x: 0,
    y: 0
  };

  function initMap(mainArray, mapSizeX, mapSizeY) {
    for (var i = 0; i < mapSizeX; i++) {
      mainArray.push([])
      colArray.push([])

      for (var j = 0; j < mapSizeY; j++) {
        mainArray[i][j] = ".";
        colArray[i][j] = "";

        if (j == 0) {
          mainArray[i][j] = "#";
          colArray[i][j] = "Solid";
        }
        if (j == mapSizeY - 1) {
          mainArray[i][j] = "#";
          colArray[i][j] = "Solid";
        }
        if (i == 0) {
          mainArray[i][j] = "#";
          colArray[i][j] = "Solid";
        }
        if (i == mapSizeX - 1) {
          mainArray[i][j] = "#";
          colArray[i][j] = "Solid";
        }
      }
    }
  }

  function nl() {
    GameScreen.innerText += "\n";
  }

  function render() {
    GameScreen.innerText = mainArray.map(arr => arr.join("")).join("\n");
    nl();
    nl();
  }

  function reposition(xChange, yChange, strA) {
    if (colArray[idPos.x + xChange][idPos.y + yChange] === "Solid") {
      GameLog.innerText = "You can not travel in that direction"
    } else {
      mainArray[idPos.x][idPos.y] = ".";
      idPos.x = idPos.x + xChange;
      idPos.y = idPos.y + yChange;
      mainArray[idPos.x][idPos.y] = "@";
      GameLog.innerText = "You take a step to the " + strA
    }

    render();
  }

  //Startup
  initMap(mainArray, mapSizeX, mapSizeY);
  idPos.x = mapSizeX / 2;
  idPos.y = mapSizeY / 2;
  mainArray[idPos.x][idPos.y] = "@";
  //First Render
  render();

  document.addEventListener('keydown', function(event) {
    if (event.keyCode === 38) {
      reposition(-1, 0, "North");
    }
    if (event.keyCode === 40) {
      reposition(1, 0, "South");
    }
    if (event.keyCode === 37) {
      reposition(0, -1, "West");
    }
    if (event.keyCode === 39) {
      reposition(0, 1, "East");
    }
    //alert(event.keyCode);
  });
}

gameloop();
<p style="color:#7d7d7d;font-family:Lucida Console;">Dungeon Valley.<br>
  <font style="color:#ABABAB;font-family:Lucida Console;font-size:0.5em" ;>
    Taming the Borderlands.<br> v0.005 By heromedel. </P>
</font>
<P>
  <section id="GameScreen" style="color:#000000;font-family:Lucida Console;"></section>
  <P>
    <section id="GameLog" style="color:#000000;font-family:Lucida Console;">Arrow Keys to move.<br></section>
    <script src="main.js"></script>

Answer №1

Your code currently has mainArray[x][y] as a string. To store additional properties at that level, you'll need to replace the string with an object containing those properties.

I've made the necessary updates to your code:

Here are some important notes:

  • I replaced the 4 separate wall if statements with a single if statement that checks all 4 conditions.
  • In the render function, I added an extra map to extract the surface symbol from the new object.
  • All references to mainArray[x][y] have been updated to mainArray[x][y].surface.

function gameloop() {
  var mainArray = [];
  var colArray = [];
  var mapSizeX = 32;
  var mapSizeY = 128;
  var idPos = {
    x: 0,
    y: 0
  };

  function initMap(mainArray, mapSizeX, mapSizeY) {
    for (var i = 0; i < mapSizeX; i++) {
      mainArray.push([]);
      colArray.push([]);

      for (var j = 0; j < mapSizeY; j++) {
        mainArray[i][j] = {
          surface: "."
        };
        colArray[i][j] = "";

        if (j == 0 ||
          j == mapSizeY - 1 ||
          i == 0 ||
          i == mapSizeX - 1) {
          mainArray[i][j].surface = "#";
          colArray[i][j] = "Solid";
        }
      }
    }
  }

  function nl() {
    GameScreen.innerText += "\n";
  }

  function render() {
    GameScreen.innerText = mainArray.map(arr => arr.map(cell => cell.surface).join("")).join("\n");
    nl();
    nl();
  }

  function reposition(xChange, yChange, strA) {
    if (colArray[idPos.x + xChange][idPos.y + yChange] === "Solid") {
      GameLog.innerText = "You cannot travel in that direction."
    } else {
      mainArray[idPos.x][idPos.y].surface = ".";
      idPos.x = idPos.x + xChange;
      idPos.y = idPos.y + yChange;
      mainArray[idPos.x][idPos.y].surface = "@";
      GameLog.innerText = "You take a step to the " + strA;
    }

    render();
  }

  // Startup
  initMap(mainArray, mapSizeX, mapSizeY);
  idPos.x = mapSizeX / 2;
  idPos.y = mapSizeY / 2;
  mainArray[idPos.x][idPos.y].surface = "@";
  // First Render
  render();

  document.addEventListener('keydown', function(event) {
    if (event.keyCode === 38) {
      reposition(-1, 0, "North");
    }
    if (event.keyCode === 40) {
      reposition(1, 0, "South");
    }
    if (event.keyCode === 37) {
      reposition(0, -1, "West");
    }
    if (event.keyCode === 39) {
      reposition(0, 1, "East");
    }
    // alert(event.keyCode);
  });
}

gameloop();
.info {
  color: #7d7d7d;
  font-family: Lucida Console;
}

.info span {
  color: #ABABAB;
  font-family: Lucida Console;
  font-size: 0.5em;
}

#GameScreen,
#GameLog {
  color: #000000;
  font-family: Lucida Console;
}
<p class="info">Dungeon Valley.<br>
  <span class="">
    Taming the Borderlands.<br> v0.005 By heromedel.
  </span>
</p>
<section id="GameScreen"></section>
<section id="GameLog">Arrow Keys to move.<br></section>

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

What is the best way to update the current timestamp dynamically in Vue.js without needing to refresh the page?

I have a Vue application where I am using a method to retrieve the current timestamp. Although it successfully displays the current time and date, it only updates upon page refresh. I would like for it to update dynamically without requiring a page refresh ...

Nested $cond in MongoDBIn MongoDB, nesting $cond operators inside

I need to perform a group by operation on Campaign_Name and then apply a sum aggregator based on certain conditions. However, I'm encountering syntax errors in the code snippet below: $group : { _id: "$Campaign_Name", ...

Prevent the ability to add options dynamically to a drop-down select list

I have implemented a dynamic data retrieval feature from my database using jQuery's .getJSON function and appended the data to an HTML select drop-down list. The JavaScript code for this functionality is as follows: $.getJSON('url', f ...

Persistent hover state remains on buttons following a click event

In my current project, I am dealing with a form that has two distinct states: editing and visible. When the user clicks on an icon to edit the form, two buttons appear at the bottom - one for saving changes and one for canceling. Upon clicking either of th ...

Encountered an issue with using multer as middleware in Express 4

const express = require('express'); const router = express.Router(), const multer = require('multer'); const uploadFile = multer({ dest: __dirname + '../public/uploads/' }) router.post('/upload', uploadFile, fun ...

Listener for 'timeupdate' event on video doesn't retain values

My html5 video event listener is designed to pause the video at a specific time while the user participates in a quiz. The first 'lesson' works fine, and the second video also appears to add the listener with the correct pause time. However, when ...

In Angular 7, where can the controller be found within its MVC architecture implementation?

From what I understand, Angular adheres to the MVC architecture. In the components, there is a .ts file which serves as the model and a .html file for the view, but my question is: where is the controller located? ...

Having trouble loading popper.js using Laravel mix and webpack

I have been working on my project with Bootstrap 4 beta and Laravel 5.4, using npm and Laravel mix to load my JavaScript dependencies. Everything was going smoothly until I encountered an error while trying to use Bootstrap JavaScript methods. The error me ...

Change a 2D array into a 1D array in the C programming

My two dimensional array is set up like this: ptr = (int **) malloc(size); for (i = 0; i < len; i++) { ptr[i] = (int *) malloc(size); } Is there a way to efficiently create an int *intPtr for that array so I can access the values in row-major ord ...

Guide on making an NPM package with a web worker integration

Currently, I am in the process of developing an npm package that incorporates a web worker with type module. The issue arises when I try to link this package to a React application for testing purposes since the application cannot locate the worker.js file ...

Guide on utilizing the "window" attribute within Angular framework

Recently, I came across a neat "Scroll back to top" button that caught my eye: https://www.w3schools.com/howto/howto_js_scroll_to_top.asp Despite being new to Angular, I wanted to give it a try and implement this feature myself. However, every attempt I ...

"Shopping just got easier with our new drag and drop feature! Simply drag items

I want to develop a Virtual Shopping Cart system. Items will be retrieved from a database. A virtual basket will be available. Users can drag items and drop them into the basket, similar to shopping in a mall. Once the user clicks the save button, the s ...

Issue with JavaScript not executing upon clicking the submit button on a form within the Wordpress admin page

In the admin pages of my Wordpress installation, I have created an HTML form. My goal is to validate the data inputted when the submit button is pressed using a Javascript function. If the data is not correctly inserted, I want alerts to be displayed. Desp ...

Exporting JSON models with textures from Blender using THREE.JS

I am currently utilizing the mrdoob Blender Export Plugin (io_mesh_threejs) for exporting to Three JS, but I am encountering an issue where the exported .js or .dae objects do not contain any reference to the texture map files. I am wondering if there is a ...

Is it possible to pass a PHP array as variables to load a URL in Javascript and then back to a PHP array

I have come across several related examples but I am still unsure. I am using ajax (which I am not very familiar with) to retrieve the results of a file that is updated every xxx seconds. Everything works perfectly when I pass just one variable, but what i ...

Inspect the table and format the tr content in bold depending on the values found in two corresponding columns within the same table

Looking to create a responsive table where row content becomes bold if it matches the current date. Hiding the first-child th & td as they are only needed for a specific function. Comparing values in <td data-label="TodaysDate">06-05-2020</t ...

What is the best method to update the content of a bootstrap-5 popover using only pure JavaScript?

Having trouble changing the content of a Bootstrap popover using vanilla JavaScript? The code seems to be updating, but the changes are not reflecting on the site. Any suggestions or alternative methods would be greatly appreciated! Maybe there's a di ...

Customizing Magnific Popup: Changing showCloseBtn and closeOnBgClick settings during display

Is there a way to customize the behavior of an open instance of a magnific popup? I want to have different settings for when the popup is closable and when it should be prevented from closing. It appears that these options are only available during initial ...

The React file fails to render properly in the browser when initiated

I downloaded a Bootstrap template for my project, but when I run the script in the browser, nothing shows up. Can anyone help me identify the issue in this code? I was expecting to see the output on my localhost. In the home.jsx file, I had to remove ...

Try utilizing a dynamically created JSON object in place of using d3.json

I spent a considerable amount of time trying to solve this issue, but unfortunately I was unsuccessful. I know how to render a d3 tree with an external file, but I'm struggling with how to do it with a generated object. I am retrieving a JSON object t ...