ItemStack.cpp 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. #include "ItemStack.h"
  2. #include "Item.h"
  3. ItemStack::ItemStack(Item* item, int currentSize, int maxSize)
  4. : ReferenceCounter(),
  5. item(item),
  6. size(currentSize),
  7. maxSize(maxSize)
  8. {}
  9. ItemStack::ItemStack(Item* item, int currentSize)
  10. : ItemStack(item, currentSize, item->getMaxStackSize())
  11. {}
  12. ItemStack::~ItemStack()
  13. {
  14. if (item) item->release();
  15. }
  16. void ItemStack::setMaxSize(int size)
  17. {
  18. maxSize = size;
  19. }
  20. ItemStack* ItemStack::split(int size)
  21. {
  22. size = MIN(size, this->size);
  23. this->size -= size;
  24. ItemStack *result = new ItemStack(
  25. dynamic_cast<Item*>(item->getThis()), size, item->getMaxStackSize());
  26. if (size == 0)
  27. {
  28. item->release();
  29. item = 0;
  30. }
  31. return result;
  32. }
  33. Item* ItemStack::extractFromStack()
  34. {
  35. if (size == 0) return 0;
  36. --size;
  37. Item* result = item->zItemType()->cloneItem(item);
  38. if (size == 0)
  39. {
  40. item->release();
  41. item = 0;
  42. }
  43. return result;
  44. }
  45. bool ItemStack::addToStack(Item* item)
  46. {
  47. if (size < maxSize && (size == 0 || this->item->canBeStackedWith(item)))
  48. {
  49. if (!this->item)
  50. {
  51. this->item = item->zItemType()->cloneItem(item);
  52. }
  53. ++size;
  54. item->release();
  55. return true;
  56. }
  57. item->release();
  58. return false;
  59. }
  60. void ItemStack::addItemStack(ItemStack* zItemStack)
  61. {
  62. if (item && zItemStack->zItem()->canBeStackedWith(item))
  63. {
  64. int numToAdd = MIN(zItemStack->getSize(), maxSize - size);
  65. size += numToAdd;
  66. zItemStack->size -= numToAdd;
  67. }
  68. }
  69. bool ItemStack::isStackable(Item* zItem) const
  70. {
  71. return size == 0 || item->canBeStackedWith(zItem);
  72. }
  73. const Item* ItemStack::zItem() const
  74. {
  75. return item;
  76. }
  77. int ItemStack::getSize() const
  78. {
  79. return size;
  80. }
  81. int ItemStack::getMaxSize() const
  82. {
  83. return maxSize;
  84. }