Calicol Calicol - 2 months ago 21
Javascript Question

How to make a road of colored tiles

How can I implement this to make a road of colored tiles that a character would follow (The character needs to file a rode with the same color of the character that will be a cube.)
I have this for now(from other post):



<html><head>
<style>
body{ background-color: ivory; padding:10px; }
#canvas{border:1px solid red;}
</style>
</head>
<body>
<canvas id="canvas" width="1000" height="1000"></canvas>
<script type="text/javascript">

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");

var cw=canvas.width;
var ch=canvas.height;

var colwidth=cw/20;
var rowheight=ch/20;

for(var y=0;y<20;y++){

for(var x=0;x<20;x++){

ctx.fillStyle=randomColor();
ctx.fillRect(x*colwidth,y*rowheight,colwidth,rowheight);
ctx.strokeRect(x*colwidth,y*rowheight,colwidth,rowheight);
}}

function randomColor(){
return('#'+Math.floor(Math.random()*12345678).toString(16));
}
</script>

</body></html>




Answer
<html>
<head>
<style>
body{background-color:ivory;padding:10px;}
#canvas{border:1px solid red;}
</style>
</head>
<body>
<canvas id="canvas" width="1000" height="1000"></canvas>
<script type="text/javascript">

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");

var cw=canvas.width;
var ch=canvas.height;

var n = 20;

var colwidth=cw/n;
var rowheight=ch/n;

var colors = [];
for(var y=0;y<n;y++)
{
  colors[y] = [];
  for(var x=0;x<n;x++)
  {
    colors[y][x] = randomColor();
  }
}

var road_color = randomColor();
var x = n/2;
var y = 0;
while(y < n)
{
  colors[y][x] = road_color;
  var path = Math.floor(Math.random()*3);
  switch(path)
  {
    case 0: //try left
      if(x > 0 && colors[y][x-1] != road_color) x--; break;
    case 1: //try right
      if(x < n-1 && colors[y][x+1] != road_color) x++; break;
    case 2: //down
      y++; break;
  }
}

for(var y=0;y<n;y++)
{
  for(var x=0;x<n;x++)
  {
    ctx.fillStyle=colors[y][x];
    ctx.fillRect  (x*colwidth,y*rowheight,colwidth,rowheight);
  }
}
for(var y=0;y<n;y++)
{
  for(var x=0;x<n;x++)
  {
    ctx.strokeRect(x*colwidth,y*rowheight,colwidth,rowheight);
  }
}

function randomColor(){return('#'+Math.floor(Math.random()*0xFFFFFF).toString(16));}
</script>
</body>
</html>

Can't really tell for sure what you're going for... I assume "road" was a bad translation of "path"? This just creates a "random" path of a solid color down your randomly generated color tile. (Also, I changed 12345678 to 0xFFFFFF to give the full spectrum of random colors, and stroked the lines after drawing all the fills for consistent line weight.)

Comments