lua学习笔记---5.斗地主游戏工具类

525 阅读2分钟

游戏大体框架

  • 描述一张牌:使用16进制(十位表示花色,个位表示点数)
  • 花色:红黑梅方 大小王(0 - 4)
  • 点数:A - k(1 - 13)
  • 牌值:对应的大小顺序排列(3 - k:3-13 A:14 2:15 小王:18 大王:19)

例如

  • 红桃K:0x0D
  • 黑桃A:0x11

代码部分

创建牌的工具类

local CardUtils = {} --牌的工具类

创建一副牌

function CardUtils:newCards()
    return
    {
        0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0A,0x0B,0x0C,0x0D,
        0x11,0x12,0x13,0x14,0x15,0x16,0x17,0x18,0x19,0x1A,0x1B,0x1C,0x1D,
        0x21,0x22,0x23,0x24,0x25,0x26,0x27,0x28,0x29,0x2A,0x2B,0x2C,0x2D,
        0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,0x39,0x3A,0x3B,0x3C,0x3D,
        0x41,0x42
    }
end

求牌的花色

function CardUtils:getCardColor(card)
    return math.floor(card / 0x10)
end

求牌的点数

function CardUtils:getCardPointNumber(card)
    return card % 0x10
end

判断是否是王牌

function CardUtils:isKingCard(card)
    local color =  self:getCardColor(card)
    -- 花色为4的是大小王
    return color == 4
end

求牌的牌值

function CardUtils:getCardValue(card)
    local point = self:getCardPointNumber(card) -- 获得点数
    -- 如果是大小王,则大小王的值分别是15 14
    if self:isKingCard(card) then
        return 17 + point 
    end
    if point == 1 or point == 2 then
        return 13 + point
    else
        return point
    end
end

洗牌

function CardUtils:shuffle(allCards)
    for i = 1,#allCards do
        local j = math.random(1, #allCards)
        allCards[i],allCards[j] = allCards[j],allCards[i]
    end
end

发牌

function CardUtils:sendCards(allCards)
    local handCards = {}
    for i = 1,3 do
        handCards[i] = {}
        for j = 1,17 do
           local card = table.remove(allCards) -- 取出所剩的最后一张牌
           table.insert(handCards[i],card) -- 插入到手牌的末尾 
        end
    end
    return handCards
end

牌排序

function CardUtils:sort(handCards)
    table.sort(handCards, function (card1,card2)
        local value1 = self:getCardValue(card1)
        local value2 = self:getCardValue(card2)
        local color1 = self:getCardColor(card1)
        local color2 = self:getCardColor(card2)
        if value1 ~= value then
            -- 先比较牌值
            return value1 > value2
        else
            -- 再比较花色
            return color1 > color2
        end
    end)
end

打印整副牌

function CardUtils:print(handCards)
    local s = ""
    for i = 1,#handCards do
        -- local color = self:getCardColor(handCards[i])
        -- local point = self:getCardPointNumber(handCards[i])
        s = s .. string.format("0x%02x",handCards[i]) .. " "
    end
    print(s)
end

测试代码

local allCards = CardUtils:newCards()  --创建一副牌
CardUtils:shuffle(allCards)-- 打乱顺序
local handCards = CardUtils:sendCards(allCards) -- 发牌

for i = 1,#handCards do
    CardUtils:sort(handCards[i])
    CardUtils:print(handCards[i])
end
return CardUtils