Help with Tic-Tac-Toe game

I am working on a “Tic Tac Toe” game with a friend. A problem I came across is how would I know if there is a “3 in a row”? I wanted to use “TextButtons” and switching the text to O’s and X’s but that wont work for figuring out if its a “3 in a row”. If you have any ideas on how to implement it that would be awesome thanks! [No code at the moment just brain storming]

I thought of a basic way to do it and here’s an example:

{
r1 = {"x","-","-"}; --if the first row's first tile is an X then
r2 = {"-","x","-"}; --if the second row's second tile is an X then
r3 = {"-","-","x"}; --if the third row's third tile is an X then
}
local board = {
	{0, 0, 0},
	{0, 0, 0},
	{0, 0, 0}
}

local function checkRows()
	for row = 1, #board do
		-- start at first element in each row
		local first = board[row][1]
		-- and compare rest of the row to the first element
		for column = 2, #board[row] do
			-- if an element in the row doesn't match or is empty (0), then continue on to the next row
			if board[row][column] == 0 or board[row][column] ~= first then
				break
			elseif column == #board[row] then
				-- return winner if whole row matches
				local winner = board[row][column]
				print("Winner:", winner)
				return winner
			end
		end
	end
end

For the columns you would have to do the same check but you would need to iterate the columns first and then the rows inside the columns loop (basically the reverse)

For the diagonal you can just make some sort of loop that checks board[i][i] and board[#board - i + 1][i] for the other direction

image

image

image

6 Likes

How did you get it to print like that? Cant seem to get printing to work.

local function display()
	for i, row in ipairs(board) do
		-- replace 0's with empty space and concatenate the Rows
		local s = string.gsub(table.concat(row, " | "), "0", "   ")
		print(s)
	end
end
1 Like

For some reason the winner isnt benig printed. I was setting the 0’s to 1’s if thats why.

You need to call checkRows after you set

Ex:

for i = 1, 3 do
	board[3][i] = 1
end

checkRows()
> Winner: 1
2 Likes

can i get Ex? i still confused how does it work