Search code examples
luatouchtic-tac-toe

Tic Tac Toe (Lua (Touch Lua)) detecting 3 in a row?


So I think I have a great setup, each "Button" has a column and row. Here's my current function:

function CheckForWin()
   local X = {}
   local O = {}
   for i,v in pairs(ClosedButtons) do
      if v.title == "X" then
         table.insert(X, v)
      elseif v.title == "O" then
         table.insert(O, v)
      end
      for i,v in pairs(X) do
        --Find 3 Xs in a row
      end
      for i,v in pairs(O) do
        --Find 3 Os in a row
      end
   end
end

My question, is how should I detect?

A 3 in the row would occur if 3 buttons had the same row or column right? But the diagonal one would be a special case, it would be if 3 buttons had the same row and column in them?

Should I keep a table to check and see how many buttons have a column of 1/2/3 and a table to check how many buttons have a row of 1/2/3, and a table to see how many have the same row/column? To me that seems incredibly inefficient.

Is there a better way I should know before I start using a bunch of tables?

EDIT: Just to be clear, the buttons are tables with the properties "column" and "row"


Solution

  • To do this you would have to keep track of every row and column tiles, check for 3 in a row directly. Although inefficient I do not see any other way.