I'm so confused.

I started making my code off of @Eric’s code on flood it. I’m about 50% done and this bug is annoying the heck out of me. Here is @Eric’s code.

function setup()
    displayMode(FULLSCREEN)
    
    grid = {}  
    turnsLeft = 25
    
    local r,c
    for r = 1,14 do
        grid[r] = {}
        for c = 1,14 do
            grid[r][c] = math.random(6)
        end
    end
    
    colors = {}
    colors[1] = color(255, 0, 0, 255)
    colors[2] = color(0, 0, 255, 255)
    colors[3] = color(0, 255, 0, 255)
    colors[4] = color(255, 255, 0, 255)
    colors[5] = color(255, 0, 255, 255)
    colors[6] = color(0, 255, 255, 255)
end

function draw()
    background(40, 40, 50)

    pushStyle()
    noSmooth()
    local r,c,col
    for r, row in ipairs(grid) do
        for c, cellVal in ipairs(row) do
            col = colors[cellVal]
            fill(col.r, col.g, col.b)
            rect(((c - 1) * 50) + 300, ((r - 1) * 50) + 25, 50, 50)
        end
    end
    popStyle()
    
    pushStyle()
    strokeWidth(3)
    stroke(255, 255, 255, 255)
    for c, col in ipairs(colors) do
        fill(col.r, col.g, col.b)
        ellipse(150, ((c - 1) * 120) + 100, 100)
    end
    popStyle()
    
    text(turnsLeft, 15, HEIGHT - 15)
end

function touched(touch)
    
    if touch.state == ENDED and turnsLeft > 0 then
        local x,y,c
        x = 150
        for c in ipairs(colors) do
            y = ((c - 1) * 120) + 100
            if lineDist(x, y, touch.x, touch.y) <= 50 then
                floodFill(grid, 14, 1, grid[14][1], c)
                turnsLeft = turnsLeft - 1
            end
        end
    end
end

function lineDist(x1, y1, x2, y2)
    return math.sqrt(((x2 - x1)^2) + ((y2 - y1)^2))
end

function floodFill(grid, row, col, target, new)
    if row < 1 or col < 1 or row > #grid or col > #grid[row] then return end
    
    if grid[row][col] == target then
        grid[row][col] = new
        floodFill(grid, row + 1, col, target, new)
        floodFill(grid, row - 1, col, target, new)
        floodFill(grid, row, col + 1, target, new)
        floodFill(grid, row, col - 1, target, new)
    end
end

I always get a stack overflow error if I press a selector twice in a row. For example, pressing red, and then red again will stop the game. I really need help and I’m hoping it’s not a stupid error. I’m new to recursive methods like this. Thanks in advance

It’s because there ends up being an infinite loop with the recurrsion of the floodFill call. I was kinda lazy about it and just did the simplest form of it. A better way would be to probably have a list of cells the floodFill algorithm has visited, so it doesn’t keep going back and forth among the same ones. Another quick and dirty fix is to add

and grid[14][1] ~= c

As part of the second if in the touched function.

.@Eric thanks for the help. it works pretty well. thanks