具体来说,这是针对 Garry's Mod 的,但我认为这在这个问题上并不重要。我想做的是让一个玩家,并将其值设置为另一个随机玩家(这样每个玩家都有一个随机的“目标”)。我想不重复地做到这一点,这样玩家就不会被分配给他们自己。为了更好地说明:
与该图片的唯一区别是,我希望将每个玩家分配给另一个随机玩家,所以更像是玩家 1 => 玩家 5、玩家 3 => 玩家 2,等等。
这是我目前的代码,但这总是留下一个人未被选中:
validTargets = {}
TargetList = {}
local Swap = function(array, index1, index2)
array[index1], array[index2] = array[index2], array[index1]
end
GetShuffle = function(numelems)
local shuffle = {}
for i = 1, numelems do
shuffle[#shuffle + 1] = i
end
for ii = 1, numelems do
Swap(shuffle, ii, math.random(ii, numelems))
end
return shuffle
end
function assignTargets()
local shuffle = GetShuffle(#playing)
for k,v in ipairs(shuffle) do
TargetList[k] = v
end
SyncTargets()
end
function SyncTargets()
for k,v in pairs(TargetList) do
net.Start("sendTarget")
net.WriteEntity(v)
net.Send(k)
end
end
最佳答案
我有一个 lua 函数,在给定 n
的情况下,它会生成从 1 到 n
的随机数字。
该方法基于popular algorithm生成元素数组的随机排列。
您可以尝试像这样使用它:
local Swap = function(array, index1, index2)
array[index1], array[index2] = array[index2], array[index1]
end
GetShuffle = function(numelems)
local shuffle = {}
for i = 1, numelems do
shuffle[#shuffle + 1] = i
end
for ii = 1, numelems do
Swap(shuffle, ii, math.random(ii, numelems))
end
return shuffle
end
function assignTargets()
local shuffle = GetShuffle(#playing) --assuming `playing` is a known global
for k,v in ipairs(shuffle) do
TargetList[k] = v
end
end
关于random - 从表中获取一个值并将其分配给另一个值,不重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24145749/