-->

Placing words in table grid in word search puzzle?

2019-04-11 07:41发布

问题:

I am trying to create a words search puzzle generated by script. The words should be placed horizontally, vertically or diagonally. I might need the option to set whether they are allowed to read only forward or backward. I have an array of words such as (apple, banana, grape, lemon, pear) which needs to be placed in the table. I have already created the table but I am stuck at how to place the words in the grid.

I am looking for examples with some explanation.

Please see my code below:

var wordsList =[
"apple", 
"banana", 
"grape", 
"lemon", 
"pear" ];  

var cells = 10; // Numbers of cells horizontally and vertically in table grid
var cellSize = 15; // in pixels
var cellSpace = 2; // cell spacing in pixels

function createPuzzleTable(cells) {

    var totalNumRows = "";
    var totalNumColumns = "";

    //creating rows
    for (r=1;r<=cells;r++){
        //creating cells
        var oneCell = "<td width='" + cellSize + "' height='"+ cellSize + "'><input name='charField' type='text' /></td>";
        totalNumRows += oneCell;
    }

    //creating columns
    for (c=1;c<=cells;c++){ 
        totalNumColumns += "<tr>" + totalNumRows + "</tr>";
    }       
    var puzzleTableContent = "<div id='puzzleCont'><table id='puzzleTable' border='0' cellspacing='" + cellSpace +"' cellpadding='0'>"+ totalNumColumns +"</table></div>";

$("#wPuzzle").append(puzzleTableContent);

}

createPuzzleTable(cells);

回答1:

First, you need to establish an easy method to locating items in your grid. Use class names:

<input name='charField' class="r_2 c_3" type='text' />

Where "r_" represents rows and "c_" columns.

Then randomly select a direction and a location (row, column). See if the word will fit and that the square isn't already occupied, otherwise choose again.

Then drop letters into the grid using r_ c_ coordinate system.

Repeat.

Fill in unoccupied cells with pseudo-random filler data.



回答2:

There's already a jquery widget that does this: http://code.google.com/p/jquery-wordsearch-game/

Have a look at this code. It uses the Strategy Pattern to place words on the grid in the forward, backward, up, down and both diagonal directions. Specifically, look at line 547 onwards.

Since learning is your strong point, you might find it fun.. and probably come up with an even better way of doing it.