local a = {
[1] = {1, 2},
[2] = {3, 4},
[3] = {5, 6},
[4] = {7, 8},
[5] = {9, 10}
}
local b = {1, 2, 3, 4, 5}
local maxSize = 0
local c = {}
math.randomseed(os.time())
local function getRandomPlayerAndRemove(groupKey)
if #a[groupKey] == 0 then
error(string.format("错误:组 %d 为空", groupKey))
end
local index = math.random(#a[groupKey])
local player = a[groupKey][index]
c[#a[groupKey]] = c[#a[groupKey]] -1
if #a[groupKey] > 1 then
c[#a[groupKey]-1] = c[#a[groupKey]-1] + 1
end
while c[maxSize] == 0 do
maxSize = maxSize - 1
end
table.remove(a[groupKey], index)
return player
end
local function getGroupIndex()
if #b == 0 then
return nil
end
local index = math.random(#b)
local element = b[index]
table.remove(b, index)
return element
end
local function matchPlayers()
local matches = {}
local totalPlayers = 10
local numOnematch = 2
maxSize = 2
local numMatches = totalPlayers / numOnematch
for matchid = 1, numMatches do
local i
if (numMatches - matchid + 1 == maxSize) and (maxSize > 1) then
for index = 1, #b do
if #a[b[index]] == maxSize then
i = b[index]
table.remove(b,index)
break
end
end
else
i = getGroupIndex()
end
if not i then
print("没有找到合适的组 i")
break
end
local j = getGroupIndex()
if not j then
print("没有找到合适的组 j")
break
end
local player_i = getRandomPlayerAndRemove(i)
local player_j = getRandomPlayerAndRemove(j)
if player_i and player_j then
print(string.format("对战: 玩家 %d vs 玩家 %d", player_i, player_j))
table.insert(matches, {i, j})
else
error("匹配失败:无法从组中移除玩家")
end
if #a[i] > 0 then
table.insert(b, i)
end
if #a[j] > 0 then
table.insert(b, j)
end
end
print("一局完成了!")
return matches
end
local function selfCheck()
for _ = 1, 100000 do
a = {
[1] = {1, 2},
[2] = {3, 4},
[3] = {5, 6},
[4] = {7, 8},
[5] = {9, 10}
}
b = {1, 2, 3, 4, 5}
c = {0, 5}
local matches = matchPlayers()
local allMatched = true
for _, group in pairs(a) do
if #group > 0 then
allMatched = false
break
end
end
if not allMatched then
error("检测失败:有玩家轮空")
end
for _, match in ipairs(matches) do
local i, j = match[1], match[2]
if i == j then
error(string.format("检测失败:匹配中有同组玩家"))
end
end
end
print("检测通过:所有玩家匹配完成且无轮空无同组")
end
selfCheck()