Search code examples
javascripthtmlcssmaze

Obtain binary values of the maze color in Javascript


I am pretty new to front end development. I am trying to build a maze solver using HTML, CSS and Javascript. There is a starting point and an end point and I am trying to use Shortest Path Algorithm to find the shortest distance between them.

Here is the HTML and CSS code that I have written:

http://jsfiddle.net/p9qdhfub/1/

div {
    background: #000;
    float: left;
    height: 29vw;
    margin: 1%;
    width: 23%;
    }

    div:nth-child(3n-1){
    background:white;
    margin-left:0;
     }
    <section>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
</section>

white represents: hurdle black represents: the actual path

I want to get the binary representation of the 4x4 maze that I have created, where black represents 1 and white represents 0. How can I do that in Javascript??

The result should be a 4x4 matrix based on the color.


Solution

  • How can I do that in Javascript??

    If you are saying you want to test the background colour of each of the divs and map black to 1 and white to 0 then it seems to me you are going about this whole thing backwards: it would be better to create the matrix in JS first and build the html from the matrix using appropriate classes to set the colours (rather than using something like :nth-child(3n-1)). Then you could easily substitute another drawing technique, such as a canvas element.

    Anyway, starting from your existing html/css you can make use of the .getComputedStyle() method as follows:

    var divs = document.querySelectorAll("section div");
    
    var matrix = [].map.call(divs, function(v) {
      var b = window.getComputedStyle(v).backgroundColor;
      return b === "rgb(0, 0, 0)" ? 1 : 0;
    }).reduce(function(p, c, i) {
      if (i % 4 === 0) p.push([]);
      p[p.length-1].push(c);
      return p;
    }, []);
    
    console.log(matrix);
    section div {
      background: #000;
      float: left;
      height: 10px;
      margin: 2px;
      width: 23%;
    }
    div:nth-child(3n-1) {
      background: white;
      margin-left: 0;
    }
    <section>
      <div></div> <div></div> <div></div> <div></div>
      <div></div> <div></div> <div></div> <div></div>
      <div></div> <div></div> <div></div> <div></div>
      <div></div> <div></div> <div></div> <div></div>
    </section>