Skip to content

Instantly share code, notes, and snippets.

@diazvictor
Last active February 28, 2021 05:45
Show Gist options
  • Save diazvictor/6fe3372bce79587a3c21123a19881cb1 to your computer and use it in GitHub Desktop.
Save diazvictor/6fe3372bce79587a3c21123a19881cb1 to your computer and use it in GitHub Desktop.
Small Example Of A Game Inventory With MoonScript
-- I create the Inventory class
class Inventory
-- What to do when the class is initialized
new: =>
@items = {}
--- I look at what I carry in my inventory.
-- @return bool true or false if there are items.
getItem: =>
if #@items != 0 then
print "You carry:"
for _, inventory in pairs @items do
print "* #{inventory.desc}"
return true
else
print "You have nothing."
return false
--- I check if an item exists.
-- @param string item name.
-- @return bool true or false if the item exists.
hasItem: (name) =>
for _, inventory in pairs @items
if name == inventory.name
return true
return false
--- I add an item to the inventory.
-- @param string item name.
-- @param string item description.
-- @return number the number of items in the inventory.
addItem: (name, desc) =>
table.insert @items, {name: name, desc: desc}
return #@items
--- I remove an item from inventory.
-- @param string item name.
-- @return bool true or false if the item has been removed successfully.
removeItem: (name) =>
for i, inventory in pairs @items
if name == inventory.name
table.remove @items, i
return true
return false
-- BackPack inherits methods and properties from Inventory
class BackPack extends Inventory
--- I add an item to the inventory but first I check if the limit has not
-- been reached.
-- @param string item name.
-- @param string item description.
-- @return number the number of items in the inventory.
size: 10
addItem: (name, desc) =>
if #@items >= @size
print "backpack is full"
return false
else
super name, desc
return true
player = BackPack!
player\addItem "lantern", "an oil lantern"
player\addItem "camera", "a camera, it seems to be discharged"
player\addItem "sword", "a sword with the blessing of the wind"
player\getItem!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment