/
TakeCommand.java
417 lines (406 loc) · 20 KB
/
TakeCommand.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
package com.denizenscript.denizen.scripts.commands.item;
import com.denizenscript.denizen.nms.NMSHandler;
import com.denizenscript.denizen.objects.MaterialTag;
import com.denizenscript.denizen.utilities.Utilities;
import com.denizenscript.denizen.utilities.debugging.Debug;
import com.denizenscript.denizen.utilities.depends.Depends;
import com.denizenscript.denizen.utilities.inventory.SlotHelper;
import com.denizenscript.denizen.utilities.nbt.CustomNBT;
import com.denizenscript.denizen.objects.InventoryTag;
import com.denizenscript.denizen.objects.ItemTag;
import com.denizenscript.denizencore.exceptions.InvalidArgumentsException;
import com.denizenscript.denizencore.objects.Argument;
import com.denizenscript.denizencore.objects.core.ElementTag;
import com.denizenscript.denizencore.objects.ArgumentHelper;
import com.denizenscript.denizencore.objects.core.ListTag;
import com.denizenscript.denizencore.scripts.ScriptEntry;
import com.denizenscript.denizencore.scripts.commands.AbstractCommand;
import com.denizenscript.denizencore.utilities.CoreUtilities;
import com.denizenscript.denizencore.utilities.Deprecations;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.BookMeta;
import java.util.List;
import java.util.function.Function;
public class TakeCommand extends AbstractCommand {
public TakeCommand() {
setName("take");
setSyntax("take [money/xp/iteminhand/cursoritem/scriptname:<name>/bydisplay:<name>/bycover:<title>|<author>/slot:<slot>/nbt:<key>/material:<material>/<item>|...] (quantity:<#>) (from:<inventory>)");
setRequiredArguments(1, 3);
isProcedural = false;
}
// <--[command]
// @Name Take
// @Syntax take [money/xp/iteminhand/cursoritem/scriptname:<name>/bydisplay:<name>/bycover:<title>|<author>/slot:<slot>/nbt:<key>/material:<material>/<item>|...] (quantity:<#>) (from:<inventory>)
// @Required 1
// @Maximum 3
// @Short Takes an item from the player.
// @Group item
//
// @Description
// Takes items from a player or inventory.
//
// If the player or inventory does not have the item being taken, nothing happens.
//
// Using 'slot:' will take the items from that specific slot.
//
// Using 'nbt:' with a key will take items with the specified NBT key, as set by <@link mechanism ItemTag.nbt>.
//
// Using 'iteminhand' will take from the player's held item slot.
//
// Using 'cursoritem' will take from the player's held cursor item (as in, one that's actively being picked up and moved in an inventory screen).
//
// Using 'scriptname:' will take items with the specified item script name.
//
// Using 'bydisplay:' will take items with the specified display name.
//
// Using 'bycover:' will take a written book by the specified book title + author pair.
//
// Using 'material:' will take items of the specified material type (except for script items).
//
// Using 'xp' will take experience from the player.
//
// If an economy is registered, using 'money' instead of an item will take money from the player's economy balance.
//
// If no quantity is specified, exactly 1 item will be taken.
//
// Specifying a raw item without any matching method is considered unreliable and should be avoided.
//
// Optionally using 'from:' to specify a specific inventory to take from. If not specified, the linked player's inventory will be used.
//
// @Tags
// <PlayerTag.item_in_hand>
// <PlayerTag.money>
//
// @Usage
// Use to take money from the player
// - take money quantity:10
// @Usage
// Use to take an arrow from the player's enderchest
// - take material:arrow from:<player.enderchest>
// @Usage
// Use to take the current holding item from the player's hand
// - take iteminhand
// @Usage
// Use to take 5 emeralds from the player's inventory
// - take material:emerald quantity:5
// -->
private enum Type {MONEY, XP, ITEMINHAND, CURSORITEM, ITEM, INVENTORY, BYDISPLAY, SLOT, BYCOVER, SCRIPTNAME, NBT, MATERIAL}
@Override
public void parseArgs(ScriptEntry scriptEntry) throws InvalidArgumentsException {
for (Argument arg : scriptEntry.getProcessedArgs()) {
if (!scriptEntry.hasObject("type")
&& arg.matches("money", "coins")) {
scriptEntry.addObject("type", Type.MONEY);
}
else if (!scriptEntry.hasObject("type")
&& arg.matches("xp", "exp")) {
scriptEntry.addObject("type", Type.XP);
}
else if (!scriptEntry.hasObject("type")
&& arg.matches("item_in_hand", "iteminhand")) {
scriptEntry.addObject("type", Type.ITEMINHAND);
}
else if (!scriptEntry.hasObject("type")
&& arg.matches("cursoritem", "cursor_item")) {
scriptEntry.addObject("type", Type.CURSORITEM);
}
else if (!scriptEntry.hasObject("quantity")
&& arg.matchesPrefix("q", "qty", "quantity")
&& arg.matchesFloat()) {
scriptEntry.addObject("quantity", arg.asElement());
}
else if (!scriptEntry.hasObject("items")
&& arg.matchesPrefix("bydisplay")
&& !scriptEntry.hasObject("type")) {
scriptEntry.addObject("type", Type.BYDISPLAY);
scriptEntry.addObject("displayname", arg.asElement());
}
else if (!scriptEntry.hasObject("items")
&& arg.matchesPrefix("nbt")
&& !scriptEntry.hasObject("type")) {
scriptEntry.addObject("type", Type.NBT);
scriptEntry.addObject("nbt_key", arg.asElement());
}
else if (!scriptEntry.hasObject("type")
&& !scriptEntry.hasObject("items")
&& arg.matchesPrefix("bycover")) {
scriptEntry.addObject("type", Type.BYCOVER);
scriptEntry.addObject("cover", arg.asType(ListTag.class));
}
else if (!scriptEntry.hasObject("type")
&& !scriptEntry.hasObject("items")
&& arg.matchesPrefix("material")) {
scriptEntry.addObject("type", Type.MATERIAL);
scriptEntry.addObject("material", arg.asType(MaterialTag.class));
}
else if (!scriptEntry.hasObject("type")
&& !scriptEntry.hasObject("items")
&& arg.matchesPrefix("script", "scriptname")) {
scriptEntry.addObject("type", Type.SCRIPTNAME);
scriptEntry.addObject("scriptitem", arg.asType(ItemTag.class));
}
else if (!scriptEntry.hasObject("slot")
&& !scriptEntry.hasObject("type")
&& arg.matchesPrefix("slot")) {
scriptEntry.addObject("type", Type.SLOT);
scriptEntry.addObject("slot", arg.asElement());
}
else if (!scriptEntry.hasObject("items")
&& !scriptEntry.hasObject("type")
&& arg.matchesArgumentList(ItemTag.class)) {
scriptEntry.addObject("items", ListTag.valueOf(arg.raw_value.replace("item:", ""), scriptEntry.getContext()).filter(ItemTag.class, scriptEntry));
}
else if (!scriptEntry.hasObject("inventory")
&& arg.matchesPrefix("f", "from")
&& arg.matchesArgumentType(InventoryTag.class)) {
scriptEntry.addObject("inventory", arg.asType(InventoryTag.class));
}
else if (!scriptEntry.hasObject("type")
&& arg.matches("inventory")) {
Deprecations.takeCommandInventory.warn(scriptEntry);
scriptEntry.addObject("type", Type.INVENTORY);
}
else if (!scriptEntry.hasObject("inventory")
&& arg.matches("npc")) {
Deprecations.takeCommandInventory.warn(scriptEntry);
scriptEntry.addObject("inventory", Utilities.getEntryNPC(scriptEntry).getDenizenEntity().getInventory());
}
else {
arg.reportUnhandled();
}
}
scriptEntry.defaultObject("type", Type.ITEM)
.defaultObject("quantity", new ElementTag(1));
Type type = (Type) scriptEntry.getObject("type");
if (type != Type.MONEY && scriptEntry.getObject("inventory") == null) {
scriptEntry.addObject("inventory", Utilities.entryHasPlayer(scriptEntry) ? Utilities.getEntryPlayer(scriptEntry).getInventory() : null);
}
if (!scriptEntry.hasObject("inventory") && type != Type.MONEY) {
throw new InvalidArgumentsException("Must specify an inventory to take from!");
}
if (type == Type.ITEM && scriptEntry.getObject("items") == null) {
throw new InvalidArgumentsException("Must specify item/items!");
}
}
@Override
public void execute(ScriptEntry scriptEntry) {
InventoryTag inventory = scriptEntry.getObjectTag("inventory");
ElementTag quantity = scriptEntry.getElement("quantity");
ElementTag displayname = scriptEntry.getElement("displayname");
ItemTag scriptitem = scriptEntry.getObjectTag("scriptitem");
ElementTag slot = scriptEntry.getElement("slot");
ListTag titleAuthor = scriptEntry.getObjectTag("cover");
ElementTag nbtKey = scriptEntry.getElement("nbt_key");
MaterialTag material = scriptEntry.getObjectTag("material");
Type type = (Type) scriptEntry.getObject("type");
List<ItemTag> items = (List<ItemTag>) scriptEntry.getObject("items");
if (scriptEntry.dbCallShouldDebug()) {
Debug.report(scriptEntry, getName(), ArgumentHelper.debugObj("Type", type.name())
+ quantity.debug()
+ (inventory != null ? inventory.debug() : "")
+ (displayname != null ? displayname.debug() : "")
+ (scriptitem != null ? scriptitem.debug() : "")
+ ArgumentHelper.debugObj("Items", items)
+ (slot != null ? slot.debug() : "")
+ (nbtKey != null ? nbtKey.debug() : "")
+ (material != null ? material.debug() : "")
+ (titleAuthor != null ? titleAuthor.debug() : ""));
}
switch (type) {
case INVENTORY: {
inventory.clear();
break;
}
case ITEMINHAND: {
Player player = Utilities.getEntryPlayer(scriptEntry).getPlayerEntity();
int inHandAmt = player.getEquipment().getItemInMainHand().getAmount();
int theAmount = (int) quantity.asDouble();
ItemStack newHandItem = new ItemStack(Material.AIR);
if (theAmount > inHandAmt) {
Debug.echoDebug(scriptEntry, "...player did not have enough of the item in hand, taking all...");
player.getEquipment().setItemInMainHand(newHandItem);
}
else {
// amount is just right!
if (theAmount == inHandAmt) {
player.getEquipment().setItemInMainHand(newHandItem);
}
else {
// amount is less than what's in hand, need to make a new itemstack of what's left...
newHandItem = player.getEquipment().getItemInMainHand().clone();
newHandItem.setAmount(inHandAmt - theAmount);
player.getEquipment().setItemInMainHand(newHandItem);
player.updateInventory();
}
}
break;
}
case CURSORITEM: {
Player player = Utilities.getEntryPlayer(scriptEntry).getPlayerEntity();
int currentAmount = player.getItemOnCursor().getAmount();
int takeAmount = (int) quantity.asDouble();
ItemStack newItem = new ItemStack(Material.AIR);
if (takeAmount > currentAmount) {
Debug.echoDebug(scriptEntry, "...player did not have enough of the item on cursor, taking all...");
player.setItemOnCursor(newItem);
}
else {
if (takeAmount == currentAmount) {
player.setItemOnCursor(newItem);
}
else {
newItem = player.getItemOnCursor().clone();
newItem.setAmount(currentAmount - takeAmount);
player.setItemOnCursor(newItem);
player.updateInventory();
}
}
break;
}
case MONEY: {
if (Depends.economy == null) {
Debug.echoError(scriptEntry.getResidingQueue(), "No economy loaded! Have you installed Vault and a compatible economy plugin?");
return;
}
Depends.economy.withdrawPlayer(Utilities.getEntryPlayer(scriptEntry).getOfflinePlayer(), quantity.asDouble());
break;
}
case XP: {
Utilities.getEntryPlayer(scriptEntry).getPlayerEntity().giveExp(-quantity.asInt());
break;
}
case ITEM: {
for (ItemTag item : items) {
ItemStack is = item.getItemStack();
is.setAmount(quantity.asInt());
if (!removeItem(inventory.getInventory(), item, item.getAmount())) {
Debug.echoDebug(scriptEntry, "Inventory does not contain at least " + quantity.asInt() + " of " + item.identify() + "... Taking all...");
}
}
break;
}
case BYDISPLAY: {
if (displayname == null) {
Debug.echoError(scriptEntry.getResidingQueue(), "Must specify a displayname!");
return;
}
takeByMatcher(inventory, (item) -> item.hasItemMeta() && item.getItemMeta().hasDisplayName() &&
item.getItemMeta().getDisplayName().equalsIgnoreCase(displayname.identify()), quantity.asInt());
break;
}
case BYCOVER: {
if (titleAuthor == null) {
Debug.echoError(scriptEntry.getResidingQueue(), "Must specify a cover!");
return;
}
takeByMatcher(inventory, (item) -> item.hasItemMeta() && item.getItemMeta() instanceof BookMeta
&& equalOrNull(titleAuthor.get(0), ((BookMeta) item.getItemMeta()).getTitle())
&& (titleAuthor.size() == 1 || equalOrNull(titleAuthor.get(1), ((BookMeta) item.getItemMeta()).getAuthor())), quantity.asInt());
break;
}
case NBT: {
if (nbtKey == null) {
Debug.echoError(scriptEntry.getResidingQueue(), "Must specify an NBT key!");
return;
}
takeByMatcher(inventory, (item) -> CustomNBT.hasCustomNBT(item, nbtKey.asString(), CustomNBT.KEY_DENIZEN), quantity.asInt());
break;
}
case SCRIPTNAME: {
if (scriptitem == null || scriptitem.getScriptName() == null) {
Debug.echoError(scriptEntry.getResidingQueue(), "Must specify a valid script name!");
return;
}
takeByMatcher(inventory, (item) -> scriptitem.getScriptName().equalsIgnoreCase(new ItemTag(item).getScriptName()), quantity.asInt());
break;
}
case MATERIAL: {
if (material == null) {
Debug.echoError(scriptEntry.getResidingQueue(), "Must specify a valid material!");
return;
}
takeByMatcher(inventory, (item) -> item.getType() == material.getMaterial() && !(new ItemTag(item).isItemscript()), quantity.asInt());
break;
}
case SLOT: {
int slotId = SlotHelper.nameToIndex(slot.asString());
if (slotId == -1 || slotId >= inventory.getSize()) {
Debug.echoError(scriptEntry.getResidingQueue(), "The input '" + slot.asString() + "' is not a valid slot!");
return;
}
ItemStack original = inventory.getInventory().getItem(slotId);
if (original != null && original.getType() != Material.AIR) {
if (original.getAmount() > quantity.asInt()) {
original.setAmount(original.getAmount() - quantity.asInt());
inventory.setSlots(slotId, original);
}
else {
inventory.setSlots(slotId, new ItemStack(Material.AIR));
}
}
break;
}
}
}
private static boolean equalOrNull(String a, String b) {
return b == null || a == null || a.equalsIgnoreCase(b);
}
public void takeByMatcher(InventoryTag inventory, Function<ItemStack, Boolean> matcher, int quantity) {
int itemsTaken = 0;
ItemStack[] contents = inventory.getInventory().getContents();
for (int i = 0; i < contents.length; i++) {
ItemStack it = contents[i];
if (itemsTaken < quantity
&& it != null
&& matcher.apply(it)) {
int amt = it.getAmount();
if (itemsTaken + amt <= quantity) {
inventory.getInventory().setItem(i, new ItemStack(Material.AIR));
itemsTaken += amt;
}
else {
it.setAmount(amt - (quantity - itemsTaken));
inventory.getInventory().setItem(i, it);
break;
}
}
}
}
public boolean removeItem(Inventory inventory, ItemTag item, int amount) {
if (item == null) {
return false;
}
item = new ItemTag(item.getItemStack().clone());
item.setAmount(1);
String myItem = CoreUtilities.toLowerCase(item.identify());
for (int i = 0; i < inventory.getSize(); i++) {
ItemStack is = inventory.getItem(i);
if (is == null) {
continue;
}
is = is.clone();
int count = is.getAmount();
is.setAmount(1);
// Note: this double-parsing is intentional, as part of a hotfix for a larger issue
String newItem = CoreUtilities.toLowerCase(ItemTag.valueOf(new ItemTag(is).identify(), false).identify());
if (myItem.equals(newItem)) {
if (count <= amount) {
NMSHandler.getItemHelper().setInventoryItem(inventory, null, i);
amount -= count;
if (amount == 0) {
return true;
}
}
else {
is.setAmount(count - amount);
NMSHandler.getItemHelper().setInventoryItem(inventory, is, i);
return true;
}
}
}
return false;
}
}