Inventory System - GUI

I had posted not one but two articles on Inventory Management, but I found that some users were still unclear and had no idea on how to use or include it in an application. I tried to find out what would help them to understand, so I have some code that will help the developer to understand how it all works with a little GUI demo too.

The previous Articles can be found at here and here

Now what we shall do for this tutorial is create 5 coloured block, that are randomly placed on the screen (as things would be in the game) and as we click on them, we get them to appear in our inventory box which is at the bottom of the screen. Then if we click on the items whilst they are in our inventory, we print to the console that we are using that item. I have left it as en exercise for the reader to work out dealing with the objects, re-arrange it and remove that item back to the screen.

What you've all been waiting for, the code...

--Inventory Example with picking up items and using them
-- Author : Jayant C Varma []
-- © 2011, OZ Apps (
--create 5 elements to pick up

local i, randX, randY
local colours = {

local boxsize = 25
local index = 1

local _W = display.contentWidth
local _H = display.contentHeight


local inventoryBox = display.newRoundedRect(10,
           _H-((boxsize+8)*2), _W-20, ((boxsize+5)*2),10)

local function quad(colorTable)
	return colorTable[1],colorTable[2],colorTable[3]

for i=1,#colours do
	randX = math.random(1,_W-15)
	randY = math.random(1,_H-((boxsize+15)*2))
	local box = display.newRect(randX, randY, boxsize, boxsize)
	box.isWild = true	--Indicates if the item is in the inventory or not
	box.itemNumber = i	-- a tag for identifying the item number
	local function addItemToInventory(thisItem)
		if thisItem.isWild==true then
			thisItem.isWild = false
			local x = 10 + (index * (boxsize+10))
			local y = _H - boxsize - 10
			box.x = x
			box.y = y
			index = index + 1
			print("Picked up object " .. thisItem.itemNumber)
	local function useItemFromInventory(thisItem)
		if thisItem.isWild == false then
			print("Using the object " .. thisItem.itemNumber)
			--on using, the object can be removed or placed back like dropping it
			thisItem.isWild = true
			randX = math.random(1,_W-15)
			randY = math.random(1,_H-50)
			box.x = randX
			box.y = randY
			index = index - 1
			--Adjust all Items

	local function onTap(event)
		local target =
		if target.isWild == true then --This is not in the inventory
			addItemToInventory(target) --so add it into the inventory
			useItemFromInventory(target) -- This is in the inventory, so use it

have fun...


Popular Posts