0

我在 Lua 和 Corona 中对点击游戏的库存系统进行了大量研究。我遇到过这个例子,我正在做类似的事情,但我需要一个动态库存系统。我的意思是,如果我有 4 个插槽,并且它们都已满,则第五个对象转到下一个插槽,因此右侧会有一个箭头,因此我可以单击 ; 并转到下一页。假设有 5 个项目,我有 4 个插槽,第五个插槽将在下一页上。我使用第三个项目,然后第三个插槽将是空的,所以我希望第四个和第五个项目自动移回第三个和第四个插槽。我很难弄清楚这一点。感谢提前。

local myInventoryBag={}
local maxItems = 10 -- change this to how many you want

myInventoryBag[5]=3 -- Hammer for instance
myInventoryBag[4]=7 -- A metal Pipe for instance

local function getImageForItem(thisItem)
    local itemNumber = tonumber(thisItem)
    local theImage=""

    if itemNumber==3 then
        theImage="hammer.png"
    elseif itemNumber == 7 then
        theImage="metalpipe.png"
    elseif ... -- for other options
        ...
    else
        return nil
    end

    local image = display.newImage(theImage)
    return image
end

local function displayItems()
    local i
    for i=1,#myInventoryBag do
        local x = 0  -- calculate based on the i
        local y = 0 --  calculate based on the i

        local image = getImageForItem(myInventoryBag[i])

        if image==nil then return end

        image.setReferencePoint(display.TopLeftReferencePoint)
        image.x = x
        image.y = y
    end
end
4

2 回答 2

3
local itemImages =
{
    [0] = display.newImage('MISSING_ITEM_IMAGE.PNG'),
    [3] = display.newImage('hammer.png'),
    [7] = display.newImage('metalpipe.png'),
}

function getImageForItem(itemId)
    return itemImages[itemId] or itemImages[0]
end

local myInventoryBag={}
local maxItems = 10 -- change this to how many you want
local visibleItems = 4 -- show this many items at a time (with arrows to scroll to others)

-- show inventory items at index [first,last]
local function displayInventoryItems(first,last)
    local x = 0 -- first item goes here
    local y = 0 -- top of inventory row
    for i=first,last do
        image = getImageForItem(myInventoryBag[i])
        image.x = x
        image.y = y
        x = x + image.width
    end
end

-- show inventory items on a given "page"
local function displayInventoryPage(page)
    page = page or 1 -- default to showing the first page
    if page > maxItems then
        -- error! handle me!
    end
    local first = (page - 1) * visibleItems + 1
    local last = first + visibleItems - 1
    displayInventoryItems(first, last)
end

myInventoryBag[5] = 3 -- Hammer for instance
myInventoryBag[4] = 7 -- A metal Pipe for instance

displayInventoryPage(1)
displayInventoryPage(2)
于 2012-09-27T21:57:07.137 回答
2

基本上你要做的是遍历所有库存槽并检查槽是否为空。如果它是空的,则将项目放入该插槽并停止循环。如果不是,请转到下一个。

如果你想从库存中删除一个项目,你可以简单地调用table.delete(myInventoryBag, slotToEmpty).

对于页面,您只需要一个page变量。绘制库存插槽时,只需从插槽循环(page-1) * 4 + 1page * 4.

(编辑:我强烈建议使用适当的缩进,因为它会使代码更具可读性。)

于 2012-09-27T07:51:04.610 回答