I’m working on a new word-search game that uses Boggle-style logic; i.e. the letters don’t have to be in a straight line.
I’m trying to write a function that checks the grid to see if a specific word is there, and I’m having a little trouble organizing all the loops to do the checking, and I was wondering if anyone had a done something like this in the past and could help me out with a code snippet or a push in the right direction.
The letter grid is a 2D table:
local puzzleGrid = {
{ "A", "B", "C" },
{ "D", "E", "F" },
{ "G", "H", "I" }
}
For previous games- straight word search- I would go to each square and strike out in each direction using a pair of arrays to mimic the eight compass points
local directionalArrayX = { -1, -1, -1, 0, 0, 1, 1, 1 }
local directionalArrayY = { -1, 0, 1, -1, 1, -1, 0, 1 }
step through the grid
for i = 1, #puzzleGrid[1] do
for j = 1, #puzzleGrid do
and gather up all the letters in the grid along those lines and compare them to the word I was looking for. This might not be the most efficient method, but it works fine. It’s a few hundred comparisons on the outside and it happens instantly on device.
This approach will not work with non-linear word finding because things get exponential very quickly. The approach that makes sense is to compare the first letter in the word I’m trying to find with each letter of the grid:
for i = 1, #puzzleGrid[1] do
for j = 1, g #puzzleGrid do
if ( puzzleGrid[j][i] == wordToFind:sub( 1, 1 ) ) then
print( "******** First letter matches!" )
end
end
end
The above code works fine. No surprise, since it isn’t really doing anything interesting. The tricky bit is the next part where it loops through and looks at all the neighbors, snaking around until it a) finds the word it’s looking for or b) checks every sensible combination of letters. Because it will be comparing sub( 2, 2 )
, sub( 3, 3 )
, etc. and abandoning trees as soon as it hits a non match, we’re back down to a few hundred comparisons. The directional arrays make it easy to check all the neighboring letters in an orderly, clockwise manner and the search stays on the grid by ignoring any column or row that is less than zero or greater than the maximum number of columns or rows.
What I’m having trouble with is the looping- I’m hoping to find a way to do it that’s not 100 lines of if - then
statements. If anyone has anything, I would be super grateful. Thanks!