Populating a two-dimensional array with randomly generated numbers using javascript

Apologies if this has been asked before, but I couldn't find any previous posts on the topic as I'm still fairly new to this site!

Lately, I've been exploring game development using HTML5 and JavaScript and have gotten into creating tileset maps. I currently have a tileset and a 2D array where I want to assign specific tiles (usually between 6 and 10). I thought it would be neat to create a function that allows the map to randomly select from a small set of similar tiles, rather than assigning a number to each tile in the array.

The method I'm using now works for defining types, but I'm looking for a cleaner solution or an explanation of why my "cleaner" version isn't working.

var ground = [
    [tile(), tile(), tile(), tile(), tile(), tile(), tile(), tile(), tile(), tile(), tile(), tile(), tile(), tile(), tile()],
    [tile(), tile(), tile(), tile(), tile(), tile(), tile(), tile(), tile(), tile(), tile(), tile(), tile(), tile(), tile()],
    // More rows...
];

function tile() {
    var y = (Math.random() * 5 | 0) + 6;
    return y;
}

This is the code I've been using so far, where I have to manually add the 'tile()' function to each element to generate random numbers. What I'd like is something like:

for (var i = 0; i < 15; i++) {
    for (var j = 0; j < 9; j++) {
        ground[i][j] = (Math.random() * 5 | 0) + 6;
    }
}

This way, I can fill the array without having to individually apply the function to each position. I suspect I might be missing a return statement or something similar, but I'm not entirely sure.

Answer №1

Your code was on the right track, but there were a couple of errors that needed fixing ;)

  • Remember to initialize the array before pushing elements into it.
  • Also, make sure you are incrementing the correct variable in your loop.

Here's the corrected Javascript:

var ground = []; // Initialize array
for (var i = 0 ; i < 15; i++) {
    ground[i] = []; // Initialize inner array
    for (var j = 0; j < 9; j++) { // Increment j instead of i
        ground[i][j] = (Math.random() * 5 | 0) + 6;
    }
}

If you want a more reusable solution, try this function:

function createGround(width, height){
    var result = [];
    for (var i = 0 ; i < width; i++) {
        result[i] = [];
        for (var j = 0; j < height; j++) {
            result[i][j] = (Math.random() * 5 | 0) + 6;
        }
    }
    return result;
}
// Create a new ground with width = 15 & height = 9
var ground = createGround(15, 9);

Answer №2

Let me show you an example. I've crafted a function that can produce a specified size based on given width and height parameters. Additionally, I enclosed your tile function inside generate ground to maintain privacy, preventing outside scripts from accessing it.

var ground = generateGround(10, 10); //Easy implementation

function generateGround(height, width)
{
  var ground = [];
  for (var y = 0 ; y < height; y++) 
  {
    ground[y] = [];
    for (var x = 0; x < width; x++) 
    {
        ground[y][x] = tile();
    }  
  }
  return ground;

  function tile()
  {
    return (Math.random() * 5 | 0) + 6;
  }
}

http://jsbin.com/sukoyute/1/edit

Answer №3

Consider eliminating the comma from...

ground[[i],[j]] = (Math.random() * 5 | 0) + 6;

...in your revised version. Also, ensure that you are incrementing 'i' correctly in both for loops:

for (var i = 0 ; i < 15; i++) {
for (var j = 0; j < 9; i++) {

These adjustments should help resolve the issues for you :)

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

Having trouble with babel-loader, encountering an issue with UglifyJS (ES6) causing errors

Recently, I integrated the FlipClockJs vue component into my project and it was functioning properly during development when I executed yarn encore dev However, upon running yarn encore production An error cropped up as follows: ERROR Failed to ...

Do not use Express.js to serve the index.html file

Encountered an issue when attempting to run my Express.js solution. Instead of opening my desired index.html file located in the client directory, it kept opening the index.jade file from the views folder with the message "Welcome to Express" on the browse ...

"Utilizing JavaScript to filter JSON data at a deep nested

When working with a JSON data set, I often face the challenge of filtering based on specific child values. Take the following example: [ { "Date": "2017-03-02T00:00:00", "Matches": [ { "Id": 67, ...

Is Socket.io combined with Redis the best architecture for an interactive gaming experience?

My current setup involves a NodeJS scaling architecture with Redis, specifically designed for a real-time multiplayer game. However, I'm facing challenges in configuring separate lobbies for players, as the load balancer assigns users to different ser ...

Inject some content into the page with the power of jQuery

Currently working with jQuery, I have a div containing H2 tags. <div id="preload"><h2></h2></div> I'm looking to understand how to use jQuery to insert text inside the <h2> tags The expected outcome should be: <div ...

Function executed many times during click action

I have developed a web application that allows users to input any keyword or statement and receive twenty results from Wikipedia using the Wikipedia API. The AJAX functionality is working perfectly. The app should dynamically create a DIV to display each r ...

Utilizing additional PHP files to handle the AJAX post request and subsequently execute the PHP script

I have been tasked with a complex assignment that I am struggling to comprehend. Let me provide a brief overview of what is required of me. There are three files involved in this task: 1. An HTML file that sends an AJAX post request to passwrapper.php. 2. ...

What is the correct method for compiling a list of users?

Hello, I have developed a basic user list based on database results, but I am facing two issues with it. Currently, my list displays like this: [UserOne, ...][UserTwo, ...] However, I need the format to be: [UserOne],[UserTwo]... The three dots repres ...

What is the best way to make text appear as if it is floating in Jade or HTML?

Currently, I am facing an issue with a Jade file that displays an error message when a user tries to log in with incorrect credentials. The main problem is that this error message disrupts the alignment of everything else on the page, as it is just a regul ...

Obtain the index of the selected item from a dropdown menu

Is there a way for the selectedIndex to return -1 if no item is selected, instead of the element's text at position 0? It seems that the selectedIndex always returns 0 even when nothing is selected. <select id="abc" name="abc"> <option& ...

Mandatory press for a function known as a click

After dealing with a previous question on this matter, I have encountered yet another issue. My goal is to rotate an element clockwise by 22 degrees and then back to its initial state of 0 degrees on click. The first function executes correctly, but the ...

Converting JSON to C# object in order to showcase nested array as a string within a grid display

Everything went smoothly during the run and Deserialize process, except for the Roles being displayed as System.Collections.Generic.List`1[System.String] Issue If I want to link each field to a grid. Is there a way to display the collection as a string w ...

Ways to halt a CSS animation when it reaches the screen boundary

I put together this demo: By clicking, a red box falls down. The issue arises when trying to determine the screen size using only CSS. In my demo, I set the box to fall for 1000px regardless of the actual screen height. Here is the keyframe code snippet ...

Once the PostgreSQL container is stopped with docker-compose down, the previously used port becomes unavailable for use again

Currently, I am involved in a project which utilizes express as the server and postgres as the database to delve into dockerization. The server relies on the database being operational. Initially, when running docker-compose up everything functions correct ...

Obtain the row ID from a database by selecting checkboxes

I am facing a challenge when trying to remove a row from my MS Access database using checkboxes on my JSP page. Each row in the displayed database has a checkbox, but I am struggling to retrieve the rowId and link each checkbox with its respective row. Any ...

Tips for executing getJSON requests one after the other

My goal is to showcase a weather forecast for a specific date on my website. Here are excerpts from the code I've used on a trial page that isn't functioning correctly: <script> function displayWeather(date){ $.getJSON(url + apiKey + "/" ...

What is the process for retrieving the data from the POST request body on the client side?

Greetings to all, I am a student who is still in the process of learning and have a question about passing data from server to client. Currently, I have an Arduino sensor that sends POST requests containing sensor data to an express server. The server suc ...

Restrict access to table records by specifying an array of row identifiers

Hi everyone, I've encountered a small issue. Just to provide some background, I have a table with checkboxes. Each row in the table has an associated ID, and when selected, I receive an array like this: const mySelectedRoles = [1997, 1998, 1999] Once ...

How can you incorporate a custom button into the controlBar on videoJS in responsive mode?

The video player I have created using videoJS includes custom buttons in the control bar. These buttons are not clickable when viewed on mobile or tablet devices without forcing them to work. let myButton = player?.controlBar.addChild('button'); ...