Inventory.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. class Inventory {
  2. constructor() {
  3. }
  4. init() {
  5. this.hold = [];
  6. this.hold.push({ name: "₩", type: "woolong", amount: 10000 });
  7. this.hold.push({ name: "Spare Part", type: "sparepart", amount: 1 });
  8. this.hold.push({ name: "Scrap Metal", type: "scrap", amount: 2 });
  9. this.hold.push({ name: "Hydrogen", type: "element", amount: 128 });
  10. }
  11. getAll() {
  12. return this.hold;
  13. }
  14. getAllByType(type) {
  15. return this.hold.filter((item) => item.type == type);
  16. }
  17. getItem(name) {
  18. return this.hold.find((item) => item.name == name);
  19. }
  20. consumeShipRepairMaterials() {
  21. let parts = this.getAllByType("sparepart");
  22. if (!parts || parts.length == 0) { return false; }
  23. return this.consumeItem(parts[0], 1);
  24. }
  25. consumeCraftingMaterials(ingredients) {
  26. let consumed = [];
  27. for (let index = 0; index < ingredients.length; index++) {
  28. let ingredient = ingredients[index];
  29. let item = this.getItem(ingredient.name);
  30. if (!item) {
  31. this.addItems(consumed);
  32. return false;
  33. }
  34. let itemConsumed = this.consumeItem(item, ingredient.amount);
  35. if (!itemConsumed) {
  36. this.addItems(consumed);
  37. return false;
  38. }
  39. consumed.push(itemConsumed);
  40. }
  41. return true;
  42. }
  43. consumeShipTravelMaterials() {
  44. let fuel = this.getAllByType("fuel");
  45. if (!fuel || fuel.length == 0) { return false; }
  46. return this.consumeItem(fuel[0], 1);
  47. }
  48. addItem(item, amount) {
  49. let foundItem = this.getItem(item.name);
  50. if (!foundItem) {
  51. this.hold.push(item);
  52. } else {
  53. foundItem.amount += amount;
  54. }
  55. game.playerHud.inventory.buildInventory();
  56. }
  57. addItems(items) {
  58. items.forEach((item) => {
  59. this.addItem(item, item.amount);
  60. });
  61. game.playerHud.inventory.buildInventory();
  62. }
  63. consumeItem(item, amountToConsume) {
  64. if (item.amount - amountToConsume < 0) {
  65. return false;
  66. }
  67. if (item.amount == amountToConsume) {
  68. this.hold.splice(this.hold.indexOf(item), 1);
  69. game.playerHud.inventory.buildInventory();
  70. return item;
  71. }
  72. let oldItem = JSON.parse(JSON.stringify(item));
  73. item.amount -= amountToConsume;
  74. game.playerHud.inventory.buildInventory();
  75. return oldItem;
  76. }
  77. }