Lua实现洗牌算法

245 阅读1分钟
--洗牌算法:Knuth-Durstenfeld Shuffle 
--发牌时,从未发牌堆中抽1张,与当前牌交换并发出。
local Poker = {}
function Poker.new()
	Poker.__index = Poker
	local instance = setmetatable({}, Poker)
	instance:ctor()
	return instance
end
function Poker:ctor()
	self.cards = {}
	self.curIdx = 1
	self.length = 52
	for i=1,self.length do
		table.insert(self.cards,i)
	end
	math.randomseed(os.time())
	return Poker
end

function Poker:deal()
	local idx = math.random(self.curIdx,self.length)
	local newCard = self.cards[idx]
	self.cards[idx] = self.cards[self.curIdx]
	self.cards[self.curIdx] = newCard
	self.curIdx = self.curIdx + 1
	if self.curIdx > self.length then
		self.curIdx = 1
	end
	return newCard
end

local poker = Poker.new()
for i=1,poker.length do
	print("card = ",poker:deal())
end