编辑代码

-- 一个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  第五行
-- }
--[[
252 Gift Delivery 圣诞节主题
- 收集X个礼物盒
- 道具 普通礼物
- 道具 礼物袋 生成两个礼盒 等待激活后又重新生成
- 道具 加倍星星 礼物车收集的礼盒翻倍 礼物车已加倍时等待
- 道具 激活星星 激活礼物袋 没有空礼物袋时等待
]]

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

local PROP_TYPE = {
    NONE = 0,                    -- 空
    GIFT_BOX = 1,                -- 礼物盒
    GIFT_BAG = 2,                -- 礼物袋
    DOUBLE_STAR = 3,             -- 翻倍星星
    ACTIVATE_STAR = 4,           -- 激活星星
}

local COLLECT_STATE = {          -- 收集队列状态
    NORMAL = 1,                  -- 正常
    DOUBLE = 2,                  -- 加倍
}

local DefaultClickCellIndex = nil
--[[********************** 可修改参数 start **********************]]
local COLLECT_TARGET = 20    --bingo收集数量

local PROP_COUNT_LIST = {--对应道具数量
    [PROP_TYPE.GIFT_BOX] = 9,
    [PROP_TYPE.GIFT_BAG] = 4,
    [PROP_TYPE.DOUBLE_STAR] = 2,
    [PROP_TYPE.ACTIVATE_STAR] = 3,
}
local MAX_COLLECT_QUEUE = 3   -- 收集队列数

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

--格子编号转坐标 返回row col 左->右 上->下
local function grid2Pos(grid)
    return math.ceil(grid / MAX_COL), (grid - 1) % MAX_ROW + 1
end

local function pos2Grid(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 = pos2Grid(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

function table.indexof(array, value, begin)
    for i = begin or 1, #array do
        if array[i] == value then return i end
    end
    return false
end

function table.removebyvalue(array, value, removeall)
    local c, i, max = 0, 1, #array
    while i <= max do
        if array[i] == value then
            table.remove(array, i)
            c = c + 1
            i = i - 1
            max = max - 1
            if not removeall then break end
        end
        i = i + 1
    end
    return c
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 getOneBoardConfig()
    local propConfig = {}

    local allProp = {}
    for pType, pCount in pairs(PROP_COUNT_LIST) do
        for idx = 1, pCount, 1 do
            table.insert(allProp, pType)
        end
    end
    for idx = 1, MAX_ROW * MAX_COL, 1 do
        propConfig[idx] = allProp[idx] or PROP_TYPE.NONE
    end
    TableUtil.shuffle(propConfig)

    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 _isBingo = 0
    local _totaleScore = 0
    local _scoreWhen15 = 0
    local _readBallCount = 0

    local _markList = {}
    for i = 1, MAX_ROW * MAX_COL do
        _markList[i] = GRID_STATE.NONE
    end
    local _collections = 0
    local _usedBagList = {}    -- 使用完的礼物袋
    local _waitPropList = {}   -- 标记出来不满足使用条件的道具
    local _collectQueue = {}   -- 单轮收集礼物列表
    local _collectState = COLLECT_STATE.NORMAL
    
    -- 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 checkBingo()
        if _collections >= COLLECT_TARGET then
            _isBingo = 1
            return true
        end
        return false
    end

    local function addGift(addCount)
        --已经bingo 不再处理剩余道具
        if checkBingo() then
            return
        end

        table.insert(_collectQueue, addCount)
        if #_collectQueue >= MAX_COLLECT_QUEUE then
            for _, score in ipairs(_collectQueue) do
                _collections = _collections + score
                if _collectState == COLLECT_STATE.DOUBLE then
                    _collections = _collections + score
                end
            end
            _collectQueue = {}
            _collectState = COLLECT_STATE.NORMAL
        end
    end

    local function checkWait()
        --已经bingo 不再处理剩余道具
        if checkBingo() then
            return
        end

        for idx, grid in ipairs(_waitPropList) do
            local pType = _propConfig[grid]
            if pType == PROP_TYPE.DOUBLE_STAR then
                if _collectState == COLLECT_STATE.NORMAL then
                    _collectState = COLLECT_STATE.DOUBLE
                    table.remove(_waitPropList, idx)
                    checkWait()
                    break
                end
            elseif pType == PROP_TYPE.ACTIVATE_STAR then
                local usedBagCount = #_usedBagList
                if usedBagCount > 0 then
                    for i = 1, usedBagCount, 1 do
                        addGift(2)
                    end
                    table.remove(_waitPropList, idx)
                    checkWait()
                    break
                end
            end
        end
    end

    local function removeOnlyGrid(gridIndex)
        if _markList[gridIndex] == GRID_STATE.MARK then
            return
        end
        _markList[gridIndex] = GRID_STATE.MARK
        local propType = _propConfig[gridIndex]
        
        --标记出的能直接加礼盒 先加礼盒 剩下的道具统一在标记完成后检查
        if propType == PROP_TYPE.GIFT_BOX then
            addGift(1)
        elseif propType == PROP_TYPE.GIFT_BAG then
            addGift(2)
            table.insert(_usedBagList, gridIndex)
        else
            table.insert(_waitPropList, gridIndex)
        end

        checkWait()
    end

    --算法逻辑
    local function updateLogic(gridIndex)
        removeOnlyGrid(gridIndex)
    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 > targetCount 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次读球:累计bingo数量, 分:", bingoTotal[15], allTotalScoreWhen15 / LoopCount)