JSFiddle - React, Tailwind, and code Playground
by gRoberts
HTML
<div id="grid"></div>
JavaScript
(function($) {
$.fn.crossword = function(options) {
var BLANK = '@',
CANT_GO_DOWN = '|',
CANT_GO_ACROSS = '_',
CANT_GO_BOTH = '+',
DOWN = 0,
ACROSS = 1;
function Grid(x, y, def) {
this.items = new Array();
this.get = function(x, y) {
return this.items[y][x];
};
this.set = function(x, y, value) {
if (x >= 0 && x < opts.grid.x && y >= 0 && y < opts.grid.y) {
var val = this.get(x, y);
if ((value === CANT_GO_DOWN && val === CANT_GO_ACROSS) || (value === CANT_GO_ACROSS && val === CANT_GO_DOWN)) {
this.items[y][x] = CANT_GO_BOTH;
} else if(val === BLANK) {
this.items[y][x] = value;
}
}
};
this.addWord = function(word, x, y, direction) {
for (var i = 0; i < word.length; i++) {
var ch = word.charAt(i);
this.set(x, y, ch);
if (direction === DOWN) {
y++;
} else {
x++;
}
}
};
for (var i_y = 0; i_y < y; i_y++) {
this.items[i_y] = new Array();
for (var i_x = 0; i_x < x; i_x++) {
this.items[i_y][i_x] = def;
}
}
};
function buildStage() {
var me = $(this);
// Remove existing grid, if one is there.
me.find('.stage').remove();
placedWords = [];
unplacedWords = opts.answers;
grid = new Grid(opts.grid.x, opts.grid.y, BLANK);
// Build a new stage based on the options.
var stage = $('<table>').addClass('stage');
for (var y = 0; y < opts.grid.y; y++) {
var row = $('<tr>');
for (var x = 0; x < opts.grid.x; x++) {
var cell = $('<td>');
row.append(cell);
}
stage.append(row);
}
me.append(stage);
placeWords();
var rows = stage.find('tr');
for ( var r = 0; r < rows.length; r++) {
var cells = $(rows[r]).find('td');
for ( var c = 0; c < cells.length; c++) {
var val = grid.get(c,...