Tyler N. Creed
Tyler N. Creed

Reputation: 47

Creating a Word Find grid

I am attempting to create a grid that contains one letter in each box (like a Word Find puzzle).

I have successfully created a grid that shows w/ the determined number of cols/rows, but when I attempt to put one letter in each box, I get the following ten times in each box instead of a single letter:

[object
Object]

Here is the JavaScript:

$(function() {

var letters = [
    'rzeabppssgcddrvddydtjrkei', // 1
    'cezcqubhniittonieqerbiuvm', // 2
    'jqcjnasionsncvbsrwtabddsu', // 3
    'olselesitneagittrjanreinv', // 4
    'nqnaisdenmeibvurellsnrioc', // 5
    'ydnlevrnyeaidrwifkufmsuis', // 6
    'dcccjeeaogsemudbeemefaptn', // 7
    'evonsqpdepislsnudnurwjbpo', // 8
    'grytiunnafsexattmtclaimoi', // 9
    'pnqrhocbiieeinoitacilppat', // 10
];
var letter = [];


function splitRows(arr, arr2) {
    for (let i=0; i < arr.length; i++) {
        arr[i].split();
        for (let j=0; j < arr.length; j++) {
            arr2[j] = arr[i][j];
        }
    }        
} 

splitRows(letters, letter);

function* gen(arr) {
    for(i=0; i < arr.length; i++) {
        yield arr[i];
    }
}

function generateGrid(rows, cols, arr) {
    var grid = "<table>";
    for(row = 1; row <= rows; row++) {
        grid += "<tr>";
        for(col = 1; col <= cols; col++) {
            grid += "<td>";
            for(let i=0; i < arr.length; i++) {
                grid += gen(arr).next(); // not sure if the .next() generator works yet
            }
            grid += "</td>"; // 'letters' needs to input the next letter in letters each time it is called
        }
        grid += "</tr>";
    }
    return grid;
}

$("#tableContainer").append(generateGrid(26, 22, letter));

});

The first function is intended to take rows and split them into singular letters (eventually taking rows as an input, but for testing purposes I have them in an array)

The second function is a generator to insert into the generateGrid() function that is used to generate the next letter in the sequence each time a box is created.

Upvotes: 0

Views: 537

Answers (1)

Mr. Polywhirl
Mr. Polywhirl

Reputation: 48600

You should convert your string data to a matrix first then you can run the matrix through a table.

The following jQuery plugin clears the table and replaces it with rows and columns based on the data.

Note: I also added in tag name validation, in the case where the element the plugin was being invoked upon was not a <table> element.

var DEBUG_EXPERIMENTAL = false;

initializePlugins(); // Forward Declaration of jQuery plugins

let rawStringData = `
  rzeabppssgcddrvddydtjrkei
  cezcqubhniittonieqerbiuvm
  jqcjnasionsncvbsrwtabddsu
  olselesitneagittrjanreinv
  nqnaisdenmeibvurellsnrioc
  ydnlevrnyeaidrwifkufmsuis
  dcccjeeaogsemudbeemefaptn
  evonsqpdepislsnudnurwjbpo
  grytiunnafsexattmtclaimoi
  pnqrhocbiieeinoitacilppat
`;

$('.word-search').buildWordSearch(rawStringData, 'letter');
$('.letter').enableHighliting('highlight');

function initializePlugins() {
  (($) => {
    $.stringToMatrix = function(str) {
      return str.trim().split('\n').map(row => row.trim().split(''));
    };
    $.fn.buildWordSearch = function(stringData, cellClass) {
      this.throwErrorIfNotType('TABLE');
      return this.append($('<tbody>')
        .append($.stringToMatrix(stringData).map(row => {
          return $('<tr>').append(row.map(col => {
            return $('<td>').addClass(cellClass).text(col);
          }));
        })));
    };
    $.fn.throwErrorIfNotType = function(expectedTagName) {
      let actualTagName = this.prop('tagName');
      if (actualTagName !== expectedTagName) {
        throw Error(`Element '${actualTagName}' is not a '${expectedTagName}'!`);
      }
    };
    $.fn.getCell = function(x, y) {
      return this.find(`tr:nth-child(${y + 1}) td:nth-child(${x + 1})`);
    };
    $.fn.enableHighliting = function(cls) {
      return this.each(() => {
        this.on({
          mouseover: function() {
            let $table = $(this).closest('table');
            let $row = $(this).closest('tr');
            let rowIndex = $row.index();
            let colIndex = $(this).index();
            let rowCount = $table.find('tbody tr').length;
            let colCount = $row.find('td').length;

            // Hightlights diagonals.
            if (DEBUG_EXPERIMENTAL) {
              let limit = rowCount;
              let xNeg = colIndex - 1;
              let xPos = colIndex + 1;
              let yNeg = rowIndex - 1;
              let yPos = rowIndex + 1;
              while (limit > 0) {
                if (xNeg > -1 && yNeg > -1) {
                  $table.getCell(xNeg, yNeg).addClass(cls);
                }
                if (xPos < colCount && yNeg > -1) {
                  $table.getCell(xPos, yNeg).addClass(cls);
                }
                if (xNeg > -1 && yPos < rowCount) {
                  $table.getCell(xNeg, yPos).addClass(cls);
                }
                if (xPos < colCount && yPos < rowCount) {
                  $table.getCell(xPos, yPos).addClass(cls);
                }
                xNeg--;
                xPos++;
                yNeg--;
                yPos++;
                limit--;
              }
            }

            $row.addClass(cls);
            $table.find(`td:nth-child(${colIndex + 1})`).addClass(cls);
          },
          mouseout: function() {
            let $table = $(this).closest('table');
            let $row = $(this).closest('tr');
            let rowIndex = $row.index();
            let colIndex = $(this).index();
            let rowCount = $table.find('tbody tr').length;
            let colCount = $row.find('td').length;

            // Un-hightlights diagonals.
            if (DEBUG_EXPERIMENTAL) {
              let limit = rowCount;
              let xNeg = colIndex - 1;
              let xPos = colIndex + 1;
              let yNeg = rowIndex - 1;
              let yPos = rowIndex + 1;
              while (limit > 0) {
                if (xNeg > -1 && yNeg > -1) {
                  $table.getCell(xNeg, yNeg).removeClass(cls);
                }
                if (xPos < colCount && yNeg > -1) {
                  $table.getCell(xPos, yNeg).removeClass(cls);
                }
                if (xNeg > -1 && yPos < rowCount) {
                  $table.getCell(xNeg, yPos).removeClass(cls);
                }
                if (xPos < colCount && yPos < rowCount) {
                  $table.getCell(xPos, yPos).removeClass(cls);
                }
                xNeg--;
                xPos++;
                yNeg--;
                yPos++;
                limit--;
              }
            }

            $row.removeClass(cls);
            $table.find(`td:nth-child(${colIndex + 1})`).removeClass(cls);
          }
        });
      });
    };
  })(jQuery);
}
.word-search {
  border: 2px solid #000;
  border-collapse: collapse;
}

.word-search td {
  width: 1.25em;
  height: 1.25em;
  line-height: 1.25em;
  text-align: center;
}

.highlight {
  background: #FFD;
}

.letter.highlight:hover {
  background: #FF0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="word-search"></table>

Upvotes: 1

Related Questions