Random array array with javascript

1

Good evening guys,

I'm trying to create a map with earth and water in javascript but I want it to be completely random, for this I assigned 0's and 1's in an array and where I had 0 put the ground and where I had 1 put water. Now I wanted to know how to populate this array with 0 and 1 randomly so that every time I give f5 a different and crazy thing pops up.

The code I'm using below is below:

    

    <meta charset="UTF-8">

    <title>Canvas Tile Map</title>

    <style>
        #canvas{
            border: 1px solid black;
            margin-left: 360px;
            margin top: -25px;
        }

        h1{
            text-align: center;
            font-size: 50px;
            font-family: sans-serif;
            color: gray;
        }

    </style>

</head>

<body>

    <h1>Mapa randômico</h1>

    <canvas id="canvas" height="400px" width="480px"></canvas>

    <script>
        var canvas = document.getElementById("canvas");
        var context = canvas.getContext("2d");
        var mapArray=[
            [0,0,0,0,0,1,1,0,0,0,0,0],
            [0,0,0,1,1,1,0,0,0,0,0,0],
            [0,1,1,1,1,0,0,0,0,1,0,0],
            [0,1,1,1,1,1,1,0,0,0,0,0],
            [0,1,1,1,1,0,0,0,0,0,0,0],
            [0,1,1,1,1,0,0,0,0,0,0,0],
            [0,1,1,1,1,0,0,0,0,0,0,0],
            [0,1,1,1,1,0,0,0,0,0,0,0],
            [0,1,1,1,1,0,0,0,0,0,0,0],
            [0,1,1,1,1,0,0,0,0,0,0,0]
            ];

        var grama = new Image();
        var agua = new Image();

        grama.src= 'grama.png';
        agua.src = 'agua.png';

        var posX=0;
        var posY = 0;

        //verifica elementos do vetor e atribui uma tile

        grama.onload = function (){
        agua.onload = function (){
        for(var i=0; i < mapArray.length; i++){

            for(var j=0; j < mapArray[i].length; j++){

                if(mapArray[i][j]==0){
                    context.drawImage(grama,posX, posY, 40, 40);
                }

                if(mapArray[i][j]==1){
                    context.drawImage(agua,posX,posY,40,40);
                }

                posX+=40;

            }

            posY+=40;
            posX=0;

        }
    }
}


    </script>

    </br>
    <button>gerar arquivo</button>

</body>

    
asked by anonymous 29.04.2017 / 00:14

1 answer

0

If I understand correctly you want to generate a matrix 10 x 12 with 0 s and 1 s.

You can do it like this:

function gerarMatriz(x, y) {
  /* ou se preferires mais estático tira os argumentos e faz:
  var x = 10;
  var y = 12;
  */
  var matriz = [];
  for (var i = 0; i < x; i++) {
    var linha = [];
    for (var j = 0; j < y; j++) {
      linha.push(Math.round(Math.random()));
    }
    matriz.push(linha);
  }
  return matriz;
}
setInterval(function() {
  var matriz = gerarMatriz(10, 12);
  document.body.innerHTML = matriz.map(l => '<br>' + l);
}, 500);
    
29.04.2017 / 09:09