Share-a-function thread
Posted: Tue Mar 04, 2008 1:37 am
To encourage everyone to give something back to the community, share a small (or big) helper function you are frequently using in your scripting. Maybe some of thease would fit in the distro as well.
To start off, here's two of our item functions.
To start off, here's two of our item functions.
Code: Select all
/*
Reaches
Checks if player reaches the wanted item.
Params:
Char Who uses
Item What
~Integer Options
~String What item name will be messaged, if 0 sends nothing
Returns: true or error
*/
enum OPTIONS
OPT_UNMOVABLE := 0x1 // Allowing unmovables
endenum
function Reaches( who, item, options := 0, what := "item" )
var msg;
if (!Accessible(who, item))
msg := " is unreachable.";
elseif (!(options & OPT_UNMOVABLE) && item.movable == 0)
msg := " is unmovable.";
elseif (!ReserveItem(item))
msg := " is already in use.";
elseif (Distance(who, item) > 2)
msg := " is too far away.";
elseif (item.GetProp("Vendored"))
// Player merchants, remove if not needed
msg := " is not yours.";
else
return 1;
endif
// Does not reach
if (what)
SendSysMessageUC(who, CAscZ("The "+what+msg));
endif
return 0;
endfunction
Code: Select all
/*
ItemEquip
Acts as EquipItem, but removes weared equipment of the same layer.
Params:
Char who
Item Equipment to be weared
~Integer Options in bit-form
OPT_FORCE Skip reaches() check
OPT_LIST_STRIPPED Lists and returns removed items
Returns:
item array if OPT_LIST_STRIPPED is set
1 if item is equipped
error when failed
*/
enum EQUIP_OPTIONS
OPT_FORCE := 1,
OPT_LIST_STRIPPED := 2
endenum
function ItemEquip( who, itemref, options := 0 )
if (!(options & OPT_FORCE))
var res := Reaches(who, itemref);
if (res == error)
return res;
endif
endif
var result := 0;
var stripped := array;
// Item already equpped (core EquipItem() returns negative if item is already weared)
if (itemref.container == who)
result := 1;
elseif (itemref.isa(POLCLASS_EQUIPMENT))
result := EquipItem(who, itemref);
if (!result)
// Conflicting items are unequipped
var itemlayer := itemref.layer;
if (itemlayer == 1 || itemlayer == 2)
// Layer 2 needs layer 1 to be empty and vice versa
itemlayer := { 1, 2 };
else
itemlayer := { itemlayer };
endif
foreach layer in itemlayer
var equipped := GetEquipmentByLayer(who, layer);
if (equipped)
// Moving conflicting equipment to backpack or ground
if (!MoveItemToContainer(equipped, who.backpack))
MoveObjectToLocation(equipped, who.x, who.y, who.z, who.realm, MOVEOBJECT_FORCELOCATION);
endif
if (options & OPT_LIST_STRIPPED)
stripped.append(equipped);
endif
endif
endforeach
// New try
result := EquipItem(who, itemref);
endif
endif
if (options & OPT_LIST_STRIPPED)
return stripped;
endif
return result;
endfunction