Improve logic

This commit is contained in:
2024-08-24 17:22:53 +02:00
parent 0d52210209
commit 2ea722cee3
9 changed files with 62 additions and 53 deletions

View File

@@ -98,14 +98,14 @@ public class CommandRegistry {
dispatcher.register(literal("buy") dispatcher.register(literal("buy")
.then(argument("item", ItemStackArgumentType.itemStack(commandRegistryAccess)) .then(argument("item", ItemStackArgumentType.itemStack(commandRegistryAccess))
.then(argument("count", IntegerArgumentType.integer(1, 64)) .then(argument("count", IntegerArgumentType.integer(1))
.executes(StoreCommands::buyCount)) .executes(StoreCommands::buyCount))
.executes(StoreCommands::buyOne) .executes(StoreCommands::buyOne)
) )
); );
dispatcher.register(literal("sell") dispatcher.register(literal("sell")
.then(argument("item", ItemStackArgumentType.itemStack(commandRegistryAccess)) .then(argument("item", ItemStackArgumentType.itemStack(commandRegistryAccess))
.then(argument("count", IntegerArgumentType.integer(1, 64)) .then(argument("count", IntegerArgumentType.integer(1))
.executes(StoreCommands::sellCount)) .executes(StoreCommands::sellCount))
.executes(StoreCommands::sellOne) .executes(StoreCommands::sellOne)
) )

View File

@@ -41,7 +41,7 @@ public class StoreCommands {
ItemStack itemStack = new ItemStack(item, count); ItemStack itemStack = new ItemStack(item, count);
ServerPlayerEntity player = ctx.getSource().getPlayer(); ServerPlayerEntity player = ctx.getSource().getPlayer();
if (player != null) { if (player != null) {
sell(itemStack.copy(), player, false); sell(itemStack.copy(), player, false, false);
return 0; return 0;
} }
return 1; return 1;
@@ -52,7 +52,7 @@ public class StoreCommands {
ItemStack itemStack = new ItemStack(item); ItemStack itemStack = new ItemStack(item);
ServerPlayerEntity player = ctx.getSource().getPlayer(); ServerPlayerEntity player = ctx.getSource().getPlayer();
if (player != null) { if (player != null) {
sell(itemStack.copy(), player, false); sell(itemStack.copy(), player, false, false);
return 0; return 0;
} }
return 1; return 1;

View File

@@ -11,17 +11,20 @@ import static systems.brn.servershop.ServerShop.priceStorage;
import static systems.brn.servershop.lib.Util.*; import static systems.brn.servershop.lib.Util.*;
public class ShopFunctions { public class ShopFunctions {
public static void buy(ItemStack itemStack, ServerPlayerEntity player, boolean overlay) { public static void buy(ItemStack itemStackIn, ServerPlayerEntity player, boolean overlay) {
ItemStack itemStack = itemStackIn.copy();
PlayerInventory playerInventory = player.getInventory(); PlayerInventory playerInventory = player.getInventory();
ItemPriceRecord price = priceStorage.getPrices(itemStack); ItemPriceRecord price = priceStorage.getPrices(itemStack);
int buyPrice = price.buyPrice() * itemStack.getCount();
long playerBalance = balanceStorage.getBalance(player); long playerBalance = balanceStorage.getBalance(player);
if (buyPrice > 0) { if (price.buyPrice() > 0) {
int count = Math.min(itemStack.getCount(), maxInsertionAmount(playerInventory, itemStack.copy()));
itemStack.setCount(count);
int buyPrice = price.buyPrice() * itemStack.getCount();
if (playerBalance >= buyPrice) { if (playerBalance >= buyPrice) {
if (canInsertItemIntoInventory(playerInventory, itemStack.copy()) >= itemStack.getCount()) { ItemStack remaining = insertStackIntoInventory(playerInventory, itemStack.copy());
ItemStack remaining = insertStackIntoInventory(playerInventory, itemStack.copy()); int boughtCount = itemStack.getCount() - remaining.getCount();
int toDeduce = buyPrice - (price.buyPrice() * remaining.getCount()); if (boughtCount > 0) {
int boughtCount = itemStack.getCount() - remaining.getCount(); int toDeduce = price.buyPrice() * boughtCount;
balanceStorage.removeBalance(player, toDeduce); balanceStorage.removeBalance(player, toDeduce);
playerBalance = balanceStorage.getBalance(player); playerBalance = balanceStorage.getBalance(player);
player.sendMessage(Text.translatable("message.servershop.buy.success", boughtCount, itemStack.getName(), toDeduce, playerBalance), overlay); player.sendMessage(Text.translatable("message.servershop.buy.success", boughtCount, itemStack.getName(), toDeduce, playerBalance), overlay);
@@ -36,12 +39,19 @@ public class ShopFunctions {
} }
} }
public static void sell(ItemStack itemStack, ServerPlayerEntity player, boolean overlay) { public static void sell(ItemStack itemStackIn, ServerPlayerEntity player, boolean isCursorStack, boolean overlay) {
PlayerInventory playerInventory = player.getInventory(); PlayerInventory playerInventory = player.getInventory();
ItemStack itemStack = itemStackIn.copy();
ItemPriceRecord price = priceStorage.getPrices(itemStack); ItemPriceRecord price = priceStorage.getPrices(itemStack);
int sellPrice = price.sellPrice(); int sellPrice = price.sellPrice();
if (sellPrice > 0) { if (sellPrice > 0) {
int remaining = removeFromInventory(playerInventory, itemStack.copy(), itemStack.getCount()); int remaining;
if (!isCursorStack) {
remaining = removeFromInventory(playerInventory, itemStack.copy(), itemStack.getCount());
} else {
remaining = 0;
itemStackIn.setCount(0);
}
int toAdd = sellPrice * (itemStack.getCount() - remaining); int toAdd = sellPrice * (itemStack.getCount() - remaining);
int soldCount = itemStack.getCount() - remaining; int soldCount = itemStack.getCount() - remaining;
balanceStorage.addBalance(player, toAdd); balanceStorage.addBalance(player, toAdd);

View File

@@ -7,13 +7,13 @@ import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.inventory.Inventory; import net.minecraft.inventory.Inventory;
import net.minecraft.item.Item; import net.minecraft.item.Item;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import net.minecraft.item.Items;
import net.minecraft.server.MinecraftServer; import net.minecraft.server.MinecraftServer;
import net.minecraft.server.network.ServerPlayerEntity; import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.text.*; import net.minecraft.text.*;
import net.minecraft.util.Formatting; import net.minecraft.util.Formatting;
import net.minecraft.util.Identifier; import net.minecraft.util.Identifier;
import net.minecraft.util.UserCache; import net.minecraft.util.UserCache;
import net.minecraft.util.collection.DefaultedList;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import systems.brn.servershop.ServerShop; import systems.brn.servershop.ServerShop;
import systems.brn.servershop.lib.records.AuctionRecord; import systems.brn.servershop.lib.records.AuctionRecord;
@@ -42,23 +42,17 @@ public class Util {
return Identifier.of(ServerShop.MOD_ID, path); return Identifier.of(ServerShop.MOD_ID, path);
} }
public static int canInsertItemIntoInventory(Inventory inventory, ItemStack itemStack) { public static int maxInsertionAmount(PlayerInventory inventory, ItemStack itemStackIn) {
// Get the player's inventory // Get the player's inventory
int maxInsert = 0; int maxInsert = 0;
if (inventory instanceof PlayerInventory playerInventory) { // Iterate through the slots in the player's inventory
// Iterate through the slots in the player's inventory for (int i = 0; i < inventory.main.size(); i++) {
for (int i = 0; i < playerInventory.main.size(); i++) { ItemStack slotStack = inventory.main.get(i);
ItemStack slotStack = playerInventory.main.get(i); maxInsert = canInsertToStack(slotStack, itemStackIn, maxInsert);
maxInsert = canInsertToStack(slotStack, itemStack, maxInsert);
}
} else {
for (int i = 0; i < inventory.size(); i++) {
ItemStack slotStack = inventory.getStack(i);
maxInsert = canInsertToStack(slotStack, itemStack, maxInsert);
}
} }
return maxInsert; // Return the maximum insertion count return maxInsert; // Return the maximum insertion count
} }
@@ -99,16 +93,16 @@ public class Util {
return !stack1.isEmpty() && stack1.getItem() == stack2.getItem() && ItemStack.areItemsAndComponentsEqual(stack1, stack2); return !stack1.isEmpty() && stack1.getItem() == stack2.getItem() && ItemStack.areItemsAndComponentsEqual(stack1, stack2);
} }
public static ItemStack insertStackIntoInventory(Inventory inventory, ItemStack stack) { public static ItemStack insertStackIntoInventory(PlayerInventory playerInventory, ItemStack stack) {
DefaultedList<ItemStack> inventory = playerInventory.main;
// First, try to merge with existing stacks // First, try to merge with existing stacks
for (int i = 0; i < inventory.size(); i++) { for (ItemStack slotStack : inventory) {
ItemStack slotStack = inventory.getStack(i);
if (canCombine(slotStack, stack)) { if (canCombine(slotStack, stack)) {
int transferAmount = Math.min(stack.getCount(), slotStack.getMaxCount() - slotStack.getCount()); int transferAmount = Math.min(stack.getCount(), slotStack.getMaxCount() - slotStack.getCount());
if (transferAmount > 0) { if (transferAmount > 0) {
slotStack.increment(transferAmount); slotStack.increment(transferAmount);
stack.decrement(transferAmount); stack.decrement(transferAmount);
inventory.markDirty(); playerInventory.markDirty();
if (stack.isEmpty()) { if (stack.isEmpty()) {
return ItemStack.EMPTY; return ItemStack.EMPTY;
} }
@@ -118,12 +112,16 @@ public class Util {
// Next, try to find an empty slot // Next, try to find an empty slot
for (int i = 0; i < inventory.size(); i++) { for (int i = 0; i < inventory.size(); i++) {
ItemStack slotStack = inventory.getStack(i); ItemStack slotStack = inventory.get(i);
if (slotStack.isEmpty()) { if (slotStack.isEmpty()) {
inventory.setStack(i, stack.copy()); ItemStack stackTemp = stack.copy();
stack.setCount(0); stackTemp.setCount(Math.min(stackTemp.getCount(), stackTemp.getMaxCount()));
inventory.markDirty(); inventory.set(i, stackTemp.copy());
return ItemStack.EMPTY; stack.decrement(stackTemp.getCount());
playerInventory.markDirty();
if (stack.isEmpty()) {
return ItemStack.EMPTY;
}
} }
} }
@@ -227,7 +225,7 @@ public class Util {
private static ItemStack addLore(int buyPrice, int sellPrice, ItemStack stack, boolean isEditor, String sellerName, boolean me) { private static ItemStack addLore(int buyPrice, int sellPrice, ItemStack stack, boolean isEditor, String sellerName, boolean me) {
Text buyLine = Text.translatable("gui.servershop." + (isEditor ? "shop.editor." : "") + "item.buy_price" + (buyPrice == 0 ? "_not_buyable" : "") + (buyPrice == -1 ? "_disabled" : ""), buyPrice).setStyle(Style.EMPTY.withColor(Formatting.DARK_GREEN).withItalic(true)); Text buyLine = Text.translatable("gui.servershop." + (isEditor ? "shop.editor." : "") + "item.buy_price" + (buyPrice == 0 ? "_not_buyable" : "") + (buyPrice == -1 ? "_disabled" : ""), buyPrice).setStyle(Style.EMPTY.withColor(Formatting.DARK_GREEN).withItalic(true));
Text sellLine = Text.translatable("gui.servershop." + (isEditor ? "shop.editor." : "") + "item.sell_price" + (sellPrice == 0 ? "_not_sellable" : "") + (sellPrice == -1 ? "_disabled" : ""), sellPrice).setStyle(Style.EMPTY.withColor(Formatting.AQUA).withItalic(true)); Text sellLine = Text.translatable("gui.servershop." + (isEditor ? "shop.editor." : "") + "item.sell_price" + (sellPrice == 0 ? "_not_sellable" : "") + (sellPrice == -1 ? "_disabled" : ""), sellPrice).setStyle(Style.EMPTY.withColor(Formatting.AQUA).withItalic(true));
Text infoLine = Text.translatable("gui.servershop.item.stack_info").setStyle(Style.EMPTY.withColor(Formatting.YELLOW).withItalic(true)); Text infoLine = Text.translatable("gui.servershop." + (isEditor ? "shop.editor." : "") + "item.stack_info").setStyle(Style.EMPTY.withColor(Formatting.YELLOW).withItalic(true));
Text sellerLine; Text sellerLine;
if (me) { if (me) {
sellerLine = Text.translatable("gui.servershop.item.seller_me", sellerName).setStyle(Style.EMPTY.withColor(Formatting.GREEN).withItalic(true)); sellerLine = Text.translatable("gui.servershop.item.seller_me", sellerName).setStyle(Style.EMPTY.withColor(Formatting.GREEN).withItalic(true));
@@ -244,7 +242,7 @@ public class Util {
loreList = new ArrayList<>(lore.lines()); loreList = new ArrayList<>(lore.lines());
} }
if (sellerName == null || sellerName.isEmpty()) { if (sellerName == null || sellerName.isEmpty()) {
if (!isEditor && (buyPrice > 0 || sellPrice > 0)) { if (buyPrice > 0 || sellPrice > 0) {
loreList.addFirst(infoLine); loreList.addFirst(infoLine);
} }
} else { } else {

View File

@@ -1,5 +1,6 @@
package systems.brn.servershop.lib.storages; package systems.brn.servershop.lib.storages;
import com.mojang.authlib.GameProfile;
import net.minecraft.entity.player.PlayerInventory; import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import net.minecraft.nbt.*; import net.minecraft.nbt.*;
@@ -76,16 +77,20 @@ public class AuctionStorage {
long playerBalance = balanceStorage.getBalance(buyer); long playerBalance = balanceStorage.getBalance(buyer);
if (buyPrice > 0 && auctions.contains(auction)) { if (buyPrice > 0 && auctions.contains(auction)) {
if (playerBalance >= buyPrice || buyer.getUuid().equals(auction.sellerUUID())) { if (playerBalance >= buyPrice || buyer.getUuid().equals(auction.sellerUUID())) {
if (canInsertItemIntoInventory(playerInventory, itemStack.copy()) >= itemStack.getCount()) { ItemStack remaining = insertStackIntoInventory(playerInventory, itemStack.copy());
ItemStack remaining = insertStackIntoInventory(playerInventory, itemStack.copy()); int boughtCount = itemStack.getCount() - remaining.getCount();
int toDeduce = buyPrice - (auction.buyPrice() * remaining.getCount()); if (boughtCount > 0) {
int boughtCount = itemStack.getCount() - remaining.getCount(); int toDeduce = auction.buyPrice() * boughtCount;
if (!buyer.getUuid().equals(auction.sellerUUID())) { if (!buyer.getUuid().equals(auction.sellerUUID())) {
balanceStorage.removeBalance(buyer, toDeduce); balanceStorage.removeBalance(buyer, toDeduce);
balanceStorage.addBalance(auction.sellerUUID(), toDeduce); balanceStorage.addBalance(auction.sellerUUID(), toDeduce);
playerBalance = balanceStorage.getBalance(buyer); playerBalance = balanceStorage.getBalance(buyer);
buyer.sendMessage(Text.translatable("message.servershop.buy.success", boughtCount, itemStack.getName(), toDeduce, playerBalance), true); buyer.sendMessage(Text.translatable("message.servershop.buy.success", boughtCount, itemStack.getName(), toDeduce, playerBalance), true);
ServerPlayerEntity seller = server.getPlayerManager().getPlayer(auction.sellerUUID());
if (seller != null && !seller.isDisconnected()) {
long sellerBalance = balanceStorage.getBalance(seller);
seller.sendMessage(Text.translatable("message.servershop.buy.other", buyer.getName(), boughtCount, itemStack.getName(), toDeduce, sellerBalance), true);
}
} else { } else {
buyer.sendMessage(Text.translatable("message.servershop.buy.own", boughtCount, itemStack.getName(), toDeduce, playerBalance), true); buyer.sendMessage(Text.translatable("message.servershop.buy.own", boughtCount, itemStack.getName(), toDeduce, playerBalance), true);
} }

View File

@@ -59,12 +59,6 @@ public class BalanceScreen extends PagedGui implements SearchableInterface {
return Math.ceilDivExact(filteredBalances.size(), PAGE_SIZE); return Math.ceilDivExact(filteredBalances.size(), PAGE_SIZE);
} }
@Override
public boolean insertItem(ItemStack stack, int startIndex, int endIndex, boolean fromLast) {
sell(stack.copy(), player, true);
return super.insertItem(stack, startIndex, endIndex, fromLast);
}
@Override @Override
protected DisplayElement getElement(int id) { protected DisplayElement getElement(int id) {
MinecraftServer server = player.getServer(); MinecraftServer server = player.getServer();

View File

@@ -77,7 +77,7 @@ public class ShopEditorScreen extends PagedGui implements SearchableInterface {
shopPriceSetScreenBuy.open(); shopPriceSetScreenBuy.open();
} else if (hasPrices(element.getItemStack())) { } else if (hasPrices(element.getItemStack())) {
ItemStack itemStack = removePrices(element.getItemStack()); ItemStack itemStack = removePrices(element.getItemStack());
ShopPriceSetScreen shopPriceSetScreen = new ShopPriceSetScreen(this, itemStack.copy(), type.isLeft ? 0 : 1); ShopPriceSetScreen shopPriceSetScreen = new ShopPriceSetScreen(this, itemStack.copy(), type.shift ? 2 : (type.isLeft ? 0 : 1));
shopPriceSetScreen.open(); shopPriceSetScreen.open();
} }
return false; return false;

View File

@@ -62,17 +62,17 @@ public class ShopScreen extends PagedGui implements SearchableInterface {
public boolean onClick(int index, ClickType type, SlotActionType action, GuiElementInterface element) { public boolean onClick(int index, ClickType type, SlotActionType action, GuiElementInterface element) {
ItemStack cursorStack = getPlayer().currentScreenHandler.getCursorStack(); ItemStack cursorStack = getPlayer().currentScreenHandler.getCursorStack();
if (!cursorStack.isEmpty()) { if (!cursorStack.isEmpty()) {
sell(cursorStack, player, true); sell(cursorStack, player, true, true);
} else if (hasPrices(element.getItemStack())) { } else if (hasPrices(element.getItemStack())) {
ItemStack itemStack = removePrices(element.getItemStack()); ItemStack itemStack = removePrices(element.getItemStack());
if (type.shift) { if (type.shift) {
itemStack.setCount(itemStack.getMaxCount()); itemStack.setCount(itemStack.getMaxCount());
} }
if (type.isLeft) { //buy if (type.isLeft) { //buy
buy(itemStack.copy(), player, true); buy(itemStack, player, true);
} else if (type.isRight) { //sell } else if (type.isRight) { //sell
sell(itemStack.copy(), player, true); sell(itemStack.copy(), player, false, true);
} }
} }
return false; return false;
@@ -80,7 +80,7 @@ public class ShopScreen extends PagedGui implements SearchableInterface {
@Override @Override
public boolean insertItem(ItemStack stack, int startIndex, int endIndex, boolean fromLast) { public boolean insertItem(ItemStack stack, int startIndex, int endIndex, boolean fromLast) {
sell(stack.copy(), player, true); sell(stack, player, true, true);
return super.insertItem(stack, startIndex, endIndex, fromLast); return super.insertItem(stack, startIndex, endIndex, fromLast);
} }

View File

@@ -44,6 +44,7 @@
"gui.servershop.shop.editor.item.buy_price.title": "Enter buy price", "gui.servershop.shop.editor.item.buy_price.title": "Enter buy price",
"gui.servershop.shop.editor.item.sell_price.title": "Enter sell price", "gui.servershop.shop.editor.item.sell_price.title": "Enter sell price",
"gui.servershop.item.stack_info": "Holding shift tries to do a stack", "gui.servershop.item.stack_info": "Holding shift tries to do a stack",
"gui.servershop.shop.editor.item.stack_info": "Holding shift edits both",
"message.servershop.prices.load": "Loaded prices from disk", "message.servershop.prices.load": "Loaded prices from disk",
"message.servershop.prices.load_fail": "Failed loading prices from disk", "message.servershop.prices.load_fail": "Failed loading prices from disk",
"message.servershop.prices.save": "Saved prices to disk", "message.servershop.prices.save": "Saved prices to disk",
@@ -69,6 +70,7 @@
"message.servershop.buy.inventory": "You don't have enough inventory space", "message.servershop.buy.inventory": "You don't have enough inventory space",
"message.servershop.buy.success": "You bought %d %s for %d, now you have %d", "message.servershop.buy.success": "You bought %d %s for %d, now you have %d",
"message.servershop.buy.own": "You bought your own %d %s for %d, now you have %d", "message.servershop.buy.own": "You bought your own %d %s for %d, now you have %d",
"message.servershop.buy.other": "%s bought %d of %s from you for %d, now you have %d",
"message.servershop.buy.not_available": "This item (%s) is not available for buying", "message.servershop.buy.not_available": "This item (%s) is not available for buying",
"message.servershop.sell.not_enough": "You don't have this item", "message.servershop.sell.not_enough": "You don't have this item",
"message.servershop.sell.success": "You sold %d %s for %d, now you have %d", "message.servershop.sell.success": "You sold %d %s for %d, now you have %d",