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>