编辑代码

      
-- 一个Board的位置信息 {
--     1 , 2 , 3 , 4 , 5 , 第一行
--     6 , 7 , 8 , 9 , 10, 第二行
--     11, 12, 13, 14, 15, 第三行
--     16, 17, 18, 19, 20, 第四行
--     21, 22, 23, 24, 25  第五行
-- }
--[[
259 Johnny's Adventure主题
- 收集一定数量的狗粮
- 道具 蘑菇     蘑菇飞向小狗在标记列向上顶1格 该列没有科顶格子蘑菇消失
- 道具 金蘑菇   蘑菇飞向小狗在标记列向上顶2格 该列没有科顶格子蘑菇消失
- 道具 狗粮     狗粮与小狗之间形成通路,狗粮落下,小狗收集,飞向进度条
- 道具 狗粮袋   狗粮与小狗之间形成通路,狗粮落下,小狗收集,多个狗粮飞向进度条
- 道具 金格子   一列全被消除,金格子落下,小狗收集,大量狗粮飞向进度条
]]

local GRID_STATE = {
    NONE = 0,
    MARK = 1,
}

local PROP_TYPE = {
    NONE = 0,            -- 空
    MUSHROOM = 1,        -- 蘑菇
    GOLD_MUSHROOM = 2,   -- 金蘑菇
    DOG_FOOD = 3,        -- 狗粮
    DOG_FOOD_BAG = 4,    -- 狗粮袋
    GOLD_GRID = 5,       -- 金格子
}

local DefaultClickCellIndex = nil
--[[********************** 可修改参数 start **********************]]
local COLLECT_TARGET = 15    -- bingo目标收集基础狗粮数量
local PROP_COUNT_LIST = {    -- 不同道具数量 规则限制金格子固定5个 蘑菇至少5个
    [PROP_TYPE.MUSHROOM] = 5,
    [PROP_TYPE.GOLD_MUSHROOM] = 3,
    [PROP_TYPE.DOG_FOOD] = 3,
    [PROP_TYPE.DOG_FOOD_BAG] = 3,
    [PROP_TYPE.GOLD_GRID] = 5,
}

local TYPE_TO_COUNT = {    -- 不同狗粮对应基础狗粮数量
    [PROP_TYPE.DOG_FOOD] = 1,
    [PROP_TYPE.DOG_FOOD_BAG] = 2,
    [PROP_TYPE.GOLD_GRID] = 4,
}

local LoopCount = 10000             -- 循环次数。
local DebugOut = false              -- 开启调试。开启后,只会计算一遍,会把每次读球数据打印出来,可以核对是否计算错误。
if DebugOut then
    LoopCount = 1
end
--[[********************** 可修改参数  end  **********************]]
local INVALID_NUM = 0
local MAX_ROW = 5
local MAX_COL = 5
local CELL_COUNT = MAX_ROW * MAX_COL

local TableUtil = {}
TableUtil.shuffle = function(t, startIndex, endIndex)
    if startIndex == nil then
        startIndex = 1
    end
    if endIndex == nil then
        endIndex = #t
    end
    for i = startIndex, endIndex do
        local randomIndex = math.random(startIndex, endIndex)
        local tempValue = t[i]
        t[i] = t[randomIndex]
        t[randomIndex] = tempValue
    end
end

local function index2Coord(index)
    return math.ceil(index / MAX_COL), (index - 1) % MAX_COL + 1
end

local function coord2Index(row, col)
    return (row - 1) * MAX_COL + col
end

local function dump_value_(v)
    if type(v) == "string" then
        v = "\"" .. v .. "\""
    end
    return tostring(v)
end
local function dump(value, description, nesting)
    if type(nesting) ~= "number" then nesting = 3 end

    local lookupTable = {}
    local result = {}

    -- local traceback = string.split(debug.traceback("", 2), "\n")
    -- print("dump from: " .. string.trim(traceback[3]))

    local function dump_(value, description, indent, nest, keylen)
        description = description or "<var>"
        local spc = ""
        if type(keylen) == "number" then
            spc = string.rep(" ", keylen - string.len(dump_value_(description)))
        end
        if type(value) ~= "table" then
            result[#result +1 ] = string.format("%s%s%s = %s", indent, dump_value_(description), spc, dump_value_(value))
        elseif lookupTable[tostring(value)] then
            result[#result +1 ] = string.format("%s%s%s = *REF*", indent, dump_value_(description), spc)
        else
            lookupTable[tostring(value)] = true
            if nest > nesting then
                result[#result +1 ] = string.format("%s%s = *MAX NESTING*", indent, dump_value_(description))
            else
                result[#result +1 ] = string.format("%s%s = {", indent, dump_value_(description))
                local indent2 = indent.."    "
                local keys = {}
                local keylen = 0
                local values = {}
                for k, v in pairs(value) do
                    keys[#keys + 1] = k
                    local vk = dump_value_(k)
                    local vkl = string.len(vk)
                    if vkl > keylen then keylen = vkl end
                    values[k] = v
                end
                table.sort(keys, function(a, b)
                    if type(a) == "number" and type(b) == "number" then
                        return a < b
                    else
                        return tostring(a) < tostring(b)
                    end
                end)
                for i, k in ipairs(keys) do
                    dump_(values[k], k, indent2, nest + 1, keylen)
                end
                result[#result +1] = string.format("%s}", indent)
            end
        end
    end
    dump_(value, description, "- ", 1)

    for i, line in ipairs(result) do
        print(line)
    end
end

local function dump_board(value, description)
    print(description or "")
    local str = "\r\n"
    for row = 1, MAX_ROW, 1 do
        for col = 1, MAX_COL, 1 do
            local cellIndex = coord2Index(row, col)
            local cell = value[cellIndex]
            str = str .. " " .. cell
        end
        if row ~= MAX_ROW then
            str = str .. "\r\n"
        end
    end
    print(str)
end

function table.nums(t)
    local count = 0
    for k, v in pairs(t) do
        count = count + 1
    end
    return count
end

function table.clone(t, nometa)
    local u = {}

    for i, v in pairs(t) do
        if type(v) == "table" then
            u[i] = table.clone(v)
        else
            u[i] = v
        end
    end
    return u
end

local function getOneCell(cellNum, cellType)
    local cell = { }
    cell.mNum_ = cellNum
    cell.mType_ = cellType
    function cell:getDescription()
        local cellNumStr = "  "
        if self.mNum_ ~= INVALID_NUM then
            cellNumStr = tostring(self.mNum_)
            if string.len(cellNumStr) == 1 then
                cellNumStr = " " .. cellNumStr
            end
        end
        
        return string.format("{%s, %s}", cellNumStr, self.mType_)
    end

    function cell:beenTagged()
        assert(self.mNum_ ~= INVALID_NUM, "Cell has been tagged.")
        self.mNum_ = INVALID_NUM
        return self.mType_
    end

    function cell:setType(type)
        self.mType_ = type
    end

    function cell:getType()
        return self.mType_
    end

    return cell
end

local function PrintCurrentState(board, allScore, ballStr, getPropMsg)
    local str = "\r\n"
    for i = 1, MAX_ROW, 1 do
        for j = 1, MAX_COL, 1 do
            local cellIndex = (i - 1) * MAX_COL + j
            local cell = board[cellIndex]
            str = str .. string.format("%s    ", cell:getDescription())
        end
        if i ~= MAX_ROW then
            str = str .. "\r\n"
        end
    end
    if ballStr ~= INVALID_NUM then
        print("Read ball: ", ballStr)
    end
    print(str)
    if getPropMsg and getPropMsg ~= "" then
        print(getPropMsg)
    end
    if allScore then
        print("Current total score: ", allScore) 
    end
    print()
end

local function getIndexRange(index)
    local row, col = index2Coord(index)
    local range = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}} --上 右 下 左
    local indexList = {}
    for dir, offset in ipairs(range) do
        local newRow, newCol = row + offset[1], col + offset[2]
        if newRow >= 1 and newRow <= MAX_ROW and newCol >= 1 and newCol <= MAX_COL then
            local dirIndex = coord2Index(newRow, newCol)
            table.insert(indexList, dirIndex)
        end
    end

    return indexList
end

local function getOneBoardConfig()
    local propConfig = {}          --道具配置表

    --金格子固定在最上面一排 蘑菇没列至少1个 狗粮、狗粮袋、金蘑菇随机分布
    for col = 1, MAX_COL do
        local mushroomRow = math.random(2, 5)
        for row = 1, MAX_ROW do
            local index = coord2Index(row, col)
            if row == 1 then
                propConfig[index] = PROP_TYPE.GOLD_GRID
            elseif mushroomRow == row then
                propConfig[index] = PROP_TYPE.MUSHROOM
            else
                propConfig[index] = PROP_TYPE.NONE
            end
        end
    end

    local emptyList = {}
    for i = 1, CELL_COUNT do
        if propConfig[i] == PROP_TYPE.NONE then
            table.insert(emptyList, i)
        end
    end
    TableUtil.shuffle(emptyList)

    local otherPropcount = 0
    for pType, pCount in pairs(PROP_COUNT_LIST) do
        if pType ~= PROP_TYPE.GOLD_GRID then
            local startIndex = pType == PROP_TYPE.MUSHROOM and 6 or 1
            for i = startIndex, pCount do
                otherPropcount = otherPropcount + 1
                propConfig[emptyList[otherPropcount]] = pType
            end
        end
    end

    return propConfig
end

math.randomseed(os.time())
local function simulateReadBall()
    -- generated read balls.
    local balls = { }
    for i = 1, CELL_COUNT do
        table.insert(balls, i)
    end
    -- generate board.
    local _propConfig = getOneBoardConfig()
    local board = { }
    for i = 1, CELL_COUNT do
        table.insert(board, getOneCell(i, _propConfig[i]))
    end

    -- generate tag.
    local _markList = {}
    local _allMarkList = {}
    local _isBingo = 0
    local _totaleScore = 0
    local _scoreWhen15 = 0
    local _readBallCount = 0
    local _collections = 0

    for i = 1, MAX_ROW * MAX_COL do
        _markList[i] = GRID_STATE.NONE
        _allMarkList[i] = GRID_STATE.NONE
    end

    -- build map for board.
    local numToBoardIndex = { }
    for cellIndex, cell in ipairs(board) do
        if cell.mNum_ ~= INVALID_NUM then
            numToBoardIndex[cell.mNum_] = cellIndex
        end
    end
    TableUtil.shuffle(balls)

    local function removeOnlyGrid(gridIndex)
        if _markList[gridIndex] == GRID_STATE.MARK then
            return
        end
        _markList[gridIndex] = GRID_STATE.MARK
        _allMarkList[gridIndex] = GRID_STATE.MARK
        local pType = _propConfig[gridIndex]
        local row, col = index2Coord(gridIndex)

        --蘑菇一列已被消除则消失
        if pType == PROP_TYPE.MUSHROOM or pType == PROP_TYPE.GOLD_MUSHROOM then
            local removeRow = nil
            for i = MAX_ROW, 1, -1 do
                local index = coord2Index(i, col)
                if _allMarkList[index] == GRID_STATE.NONE then
                    removeRow = i
                    break
                end
            end
            if removeRow then
                local removeList = {coord2Index(removeRow, col)}
                if pType == PROP_TYPE.GOLD_MUSHROOM and removeRow > 1 then
                    table.insert(removeList, coord2Index(removeRow - 1, col))
                end
                for _, index in ipairs(removeList) do
                    _allMarkList[index] = GRID_STATE.MARK
                end
                for _, index in ipairs(removeList) do
                    removeOnlyGrid(index)
                end
            else
                _propConfig[gridIndex] = PROP_TYPE.NONE
                pType = PROP_TYPE.NONE
            end
        end

        --遍历该列的消除情况
        for i = MAX_ROW, 1, -1 do
            local index = coord2Index(i, col)
            if _markList[index] == GRID_STATE.MARK then
                local mType = _propConfig[index]
                if TYPE_TO_COUNT[mType] then
                    _collections = _collections + TYPE_TO_COUNT[mType]
                    _propConfig[index] = PROP_TYPE.NONE
                end
            else
                break
            end
        end

        if DebugOut then
            dump_board(_markList, gridIndex .. " " .. pType)
        end
    end

    --算法逻辑
    local function updateLogic(gridIndex)
        removeOnlyGrid(gridIndex)
    end
    
    local function checkBingo()
        if _totaleScore >= COLLECT_TARGET then
            _isBingo = 1
            return true
        end
        return false
    end

    -- read balls
    while #balls > 0 do
        _readBallCount = _readBallCount + 1
        local ballNum = balls[1]
        table.remove(balls, 1)
        local ballIndex = numToBoardIndex[ballNum]
        assert(ballIndex ~= nil, string.format("Cant find ball num index: %d", ballNum))
        assert(board[ballIndex].mNum_ == ballNum, "NumToBoardIndex Map Error!")

        board[ballIndex]:beenTagged()
        if ballIndex ~= DefaultClickCellIndex then
            updateLogic(ballIndex)
        end

        _totaleScore = _collections

        if _totaleScore > COLLECT_TARGET then
            _totaleScore = COLLECT_TARGET
        end
        if DebugOut then
            PrintCurrentState(board, _totaleScore, ballNum)
        end
        if _readBallCount <= 15 then
            _scoreWhen15 = _totaleScore
        end

        if checkBingo() then
            break
        end
    end

    return _readBallCount, _scoreWhen15
end

local bingoNeedReadBall = { }
for i = 1, CELL_COUNT do
    bingoNeedReadBall[i] = 0
end
local allTotalScoreWhen15 = 0

for i = 1, LoopCount do
    local ballCountCompleteBingo, snailNodePositionWhen15 = simulateReadBall()
    bingoNeedReadBall[ballCountCompleteBingo] = bingoNeedReadBall[ballCountCompleteBingo] + 1
    allTotalScoreWhen15 = allTotalScoreWhen15 + snailNodePositionWhen15
end
local bingoTotal = { }
bingoTotal[1] = 0
for i = 2, CELL_COUNT do
    bingoTotal[i] = bingoNeedReadBall[i] + bingoTotal[i - 1]
end

print("标记格子数量发生bingo:", table.concat(bingoNeedReadBall, ", "))
print("标记累计发生bingo数量:", table.concat(bingoTotal, ", "))
print("第15次读球分:", allTotalScoreWhen15 / LoopCount)
print("第15次读球累计bingo数:", bingoTotal[15])