2012-09-27 33 views
0

我已經做了大量的關於點和點擊遊戲的Lua和日冕的invetory系統的研究。 我遇到過這個例子,我正在做類似的事情,但我需要一個動態庫存系統。 我的意思是如果我有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 

回答

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) 
+0

感謝您的幫助,環顧四周,玩了很多後,我覺得有很多方法可以創建一個動態庫存系統。因爲我已經進入了7個月的編程,並仍在學習;有時我傾向於認爲,只能有一種方法或解決方案。 –

2

基本上你會做的是循環所有庫存插槽並檢查插槽是否爲空。如果它是空的,將物品放入該插槽並停止循環。如果不是,請轉到下一個。

如果您想從清單中刪除物品,您只需撥打table.delete(myInventoryBag, slotToEmpty)即可。

對於頁面,您只需要有一個page變量。繪製庫存插槽時,只需從插槽(page-1) * 4 + 1page * 4循環。

(編輯:我會強烈建議使用適當的縮進,因爲這將使得代碼更更具可讀性。)

+0

我有點糊塗頁面上增值經銷商,並且您已經使用的數字。 –

+0

我想他的意思是有一個變量來跟蹤玩家所在的頁面,然後用它來檢查所有的插槽。 – Jutanium