0

I'm trying to set up a minesweeper-ish kind of game I can share with my Dad over the web. How would I use a loop to create that grid and make each index at a certain coordinate that I can manipulate? Thanks everyone.

2 Answers 2

3

You can use a multi-dimensional array (an array of arrays).

var gridWidth = 10;
var gridHeight = 10;
var grid = [];
for(var y = 0; y < gridHeight; y++)
{
    grid.push([]);
    for(var x = 0; x < gridWidth; x++)
    {
        grid[y].push(0);
    }
}

You now have a 10x10 grid, which you can access via grid[x][y]

Representing this on the page, in HTML, depends on the framework you are using. If you want to do it with raw javascript, you could perhaps output a table.

document.write('<table>');
var gridWidth = 10;
var gridHeight = 10;
var grid = [];
for(var y = 0; y < gridHeight; y++)
{
    document.write('<tr>');
    grid.push([]);
    for(var x = 0; x < gridWidth; x++)
    {
        document.write('<td onclick="alert(\'clicked\');">');
        grid[y].push(0);
        document.write('</td>');
    }
    document.write('</tr>');
}
document.write('</table>');
Sign up to request clarification or add additional context in comments.

6 Comments

That's exactly what I'm looking for. Is there anything particular I need to do in the html? I use Chrome, so that shouldn't be an issue.
Well, obviously you will need to add all of your game logic. StackOverflow won't write it for you, but if you get stuck, feel free to ask :)
Thanks! I mean besides the basic html structure, do I need to have a table already written in the html?
Well, the code that I wrote above will output it for you, but document.write() is bad practice for a few reasons - I only added it for demo purposes. Ideally you should be using a framework - jQuery, for example, is very popular. I personally use Angular for pretty much everything I do, but there's a learning curve.
It says "clickableGrid" is not defined. I'm using jquery 1.12.3
|
2

This will give you some click events, reporting back the column and row.

css:

td {
    border: black solid 1px;
}

html:

<table class="table"></table>

javascript:

$('.table').on('click', 'td', function () {
    console.log($(this).attr('data-row'));
    console.log($(this).attr('data-column'));
})

var columns = 10, rows = 10

function createGrid(columns, rows) {
    var table = $('.table');

    for (var i = 0; i < rows; i++) {
        var row = $('<tr>');
        table.append(row)
        for (var j = 0; j < columns; j++) {
            var cell = $('<td>')
            cell.attr('data-row', i);
            cell.attr('data-column', j)
            row.append(cell);
        }
    }
}
createGrid(columns, rows);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.