mirror of
https://github.com/KAMKEEL/CustomNPC-Plus.git
synced 2026-11-18 07:59:08 +00:00
Implement Phase 4: Auction House core system
- Add auction enums: - EnumAuctionDuration.java - configurable auction durations (SHORT/MEDIUM/LONG/VERY_LONG) - EnumAuctionStatus.java - listing statuses (ACTIVE/SOLD/EXPIRED/CANCELLED/CLAIMED) - EnumAuctionCategory.java - auto-categorization of items for browsing - Add AuctionListing.java data class: - Complete auction listing with seller/bidder tracking - Pricing with starting price, buyout price, current bid - Timing with snipe protection (extends TO X minutes, not by) - Item validation (checks trade restrictions and blacklist) - Previous bidder tracking for refund notifications - NBT serialization for persistence - Add AuctionController.java: - Global auction house management - Create/cancel/finalize listings - Bid placement with automatic outbid refunds via claims system - Buyout support with immediate sale - Claim system for sellers (proceeds) and buyers (items) - Search and filter by category/name - Periodic expiration processing - Persistence via auctions.dat - Add RoleAuctioneer.java NPC role: - Configurable tabs (listings, my listings, my bids, claims) - Configurable permissions (create, bid, buyout) - Custom welcome/disabled messages - Opens auction GUI on interaction - Update ConfigMarket.java: - Duration-specific settings (hours and fees) - Removed deprecated AvailableDurations string - Update EnumRoleType.java - add Auctioneer - Update EnumGuiType.java - add PlayerAuction, SetupAuctioneer - Update DataAdvanced.java - handle Auctioneer role creation - Update CustomNpcs.java - initialize AuctionController
This commit is contained in:
11 files changed
+1522
-29
No files matched your search
@@ -61,6 +61,7 @@ import noppes.npcs.controllers.MagicController;
|
||||
import noppes.npcs.controllers.VaultHelper;
|
||||
import noppes.npcs.controllers.CurrencyController;
|
||||
import noppes.npcs.controllers.AuctionBlacklist;
|
||||
import noppes.npcs.controllers.AuctionController;
|
||||
import noppes.npcs.controllers.PlayerDataController;
|
||||
import noppes.npcs.controllers.QuestController;
|
||||
import noppes.npcs.controllers.RecipeController;
|
||||
@@ -310,6 +311,7 @@ public class CustomNpcs {
|
||||
new VaultHelper();
|
||||
new CurrencyController();
|
||||
new AuctionBlacklist();
|
||||
new AuctionController();
|
||||
RecipeController.Instance.load();
|
||||
new BankController();
|
||||
DialogController.Instance.load();
|
||||
|
||||
@@ -18,6 +18,7 @@ import noppes.npcs.roles.JobGuard;
|
||||
import noppes.npcs.roles.JobHealer;
|
||||
import noppes.npcs.roles.JobItemGiver;
|
||||
import noppes.npcs.roles.JobSpawner;
|
||||
import noppes.npcs.roles.RoleAuctioneer;
|
||||
import noppes.npcs.roles.RoleBank;
|
||||
import noppes.npcs.roles.RoleCompanion;
|
||||
import noppes.npcs.roles.RoleFollower;
|
||||
@@ -218,6 +219,8 @@ public class DataAdvanced {
|
||||
npc.roleInterface = new RoleCompanion(npc);
|
||||
else if (role == EnumRoleType.Mount && !(npc.roleInterface instanceof RoleMount))
|
||||
npc.roleInterface = new RoleMount(npc);
|
||||
else if (role == EnumRoleType.Auctioneer && !(npc.roleInterface instanceof RoleAuctioneer))
|
||||
npc.roleInterface = new RoleAuctioneer(npc);
|
||||
}
|
||||
|
||||
public void setJob(int i) {
|
||||
|
||||
@@ -40,13 +40,23 @@ public class ConfigMarket {
|
||||
public static double ListingFeePercent = 0.0;
|
||||
public static double SalesTaxPercent = 0.05;
|
||||
public static boolean RequireAuctioneerNPC = true;
|
||||
public static String AvailableDurations = "2,12,24,48";
|
||||
public static int DefaultDurationHours = 24;
|
||||
public static int ClaimExpirationDays = 30;
|
||||
public static double MinBidIncrementPercent = 0.05;
|
||||
public static int SnipeProtectionMinutes = 5;
|
||||
public static int SnipeProtectionThreshold = 5;
|
||||
|
||||
// Auction Duration Settings (in hours)
|
||||
public static int AuctionDurationShort = 2;
|
||||
public static int AuctionDurationMedium = 12;
|
||||
public static int AuctionDurationLong = 24;
|
||||
public static int AuctionDurationVeryLong = 48;
|
||||
|
||||
// Auction Duration Fees (flat currency amount)
|
||||
public static long AuctionFeeShort = 0;
|
||||
public static long AuctionFeeMedium = 0;
|
||||
public static long AuctionFeeLong = 0;
|
||||
public static long AuctionFeeVeryLong = 0;
|
||||
|
||||
// =========================================
|
||||
// Trader Settings
|
||||
// =========================================
|
||||
@@ -108,12 +118,6 @@ public class ConfigMarket {
|
||||
RequireAuctioneerNPC = config.get(AUCTION, "Require Auctioneer NPC", true,
|
||||
"Require an Auctioneer NPC to access auction house").getBoolean(true);
|
||||
|
||||
AvailableDurations = config.get(AUCTION, "Available Durations", "2,12,24,48",
|
||||
"Available auction durations in hours (comma-separated)").getString();
|
||||
|
||||
DefaultDurationHours = config.get(AUCTION, "Default Duration Hours", 24,
|
||||
"Default auction duration in hours").getInt(24);
|
||||
|
||||
ClaimExpirationDays = config.get(AUCTION, "Claim Expiration Days", 30,
|
||||
"Claim expiration in days (claims auto-expire after this period, 0 = never)").getInt(30);
|
||||
|
||||
@@ -126,6 +130,32 @@ public class ConfigMarket {
|
||||
SnipeProtectionThreshold = config.get(AUCTION, "Snipe Protection Threshold", 5,
|
||||
"How many minutes before end triggers snipe protection").getInt(5);
|
||||
|
||||
// Duration settings
|
||||
AuctionDurationShort = config.get(AUCTION, "Duration Short Hours", 2,
|
||||
"Short auction duration in hours").getInt(2);
|
||||
|
||||
AuctionDurationMedium = config.get(AUCTION, "Duration Medium Hours", 12,
|
||||
"Medium auction duration in hours").getInt(12);
|
||||
|
||||
AuctionDurationLong = config.get(AUCTION, "Duration Long Hours", 24,
|
||||
"Long auction duration in hours").getInt(24);
|
||||
|
||||
AuctionDurationVeryLong = config.get(AUCTION, "Duration Very Long Hours", 48,
|
||||
"Very long auction duration in hours").getInt(48);
|
||||
|
||||
// Duration fees
|
||||
AuctionFeeShort = config.get(AUCTION, "Fee Short Duration", 0,
|
||||
"Flat fee for short duration auctions").getInt(0);
|
||||
|
||||
AuctionFeeMedium = config.get(AUCTION, "Fee Medium Duration", 0,
|
||||
"Flat fee for medium duration auctions").getInt(0);
|
||||
|
||||
AuctionFeeLong = config.get(AUCTION, "Fee Long Duration", 0,
|
||||
"Flat fee for long duration auctions").getInt(0);
|
||||
|
||||
AuctionFeeVeryLong = config.get(AUCTION, "Fee Very Long Duration", 0,
|
||||
"Flat fee for very long duration auctions").getInt(0);
|
||||
|
||||
// =========================================
|
||||
// Trader Settings
|
||||
// =========================================
|
||||
@@ -157,12 +187,18 @@ public class ConfigMarket {
|
||||
"Listing Fee Percent",
|
||||
"Sales Tax Percent",
|
||||
"Require Auctioneer NPC",
|
||||
"Available Durations",
|
||||
"Default Duration Hours",
|
||||
"Claim Expiration Days",
|
||||
"Min Bid Increment Percent",
|
||||
"Snipe Protection Minutes",
|
||||
"Snipe Protection Threshold"
|
||||
"Snipe Protection Threshold",
|
||||
"Duration Short Hours",
|
||||
"Duration Medium Hours",
|
||||
"Duration Long Hours",
|
||||
"Duration Very Long Hours",
|
||||
"Fee Short Duration",
|
||||
"Fee Medium Duration",
|
||||
"Fee Long Duration",
|
||||
"Fee Very Long Duration"
|
||||
)));
|
||||
|
||||
config.setCategoryPropertyOrder(TRADER, new ArrayList<>(Arrays.asList(
|
||||
@@ -198,20 +234,4 @@ public class ConfigMarket {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse available durations from config string
|
||||
*/
|
||||
public static int[] getAvailableDurationsArray() {
|
||||
String[] parts = AvailableDurations.split(",");
|
||||
int[] durations = new int[parts.length];
|
||||
for (int i = 0; i < parts.length; i++) {
|
||||
try {
|
||||
durations[i] = Integer.parseInt(parts[i].trim());
|
||||
} catch (NumberFormatException e) {
|
||||
durations[i] = 24; // Default to 24 hours if parsing fails
|
||||
}
|
||||
}
|
||||
return durations;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
package noppes.npcs.constants;
|
||||
|
||||
import net.minecraft.init.Items;
|
||||
import net.minecraft.item.Item;
|
||||
import net.minecraft.item.ItemArmor;
|
||||
import net.minecraft.item.ItemAxe;
|
||||
import net.minecraft.item.ItemBlock;
|
||||
import net.minecraft.item.ItemBow;
|
||||
import net.minecraft.item.ItemEnchantedBook;
|
||||
import net.minecraft.item.ItemFood;
|
||||
import net.minecraft.item.ItemHoe;
|
||||
import net.minecraft.item.ItemPickaxe;
|
||||
import net.minecraft.item.ItemPotion;
|
||||
import net.minecraft.item.ItemSpade;
|
||||
import net.minecraft.item.ItemStack;
|
||||
import net.minecraft.item.ItemSword;
|
||||
import net.minecraft.item.ItemTool;
|
||||
|
||||
/**
|
||||
* Categories for auction house items.
|
||||
* Used for filtering and browsing.
|
||||
*/
|
||||
public enum EnumAuctionCategory {
|
||||
ALL, // Special: shows all categories
|
||||
WEAPONS, // Swords, bows, etc.
|
||||
ARMOR, // Helmets, chestplates, leggings, boots
|
||||
TOOLS, // Pickaxes, axes, shovels, hoes
|
||||
FOOD, // Edible items
|
||||
POTIONS, // Potions and splash potions
|
||||
BLOCKS, // Placeable blocks
|
||||
MATERIALS, // Crafting materials (ingots, gems, etc.)
|
||||
ENCHANTED, // Items with enchantments or enchanted books
|
||||
MISC; // Everything else
|
||||
|
||||
/**
|
||||
* Get display name for GUI
|
||||
*/
|
||||
public String getDisplayName() {
|
||||
switch (this) {
|
||||
case ALL: return "All Items";
|
||||
case WEAPONS: return "Weapons";
|
||||
case ARMOR: return "Armor";
|
||||
case TOOLS: return "Tools";
|
||||
case FOOD: return "Food";
|
||||
case POTIONS: return "Potions";
|
||||
case BLOCKS: return "Blocks";
|
||||
case MATERIALS: return "Materials";
|
||||
case ENCHANTED: return "Enchanted";
|
||||
case MISC: return "Miscellaneous";
|
||||
default: return "Unknown";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Auto-categorize an item based on its type
|
||||
*/
|
||||
public static EnumAuctionCategory categorize(ItemStack itemStack) {
|
||||
if (itemStack == null || itemStack.getItem() == null) {
|
||||
return MISC;
|
||||
}
|
||||
|
||||
Item item = itemStack.getItem();
|
||||
|
||||
// Check for enchantments first (higher priority)
|
||||
if (itemStack.isItemEnchanted() || item instanceof ItemEnchantedBook) {
|
||||
return ENCHANTED;
|
||||
}
|
||||
|
||||
// Weapons
|
||||
if (item instanceof ItemSword || item instanceof ItemBow) {
|
||||
return WEAPONS;
|
||||
}
|
||||
|
||||
// Armor
|
||||
if (item instanceof ItemArmor) {
|
||||
return ARMOR;
|
||||
}
|
||||
|
||||
// Tools
|
||||
if (item instanceof ItemTool || item instanceof ItemPickaxe ||
|
||||
item instanceof ItemAxe || item instanceof ItemSpade ||
|
||||
item instanceof ItemHoe) {
|
||||
return TOOLS;
|
||||
}
|
||||
|
||||
// Food
|
||||
if (item instanceof ItemFood) {
|
||||
return FOOD;
|
||||
}
|
||||
|
||||
// Potions
|
||||
if (item instanceof ItemPotion) {
|
||||
return POTIONS;
|
||||
}
|
||||
|
||||
// Blocks
|
||||
if (item instanceof ItemBlock) {
|
||||
return BLOCKS;
|
||||
}
|
||||
|
||||
// Materials - common crafting items
|
||||
if (isMaterial(item)) {
|
||||
return MATERIALS;
|
||||
}
|
||||
|
||||
return MISC;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if an item is a common crafting material
|
||||
*/
|
||||
private static boolean isMaterial(Item item) {
|
||||
// Check common material items
|
||||
return item == Items.iron_ingot ||
|
||||
item == Items.gold_ingot ||
|
||||
item == Items.diamond ||
|
||||
item == Items.emerald ||
|
||||
item == Items.coal ||
|
||||
item == Items.redstone ||
|
||||
item == Items.glowstone_dust ||
|
||||
item == Items.quartz ||
|
||||
item == Items.leather ||
|
||||
item == Items.string ||
|
||||
item == Items.feather ||
|
||||
item == Items.bone ||
|
||||
item == Items.gunpowder ||
|
||||
item == Items.slime_ball ||
|
||||
item == Items.ender_pearl ||
|
||||
item == Items.blaze_rod ||
|
||||
item == Items.ghast_tear ||
|
||||
item == Items.gold_nugget ||
|
||||
item == Items.nether_wart ||
|
||||
item == Items.spider_eye ||
|
||||
item == Items.magma_cream ||
|
||||
item == Items.nether_star;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get icon item for category display
|
||||
*/
|
||||
public ItemStack getIconItem() {
|
||||
switch (this) {
|
||||
case ALL: return new ItemStack(Items.compass);
|
||||
case WEAPONS: return new ItemStack(Items.iron_sword);
|
||||
case ARMOR: return new ItemStack(Items.iron_chestplate);
|
||||
case TOOLS: return new ItemStack(Items.iron_pickaxe);
|
||||
case FOOD: return new ItemStack(Items.bread);
|
||||
case POTIONS: return new ItemStack(Items.potionitem);
|
||||
case BLOCKS: return new ItemStack(Item.getItemFromBlock(net.minecraft.init.Blocks.grass));
|
||||
case MATERIALS: return new ItemStack(Items.iron_ingot);
|
||||
case ENCHANTED: return new ItemStack(Items.enchanted_book);
|
||||
case MISC: return new ItemStack(Items.chest_minecart);
|
||||
default: return new ItemStack(Items.paper);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package noppes.npcs.constants;
|
||||
|
||||
import noppes.npcs.config.ConfigMarket;
|
||||
|
||||
/**
|
||||
* Duration options for auction listings.
|
||||
* Values are configurable via ConfigMarket.
|
||||
*/
|
||||
public enum EnumAuctionDuration {
|
||||
SHORT, // Default: 2 hours
|
||||
MEDIUM, // Default: 12 hours
|
||||
LONG, // Default: 24 hours
|
||||
VERY_LONG; // Default: 48 hours
|
||||
|
||||
/**
|
||||
* Get duration in milliseconds
|
||||
*/
|
||||
public long getMillis() {
|
||||
switch (this) {
|
||||
case SHORT:
|
||||
return ConfigMarket.AuctionDurationShort * 60L * 60L * 1000L;
|
||||
case MEDIUM:
|
||||
return ConfigMarket.AuctionDurationMedium * 60L * 60L * 1000L;
|
||||
case LONG:
|
||||
return ConfigMarket.AuctionDurationLong * 60L * 60L * 1000L;
|
||||
case VERY_LONG:
|
||||
return ConfigMarket.AuctionDurationVeryLong * 60L * 60L * 1000L;
|
||||
default:
|
||||
return 24 * 60L * 60L * 1000L;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get display name for GUI
|
||||
*/
|
||||
public String getDisplayName() {
|
||||
switch (this) {
|
||||
case SHORT:
|
||||
return ConfigMarket.AuctionDurationShort + " Hours";
|
||||
case MEDIUM:
|
||||
return ConfigMarket.AuctionDurationMedium + " Hours";
|
||||
case LONG:
|
||||
return ConfigMarket.AuctionDurationLong + " Hours";
|
||||
case VERY_LONG:
|
||||
return ConfigMarket.AuctionDurationVeryLong + " Hours";
|
||||
default:
|
||||
return "Unknown";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get listing fee for this duration
|
||||
*/
|
||||
public long getListingFee() {
|
||||
switch (this) {
|
||||
case SHORT:
|
||||
return ConfigMarket.AuctionFeeShort;
|
||||
case MEDIUM:
|
||||
return ConfigMarket.AuctionFeeMedium;
|
||||
case LONG:
|
||||
return ConfigMarket.AuctionFeeLong;
|
||||
case VERY_LONG:
|
||||
return ConfigMarket.AuctionFeeVeryLong;
|
||||
default:
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package noppes.npcs.constants;
|
||||
|
||||
/**
|
||||
* Status of an auction listing.
|
||||
*/
|
||||
public enum EnumAuctionStatus {
|
||||
ACTIVE, // Currently listed and accepting bids
|
||||
SOLD, // Successfully sold (buyout or auction end with bids)
|
||||
EXPIRED, // Ended without any bids
|
||||
CANCELLED, // Cancelled by seller (only allowed before first bid)
|
||||
CLAIMED; // Item/money has been claimed by respective parties
|
||||
|
||||
/**
|
||||
* Get display name for GUI
|
||||
*/
|
||||
public String getDisplayName() {
|
||||
switch (this) {
|
||||
case ACTIVE: return "Active";
|
||||
case SOLD: return "Sold";
|
||||
case EXPIRED: return "Expired";
|
||||
case CANCELLED: return "Cancelled";
|
||||
case CLAIMED: return "Claimed";
|
||||
default: return "Unknown";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get display color for GUI (MC color codes)
|
||||
*/
|
||||
public char getColorCode() {
|
||||
switch (this) {
|
||||
case ACTIVE: return 'a'; // Green
|
||||
case SOLD: return '6'; // Gold
|
||||
case EXPIRED: return '7'; // Gray
|
||||
case CANCELLED: return 'c'; // Red
|
||||
case CLAIMED: return '8'; // Dark gray
|
||||
default: return 'f'; // White
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if listing can still receive bids
|
||||
*/
|
||||
public boolean canBid() {
|
||||
return this == ACTIVE;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if listing needs claiming (item or money)
|
||||
*/
|
||||
public boolean needsClaiming() {
|
||||
return this == SOLD || this == EXPIRED || this == CANCELLED;
|
||||
}
|
||||
}
|
||||
@@ -63,5 +63,7 @@ public enum EnumGuiType {
|
||||
ScriptItem,
|
||||
ScriptBlock,
|
||||
Paintbrush,
|
||||
MagicBook;
|
||||
MagicBook,
|
||||
PlayerAuction,
|
||||
SetupAuctioneer;
|
||||
}
|
||||
@@ -2,5 +2,5 @@ package noppes.npcs.constants;
|
||||
|
||||
public enum EnumRoleType {
|
||||
|
||||
None, Trader, Follower, Bank, Transporter, Postman, Companion, Mount
|
||||
None, Trader, Follower, Bank, Transporter, Postman, Companion, Mount, Auctioneer
|
||||
}
|
||||
@@ -0,0 +1,662 @@
|
||||
package noppes.npcs.controllers;
|
||||
|
||||
import net.minecraft.entity.player.EntityPlayer;
|
||||
import net.minecraft.item.ItemStack;
|
||||
import net.minecraft.nbt.CompressedStreamTools;
|
||||
import net.minecraft.nbt.NBTTagCompound;
|
||||
import net.minecraft.nbt.NBTTagList;
|
||||
import noppes.npcs.CustomNpcs;
|
||||
import noppes.npcs.config.ConfigMarket;
|
||||
import noppes.npcs.constants.EnumAuctionCategory;
|
||||
import noppes.npcs.constants.EnumAuctionDuration;
|
||||
import noppes.npcs.constants.EnumAuctionStatus;
|
||||
import noppes.npcs.controllers.data.AuctionListing;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* Controller for the global auction house.
|
||||
* Manages all auction listings, bidding, and claims.
|
||||
*/
|
||||
public class AuctionController {
|
||||
private static final Logger logger = LogManager.getLogger(CustomNpcs.class);
|
||||
|
||||
public static AuctionController Instance;
|
||||
|
||||
// All auction listings by ID
|
||||
private Map<Integer, AuctionListing> listings = new ConcurrentHashMap<>();
|
||||
|
||||
// Next available listing ID
|
||||
private int nextId = 1;
|
||||
|
||||
// Indices for fast lookup
|
||||
private Map<UUID, List<Integer>> listingsBySeller = new ConcurrentHashMap<>();
|
||||
private Map<UUID, List<Integer>> listingsByBidder = new ConcurrentHashMap<>();
|
||||
|
||||
public AuctionController() {
|
||||
Instance = this;
|
||||
load();
|
||||
}
|
||||
|
||||
// ==================== Listing Management ====================
|
||||
|
||||
/**
|
||||
* Create a new auction listing
|
||||
* @return The new listing, or null if creation failed
|
||||
*/
|
||||
public AuctionListing createListing(EntityPlayer seller, ItemStack item,
|
||||
long startingPrice, long buyoutPrice,
|
||||
EnumAuctionDuration duration) {
|
||||
// Validate item
|
||||
String validation = AuctionListing.validateItem(item);
|
||||
if (validation != null) {
|
||||
logger.warn("Auction listing validation failed: " + validation);
|
||||
return null;
|
||||
}
|
||||
|
||||
// Check seller's listing limit
|
||||
int currentListings = getActiveListingsCount(seller.getUniqueID());
|
||||
int maxListings = getMaxListings(seller);
|
||||
if (currentListings >= maxListings) {
|
||||
logger.info("Player {} has reached max listings ({}/{})",
|
||||
seller.getCommandSenderName(), currentListings, maxListings);
|
||||
return null;
|
||||
}
|
||||
|
||||
// Calculate and charge listing fee
|
||||
AuctionListing listing = new AuctionListing(
|
||||
seller.getUniqueID(),
|
||||
seller.getCommandSenderName(),
|
||||
item,
|
||||
startingPrice,
|
||||
buyoutPrice,
|
||||
duration
|
||||
);
|
||||
|
||||
long listingFee = listing.getListingFee();
|
||||
if (listingFee > 0) {
|
||||
if (!CurrencyController.Instance.canAfford(seller, listingFee)) {
|
||||
logger.info("Player {} cannot afford listing fee of {}",
|
||||
seller.getCommandSenderName(), listingFee);
|
||||
return null;
|
||||
}
|
||||
CurrencyController.Instance.withdraw(seller, listingFee);
|
||||
}
|
||||
|
||||
// Assign ID and store
|
||||
listing.id = nextId++;
|
||||
listings.put(listing.id, listing);
|
||||
|
||||
// Update indices
|
||||
addToSellerIndex(seller.getUniqueID(), listing.id);
|
||||
|
||||
save();
|
||||
logger.info("Created auction listing {} by {} for {}",
|
||||
listing.id, seller.getCommandSenderName(),
|
||||
item.getDisplayName());
|
||||
|
||||
return listing;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a listing by ID
|
||||
*/
|
||||
public AuctionListing getListing(int id) {
|
||||
return listings.get(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all active listings
|
||||
*/
|
||||
public List<AuctionListing> getActiveListings() {
|
||||
processExpiredAuctions();
|
||||
return listings.values().stream()
|
||||
.filter(AuctionListing::isActive)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
/**
|
||||
* Get active listings by category
|
||||
*/
|
||||
public List<AuctionListing> getActiveListings(EnumAuctionCategory category) {
|
||||
if (category == EnumAuctionCategory.ALL) {
|
||||
return getActiveListings();
|
||||
}
|
||||
return getActiveListings().stream()
|
||||
.filter(l -> l.category == category)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
/**
|
||||
* Search listings by item name
|
||||
*/
|
||||
public List<AuctionListing> searchListings(String query) {
|
||||
String lowerQuery = query.toLowerCase();
|
||||
return getActiveListings().stream()
|
||||
.filter(l -> l.item.getDisplayName().toLowerCase().contains(lowerQuery))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all listings by a seller (all statuses)
|
||||
*/
|
||||
public List<AuctionListing> getListingsBySeller(UUID sellerUUID) {
|
||||
List<Integer> ids = listingsBySeller.get(sellerUUID);
|
||||
if (ids == null) {
|
||||
return new ArrayList<>();
|
||||
}
|
||||
return ids.stream()
|
||||
.map(listings::get)
|
||||
.filter(Objects::nonNull)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
/**
|
||||
* Get active listing count for a seller
|
||||
*/
|
||||
public int getActiveListingsCount(UUID sellerUUID) {
|
||||
return (int) getListingsBySeller(sellerUUID).stream()
|
||||
.filter(l -> l.status == EnumAuctionStatus.ACTIVE)
|
||||
.count();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get listings where player is the high bidder
|
||||
*/
|
||||
public List<AuctionListing> getListingsAsBidder(UUID bidderUUID) {
|
||||
List<Integer> ids = listingsByBidder.get(bidderUUID);
|
||||
if (ids == null) {
|
||||
return new ArrayList<>();
|
||||
}
|
||||
return ids.stream()
|
||||
.map(listings::get)
|
||||
.filter(Objects::nonNull)
|
||||
.filter(l -> bidderUUID.equals(l.highBidderUUID))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
/**
|
||||
* Get listings that need claiming by a player
|
||||
* (items won, sales proceeds, cancelled/expired items)
|
||||
*/
|
||||
public List<AuctionListing> getClaimableListings(UUID playerUUID) {
|
||||
List<AuctionListing> claimable = new ArrayList<>();
|
||||
|
||||
for (AuctionListing listing : listings.values()) {
|
||||
// Seller can claim proceeds from sold items
|
||||
if (listing.sellerUUID.equals(playerUUID) &&
|
||||
listing.status == EnumAuctionStatus.SOLD &&
|
||||
!listing.sellerClaimed) {
|
||||
claimable.add(listing);
|
||||
}
|
||||
|
||||
// Seller can claim back cancelled/expired items
|
||||
if (listing.sellerUUID.equals(playerUUID) &&
|
||||
(listing.status == EnumAuctionStatus.CANCELLED ||
|
||||
listing.status == EnumAuctionStatus.EXPIRED) &&
|
||||
!listing.sellerClaimed) {
|
||||
claimable.add(listing);
|
||||
}
|
||||
|
||||
// Buyer can claim won items
|
||||
if (listing.highBidderUUID != null &&
|
||||
listing.highBidderUUID.equals(playerUUID) &&
|
||||
listing.status == EnumAuctionStatus.SOLD &&
|
||||
!listing.buyerClaimed) {
|
||||
claimable.add(listing);
|
||||
}
|
||||
}
|
||||
|
||||
return claimable;
|
||||
}
|
||||
|
||||
// ==================== Bidding ====================
|
||||
|
||||
/**
|
||||
* Place a bid on an auction
|
||||
* @return true if bid was successful
|
||||
*/
|
||||
public boolean placeBid(int listingId, EntityPlayer bidder, long amount) {
|
||||
AuctionListing listing = listings.get(listingId);
|
||||
if (listing == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check if bidder can afford
|
||||
if (!CurrencyController.Instance.canAfford(bidder, amount)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Store previous bidder for refund
|
||||
UUID previousBidder = listing.highBidderUUID;
|
||||
long previousBidAmount = listing.currentBid;
|
||||
|
||||
// Try to place bid
|
||||
if (!listing.placeBid(bidder.getUniqueID(), bidder.getCommandSenderName(), amount)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Withdraw bid amount from new bidder
|
||||
CurrencyController.Instance.withdraw(bidder, amount);
|
||||
|
||||
// Refund previous bidder via claims system
|
||||
if (previousBidder != null) {
|
||||
CurrencyController.Instance.addClaim(
|
||||
previousBidder,
|
||||
previousBidAmount,
|
||||
"Auction Outbid",
|
||||
String.valueOf(listingId)
|
||||
);
|
||||
}
|
||||
|
||||
// Update bidder index
|
||||
addToBidderIndex(bidder.getUniqueID(), listingId);
|
||||
|
||||
save();
|
||||
logger.info("Bid placed on listing {} by {} for {}",
|
||||
listingId, bidder.getCommandSenderName(), amount);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute buyout on an auction
|
||||
* @return true if buyout was successful
|
||||
*/
|
||||
public boolean buyout(int listingId, EntityPlayer buyer) {
|
||||
AuctionListing listing = listings.get(listingId);
|
||||
if (listing == null || listing.buyoutPrice <= 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check if buyer can afford
|
||||
if (!CurrencyController.Instance.canAfford(buyer, listing.buyoutPrice)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Store previous bidder for refund
|
||||
UUID previousBidder = listing.highBidderUUID;
|
||||
long previousBidAmount = listing.currentBid;
|
||||
|
||||
// Execute buyout
|
||||
if (!listing.buyout(buyer.getUniqueID(), buyer.getCommandSenderName())) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Withdraw buyout amount from buyer
|
||||
CurrencyController.Instance.withdraw(buyer, listing.buyoutPrice);
|
||||
|
||||
// Refund previous bidder via claims system
|
||||
if (previousBidder != null) {
|
||||
CurrencyController.Instance.addClaim(
|
||||
previousBidder,
|
||||
previousBidAmount,
|
||||
"Auction Outbid (Buyout)",
|
||||
String.valueOf(listingId)
|
||||
);
|
||||
}
|
||||
|
||||
// Update bidder index
|
||||
addToBidderIndex(buyer.getUniqueID(), listingId);
|
||||
|
||||
save();
|
||||
logger.info("Buyout executed on listing {} by {} for {}",
|
||||
listingId, buyer.getCommandSenderName(), listing.buyoutPrice);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cancel an auction listing
|
||||
* @return true if cancellation was successful
|
||||
*/
|
||||
public boolean cancelListing(int listingId, EntityPlayer requester) {
|
||||
AuctionListing listing = listings.get(listingId);
|
||||
if (listing == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!listing.cancel(requester.getUniqueID())) {
|
||||
return false;
|
||||
}
|
||||
|
||||
save();
|
||||
logger.info("Listing {} cancelled by {}",
|
||||
listingId, requester.getCommandSenderName());
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
// ==================== Claiming ====================
|
||||
|
||||
/**
|
||||
* Claim seller proceeds from a sold auction
|
||||
* @return true if claim was successful
|
||||
*/
|
||||
public boolean claimSellerProceeds(int listingId, EntityPlayer seller) {
|
||||
AuctionListing listing = listings.get(listingId);
|
||||
if (listing == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!listing.sellerUUID.equals(seller.getUniqueID())) {
|
||||
return false; // Not the seller
|
||||
}
|
||||
|
||||
if (listing.status != EnumAuctionStatus.SOLD) {
|
||||
return false; // Not sold
|
||||
}
|
||||
|
||||
if (listing.sellerClaimed) {
|
||||
return false; // Already claimed
|
||||
}
|
||||
|
||||
// Deposit proceeds to seller
|
||||
long proceeds = listing.getSellerProceeds();
|
||||
CurrencyController.Instance.deposit(seller, proceeds);
|
||||
|
||||
listing.sellerClaimed = true;
|
||||
checkAndMarkClaimed(listing);
|
||||
save();
|
||||
|
||||
logger.info("Seller {} claimed {} from listing {}",
|
||||
seller.getCommandSenderName(), proceeds, listingId);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Claim item from won auction
|
||||
* @return The item if successful, null otherwise
|
||||
*/
|
||||
public ItemStack claimBuyerItem(int listingId, EntityPlayer buyer) {
|
||||
AuctionListing listing = listings.get(listingId);
|
||||
if (listing == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (listing.highBidderUUID == null ||
|
||||
!listing.highBidderUUID.equals(buyer.getUniqueID())) {
|
||||
return null; // Not the buyer
|
||||
}
|
||||
|
||||
if (listing.status != EnumAuctionStatus.SOLD) {
|
||||
return null; // Not sold
|
||||
}
|
||||
|
||||
if (listing.buyerClaimed) {
|
||||
return null; // Already claimed
|
||||
}
|
||||
|
||||
listing.buyerClaimed = true;
|
||||
checkAndMarkClaimed(listing);
|
||||
save();
|
||||
|
||||
logger.info("Buyer {} claimed item from listing {}",
|
||||
buyer.getCommandSenderName(), listingId);
|
||||
|
||||
return listing.item.copy();
|
||||
}
|
||||
|
||||
/**
|
||||
* Claim item from cancelled or expired auction (seller reclaiming)
|
||||
* @return The item if successful, null otherwise
|
||||
*/
|
||||
public ItemStack claimExpiredItem(int listingId, EntityPlayer seller) {
|
||||
AuctionListing listing = listings.get(listingId);
|
||||
if (listing == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!listing.sellerUUID.equals(seller.getUniqueID())) {
|
||||
return null; // Not the seller
|
||||
}
|
||||
|
||||
if (listing.status != EnumAuctionStatus.CANCELLED &&
|
||||
listing.status != EnumAuctionStatus.EXPIRED) {
|
||||
return null; // Not claimable
|
||||
}
|
||||
|
||||
if (listing.sellerClaimed) {
|
||||
return null; // Already claimed
|
||||
}
|
||||
|
||||
listing.sellerClaimed = true;
|
||||
listing.status = EnumAuctionStatus.CLAIMED;
|
||||
save();
|
||||
|
||||
logger.info("Seller {} reclaimed item from listing {}",
|
||||
seller.getCommandSenderName(), listingId);
|
||||
|
||||
return listing.item.copy();
|
||||
}
|
||||
|
||||
/**
|
||||
* Mark listing as fully claimed if both parties have claimed
|
||||
*/
|
||||
private void checkAndMarkClaimed(AuctionListing listing) {
|
||||
if (listing.status == EnumAuctionStatus.SOLD) {
|
||||
if (listing.sellerClaimed && listing.buyerClaimed) {
|
||||
listing.status = EnumAuctionStatus.CLAIMED;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== Expiration Processing ====================
|
||||
|
||||
/**
|
||||
* Process all expired auctions
|
||||
* Call this periodically (e.g., every minute)
|
||||
*/
|
||||
public void processExpiredAuctions() {
|
||||
boolean changed = false;
|
||||
|
||||
for (AuctionListing listing : listings.values()) {
|
||||
if (listing.status == EnumAuctionStatus.ACTIVE && listing.isExpired()) {
|
||||
listing.finalize();
|
||||
changed = true;
|
||||
|
||||
// If sold, add proceeds to seller's claims
|
||||
if (listing.status == EnumAuctionStatus.SOLD) {
|
||||
// Proceeds will be claimed manually, no automatic deposit
|
||||
logger.info("Auction {} ended with sale to {} for {}",
|
||||
listing.id, listing.highBidderName, listing.currentBid);
|
||||
} else {
|
||||
logger.info("Auction {} expired without bids", listing.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (changed) {
|
||||
save();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Clean up old claimed listings
|
||||
* Call this periodically (e.g., daily)
|
||||
*/
|
||||
public void cleanupOldListings() {
|
||||
long claimExpirationMs = ConfigMarket.ClaimExpirationDays * 24L * 60L * 60L * 1000L;
|
||||
if (claimExpirationMs <= 0) {
|
||||
return; // No expiration
|
||||
}
|
||||
|
||||
long cutoffTime = System.currentTimeMillis() - claimExpirationMs;
|
||||
List<Integer> toRemove = new ArrayList<>();
|
||||
|
||||
for (AuctionListing listing : listings.values()) {
|
||||
if (listing.status == EnumAuctionStatus.CLAIMED &&
|
||||
listing.expirationTime < cutoffTime) {
|
||||
toRemove.add(listing.id);
|
||||
}
|
||||
}
|
||||
|
||||
for (int id : toRemove) {
|
||||
AuctionListing removed = listings.remove(id);
|
||||
if (removed != null) {
|
||||
removeFromSellerIndex(removed.sellerUUID, id);
|
||||
if (removed.highBidderUUID != null) {
|
||||
removeFromBidderIndex(removed.highBidderUUID, id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!toRemove.isEmpty()) {
|
||||
save();
|
||||
logger.info("Cleaned up {} old auction listings", toRemove.size());
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== Index Management ====================
|
||||
|
||||
private void addToSellerIndex(UUID seller, int listingId) {
|
||||
listingsBySeller.computeIfAbsent(seller, k -> new ArrayList<>()).add(listingId);
|
||||
}
|
||||
|
||||
private void removeFromSellerIndex(UUID seller, int listingId) {
|
||||
List<Integer> ids = listingsBySeller.get(seller);
|
||||
if (ids != null) {
|
||||
ids.remove(Integer.valueOf(listingId));
|
||||
}
|
||||
}
|
||||
|
||||
private void addToBidderIndex(UUID bidder, int listingId) {
|
||||
listingsByBidder.computeIfAbsent(bidder, k -> new ArrayList<>()).add(listingId);
|
||||
}
|
||||
|
||||
private void removeFromBidderIndex(UUID bidder, int listingId) {
|
||||
List<Integer> ids = listingsByBidder.get(bidder);
|
||||
if (ids != null) {
|
||||
ids.remove(Integer.valueOf(listingId));
|
||||
}
|
||||
}
|
||||
|
||||
private void rebuildIndices() {
|
||||
listingsBySeller.clear();
|
||||
listingsByBidder.clear();
|
||||
|
||||
for (AuctionListing listing : listings.values()) {
|
||||
addToSellerIndex(listing.sellerUUID, listing.id);
|
||||
if (listing.highBidderUUID != null) {
|
||||
addToBidderIndex(listing.highBidderUUID, listing.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== Permission Helpers ====================
|
||||
|
||||
/**
|
||||
* Get maximum listings allowed for a player
|
||||
*/
|
||||
public int getMaxListings(EntityPlayer player) {
|
||||
// TODO: Check for permission-based overrides
|
||||
// e.g., CustomNpcsPermissions.hasCustomPermission(player, "cnpc.auction.slots.10")
|
||||
return ConfigMarket.DefaultMaxListings;
|
||||
}
|
||||
|
||||
// ==================== Persistence ====================
|
||||
|
||||
public void save() {
|
||||
File saveDir = CustomNpcs.getWorldSaveDirectory();
|
||||
if (saveDir == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
NBTTagCompound compound = new NBTTagCompound();
|
||||
compound.setInteger("NextId", nextId);
|
||||
|
||||
NBTTagList listingList = new NBTTagList();
|
||||
for (AuctionListing listing : listings.values()) {
|
||||
listingList.appendTag(listing.writeToNBT(new NBTTagCompound()));
|
||||
}
|
||||
compound.setTag("Listings", listingList);
|
||||
|
||||
File file = new File(saveDir, "auctions.dat");
|
||||
File backup = new File(saveDir, "auctions.dat_old");
|
||||
|
||||
if (file.exists()) {
|
||||
if (backup.exists()) {
|
||||
backup.delete();
|
||||
}
|
||||
file.renameTo(backup);
|
||||
}
|
||||
|
||||
file = new File(saveDir, "auctions.dat");
|
||||
FileOutputStream fos = new FileOutputStream(file);
|
||||
CompressedStreamTools.writeCompressed(compound, fos);
|
||||
fos.close();
|
||||
|
||||
} catch (Exception e) {
|
||||
logger.error("Error saving auctions", e);
|
||||
}
|
||||
}
|
||||
|
||||
public void load() {
|
||||
File saveDir = CustomNpcs.getWorldSaveDirectory();
|
||||
if (saveDir == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
listings.clear();
|
||||
|
||||
try {
|
||||
File file = new File(saveDir, "auctions.dat");
|
||||
if (!file.exists()) {
|
||||
file = new File(saveDir, "auctions.dat_old");
|
||||
if (!file.exists()) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
FileInputStream fis = new FileInputStream(file);
|
||||
NBTTagCompound compound = CompressedStreamTools.readCompressed(fis);
|
||||
fis.close();
|
||||
|
||||
nextId = compound.getInteger("NextId");
|
||||
if (nextId < 1) {
|
||||
nextId = 1;
|
||||
}
|
||||
|
||||
NBTTagList listingList = compound.getTagList("Listings", 10);
|
||||
for (int i = 0; i < listingList.tagCount(); i++) {
|
||||
AuctionListing listing = new AuctionListing();
|
||||
listing.readFromNBT(listingList.getCompoundTagAt(i));
|
||||
listings.put(listing.id, listing);
|
||||
}
|
||||
|
||||
rebuildIndices();
|
||||
|
||||
logger.info("Loaded {} auction listings", listings.size());
|
||||
|
||||
} catch (Exception e) {
|
||||
logger.error("Error loading auctions", e);
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== Statistics ====================
|
||||
|
||||
/**
|
||||
* Get total number of active listings
|
||||
*/
|
||||
public int getActiveListingCount() {
|
||||
return (int) listings.values().stream()
|
||||
.filter(l -> l.status == EnumAuctionStatus.ACTIVE)
|
||||
.count();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get total number of all listings
|
||||
*/
|
||||
public int getTotalListingCount() {
|
||||
return listings.size();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,392 @@
|
||||
package noppes.npcs.controllers.data;
|
||||
|
||||
import kamkeel.npcs.controllers.data.attribute.ItemTradeAttribute;
|
||||
import net.minecraft.item.ItemStack;
|
||||
import net.minecraft.nbt.NBTTagCompound;
|
||||
import noppes.npcs.config.ConfigMarket;
|
||||
import noppes.npcs.constants.EnumAuctionCategory;
|
||||
import noppes.npcs.constants.EnumAuctionDuration;
|
||||
import noppes.npcs.constants.EnumAuctionStatus;
|
||||
import noppes.npcs.controllers.AuctionBlacklist;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* Represents a single auction listing.
|
||||
* Contains all data about the item, seller, bidding, and timing.
|
||||
*/
|
||||
public class AuctionListing {
|
||||
// Unique identifier
|
||||
public int id;
|
||||
|
||||
// Seller info
|
||||
public UUID sellerUUID;
|
||||
public String sellerName;
|
||||
|
||||
// Item being sold
|
||||
public ItemStack item;
|
||||
|
||||
// Pricing
|
||||
public long startingPrice;
|
||||
public long buyoutPrice; // 0 = no buyout option
|
||||
public long currentBid;
|
||||
|
||||
// Current high bidder
|
||||
public UUID highBidderUUID;
|
||||
public String highBidderName;
|
||||
|
||||
// Previous bidder (for refund notifications)
|
||||
public UUID previousBidderUUID;
|
||||
public String previousBidderName;
|
||||
public long previousBidAmount;
|
||||
|
||||
// Timing
|
||||
public long listingTime; // When the auction was created
|
||||
public long expirationTime; // When the auction ends
|
||||
public EnumAuctionDuration duration;
|
||||
|
||||
// Status
|
||||
public EnumAuctionStatus status = EnumAuctionStatus.ACTIVE;
|
||||
|
||||
// Category for filtering
|
||||
public EnumAuctionCategory category = EnumAuctionCategory.MISC;
|
||||
|
||||
// Claim tracking
|
||||
public boolean sellerClaimed = false; // Has seller claimed their proceeds?
|
||||
public boolean buyerClaimed = false; // Has buyer claimed their item?
|
||||
|
||||
public AuctionListing() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new auction listing
|
||||
*/
|
||||
public AuctionListing(UUID seller, String sellerName, ItemStack item,
|
||||
long startPrice, long buyout, EnumAuctionDuration duration) {
|
||||
this.sellerUUID = seller;
|
||||
this.sellerName = sellerName;
|
||||
this.item = item.copy();
|
||||
this.startingPrice = startPrice;
|
||||
this.buyoutPrice = buyout;
|
||||
this.currentBid = 0; // No bids yet
|
||||
this.duration = duration;
|
||||
this.listingTime = System.currentTimeMillis();
|
||||
this.expirationTime = listingTime + duration.getMillis();
|
||||
this.category = EnumAuctionCategory.categorize(item);
|
||||
this.status = EnumAuctionStatus.ACTIVE;
|
||||
}
|
||||
|
||||
// ==================== Status Checks ====================
|
||||
|
||||
/**
|
||||
* Check if auction has expired
|
||||
*/
|
||||
public boolean isExpired() {
|
||||
return System.currentTimeMillis() >= expirationTime;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if auction is still active
|
||||
*/
|
||||
public boolean isActive() {
|
||||
return status == EnumAuctionStatus.ACTIVE && !isExpired();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get time remaining in milliseconds
|
||||
*/
|
||||
public long getTimeRemaining() {
|
||||
return Math.max(0, expirationTime - System.currentTimeMillis());
|
||||
}
|
||||
|
||||
/**
|
||||
* Get formatted time remaining
|
||||
*/
|
||||
public String getTimeRemainingFormatted() {
|
||||
long remaining = getTimeRemaining();
|
||||
|
||||
if (remaining <= 0) {
|
||||
return "Ended";
|
||||
}
|
||||
|
||||
long hours = remaining / (60L * 60L * 1000L);
|
||||
long minutes = (remaining % (60L * 60L * 1000L)) / (60L * 1000L);
|
||||
|
||||
if (hours > 24) {
|
||||
long days = hours / 24;
|
||||
hours = hours % 24;
|
||||
return days + "d " + hours + "h";
|
||||
} else if (hours > 0) {
|
||||
return hours + "h " + minutes + "m";
|
||||
} else {
|
||||
long seconds = (remaining % (60L * 1000L)) / 1000L;
|
||||
return minutes + "m " + seconds + "s";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if auction has any bids
|
||||
*/
|
||||
public boolean hasBids() {
|
||||
return highBidderUUID != null;
|
||||
}
|
||||
|
||||
// ==================== Bidding Methods ====================
|
||||
|
||||
/**
|
||||
* Calculate minimum valid bid amount
|
||||
*/
|
||||
public long getMinimumBid() {
|
||||
if (!hasBids()) {
|
||||
return startingPrice;
|
||||
}
|
||||
// Minimum increment is configured percent or 1, whichever is greater
|
||||
long minIncrement = Math.max(1, (long) (currentBid * ConfigMarket.MinBidIncrementPercent));
|
||||
return currentBid + minIncrement;
|
||||
}
|
||||
|
||||
/**
|
||||
* Place a bid
|
||||
* @return true if bid was successful
|
||||
*/
|
||||
public boolean placeBid(UUID bidder, String bidderName, long amount) {
|
||||
if (status != EnumAuctionStatus.ACTIVE) {
|
||||
return false;
|
||||
}
|
||||
if (isExpired()) {
|
||||
return false;
|
||||
}
|
||||
if (amount < getMinimumBid()) {
|
||||
return false;
|
||||
}
|
||||
if (bidder.equals(sellerUUID)) {
|
||||
return false; // Can't bid on own item
|
||||
}
|
||||
|
||||
// Store previous bidder for refund notification
|
||||
if (highBidderUUID != null) {
|
||||
previousBidderUUID = highBidderUUID;
|
||||
previousBidderName = highBidderName;
|
||||
previousBidAmount = currentBid;
|
||||
}
|
||||
|
||||
// Update high bidder
|
||||
highBidderUUID = bidder;
|
||||
highBidderName = bidderName;
|
||||
currentBid = amount;
|
||||
|
||||
// Snipe protection - extend if bid placed in final minutes
|
||||
if (ConfigMarket.SnipeProtectionMinutes > 0) {
|
||||
long timeRemaining = getTimeRemaining();
|
||||
long thresholdMs = ConfigMarket.SnipeProtectionThreshold * 60L * 1000L;
|
||||
|
||||
if (timeRemaining < thresholdMs) {
|
||||
// Extend TO snipe protection time, not by it
|
||||
long newExpiration = System.currentTimeMillis() +
|
||||
(ConfigMarket.SnipeProtectionMinutes * 60L * 1000L);
|
||||
// Only extend if it would actually extend the auction
|
||||
if (newExpiration > expirationTime) {
|
||||
expirationTime = newExpiration;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute buyout (instant purchase at buyout price)
|
||||
* @return true if buyout was successful
|
||||
*/
|
||||
public boolean buyout(UUID buyer, String buyerName) {
|
||||
if (status != EnumAuctionStatus.ACTIVE) {
|
||||
return false;
|
||||
}
|
||||
if (isExpired()) {
|
||||
return false;
|
||||
}
|
||||
if (buyoutPrice <= 0) {
|
||||
return false; // No buyout available
|
||||
}
|
||||
if (buyer.equals(sellerUUID)) {
|
||||
return false; // Can't buy own item
|
||||
}
|
||||
|
||||
// Store previous bidder for refund
|
||||
if (highBidderUUID != null) {
|
||||
previousBidderUUID = highBidderUUID;
|
||||
previousBidderName = highBidderName;
|
||||
previousBidAmount = currentBid;
|
||||
}
|
||||
|
||||
highBidderUUID = buyer;
|
||||
highBidderName = buyerName;
|
||||
currentBid = buyoutPrice;
|
||||
status = EnumAuctionStatus.SOLD;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cancel listing (seller only, before any bids)
|
||||
* @return true if cancellation was successful
|
||||
*/
|
||||
public boolean cancel(UUID requester) {
|
||||
if (!requester.equals(sellerUUID)) {
|
||||
return false; // Only seller can cancel
|
||||
}
|
||||
if (hasBids()) {
|
||||
return false; // Can't cancel with active bids
|
||||
}
|
||||
if (status != EnumAuctionStatus.ACTIVE) {
|
||||
return false;
|
||||
}
|
||||
|
||||
status = EnumAuctionStatus.CANCELLED;
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Finalize auction when it expires
|
||||
* Call this when auction timer runs out
|
||||
*/
|
||||
public void finalize() {
|
||||
if (status != EnumAuctionStatus.ACTIVE) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (hasBids()) {
|
||||
status = EnumAuctionStatus.SOLD;
|
||||
} else {
|
||||
status = EnumAuctionStatus.EXPIRED;
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== Validation ====================
|
||||
|
||||
/**
|
||||
* Validate that the item can be listed
|
||||
* @return null if valid, error message if invalid
|
||||
*/
|
||||
public static String validateItem(ItemStack item) {
|
||||
if (item == null || item.getItem() == null) {
|
||||
return "Invalid item";
|
||||
}
|
||||
|
||||
// Check trade restrictions (Untradeable, ProfileSlot Bound, Soulbound)
|
||||
if (!ItemTradeAttribute.canTrade(item)) {
|
||||
String reason = ItemTradeAttribute.getTradeBlockReason(item);
|
||||
return reason != null ? reason : "Item cannot be traded";
|
||||
}
|
||||
|
||||
// Check blacklist
|
||||
if (AuctionBlacklist.Instance != null && AuctionBlacklist.Instance.isBlacklisted(item)) {
|
||||
return "Item is blacklisted from auction";
|
||||
}
|
||||
|
||||
return null; // Valid
|
||||
}
|
||||
|
||||
// ==================== Financial Calculations ====================
|
||||
|
||||
/**
|
||||
* Get listing fee for this auction
|
||||
*/
|
||||
public long getListingFee() {
|
||||
long flatFee = duration.getListingFee();
|
||||
long percentFee = (long) (startingPrice * ConfigMarket.ListingFeePercent);
|
||||
return flatFee + percentFee;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get seller's proceeds after sales tax
|
||||
*/
|
||||
public long getSellerProceeds() {
|
||||
if (status != EnumAuctionStatus.SOLD) {
|
||||
return 0;
|
||||
}
|
||||
long tax = (long) (currentBid * ConfigMarket.SalesTaxPercent);
|
||||
return currentBid - tax;
|
||||
}
|
||||
|
||||
// ==================== NBT Serialization ====================
|
||||
|
||||
public NBTTagCompound writeToNBT(NBTTagCompound compound) {
|
||||
compound.setInteger("Id", id);
|
||||
compound.setString("SellerUUID", sellerUUID.toString());
|
||||
compound.setString("SellerName", sellerName);
|
||||
compound.setTag("Item", item.writeToNBT(new NBTTagCompound()));
|
||||
compound.setLong("StartPrice", startingPrice);
|
||||
compound.setLong("BuyoutPrice", buyoutPrice);
|
||||
compound.setLong("CurrentBid", currentBid);
|
||||
|
||||
if (highBidderUUID != null) {
|
||||
compound.setString("BidderUUID", highBidderUUID.toString());
|
||||
compound.setString("BidderName", highBidderName);
|
||||
}
|
||||
|
||||
if (previousBidderUUID != null) {
|
||||
compound.setString("PrevBidderUUID", previousBidderUUID.toString());
|
||||
compound.setString("PrevBidderName", previousBidderName);
|
||||
compound.setLong("PrevBidAmount", previousBidAmount);
|
||||
}
|
||||
|
||||
compound.setLong("ListingTime", listingTime);
|
||||
compound.setLong("ExpirationTime", expirationTime);
|
||||
compound.setInteger("Duration", duration.ordinal());
|
||||
compound.setInteger("Status", status.ordinal());
|
||||
compound.setInteger("Category", category.ordinal());
|
||||
compound.setBoolean("SellerClaimed", sellerClaimed);
|
||||
compound.setBoolean("BuyerClaimed", buyerClaimed);
|
||||
|
||||
return compound;
|
||||
}
|
||||
|
||||
public void readFromNBT(NBTTagCompound compound) {
|
||||
id = compound.getInteger("Id");
|
||||
sellerUUID = UUID.fromString(compound.getString("SellerUUID"));
|
||||
sellerName = compound.getString("SellerName");
|
||||
item = ItemStack.loadItemStackFromNBT(compound.getCompoundTag("Item"));
|
||||
startingPrice = compound.getLong("StartPrice");
|
||||
buyoutPrice = compound.getLong("BuyoutPrice");
|
||||
currentBid = compound.getLong("CurrentBid");
|
||||
|
||||
if (compound.hasKey("BidderUUID")) {
|
||||
highBidderUUID = UUID.fromString(compound.getString("BidderUUID"));
|
||||
highBidderName = compound.getString("BidderName");
|
||||
}
|
||||
|
||||
if (compound.hasKey("PrevBidderUUID")) {
|
||||
previousBidderUUID = UUID.fromString(compound.getString("PrevBidderUUID"));
|
||||
previousBidderName = compound.getString("PrevBidderName");
|
||||
previousBidAmount = compound.getLong("PrevBidAmount");
|
||||
}
|
||||
|
||||
listingTime = compound.getLong("ListingTime");
|
||||
expirationTime = compound.getLong("ExpirationTime");
|
||||
|
||||
int durationOrdinal = compound.getInteger("Duration");
|
||||
if (durationOrdinal >= 0 && durationOrdinal < EnumAuctionDuration.values().length) {
|
||||
duration = EnumAuctionDuration.values()[durationOrdinal];
|
||||
} else {
|
||||
duration = EnumAuctionDuration.LONG;
|
||||
}
|
||||
|
||||
int statusOrdinal = compound.getInteger("Status");
|
||||
if (statusOrdinal >= 0 && statusOrdinal < EnumAuctionStatus.values().length) {
|
||||
status = EnumAuctionStatus.values()[statusOrdinal];
|
||||
} else {
|
||||
status = EnumAuctionStatus.ACTIVE;
|
||||
}
|
||||
|
||||
int categoryOrdinal = compound.getInteger("Category");
|
||||
if (categoryOrdinal >= 0 && categoryOrdinal < EnumAuctionCategory.values().length) {
|
||||
category = EnumAuctionCategory.values()[categoryOrdinal];
|
||||
} else {
|
||||
category = EnumAuctionCategory.MISC;
|
||||
}
|
||||
|
||||
sellerClaimed = compound.getBoolean("SellerClaimed");
|
||||
buyerClaimed = compound.getBoolean("BuyerClaimed");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
package noppes.npcs.roles;
|
||||
|
||||
import net.minecraft.entity.player.EntityPlayer;
|
||||
import net.minecraft.nbt.NBTTagCompound;
|
||||
import noppes.npcs.NoppesUtilServer;
|
||||
import noppes.npcs.config.ConfigMarket;
|
||||
import noppes.npcs.constants.EnumGuiType;
|
||||
import noppes.npcs.controllers.AuctionController;
|
||||
import noppes.npcs.entity.EntityNPCInterface;
|
||||
|
||||
/**
|
||||
* NPC role for Auctioneer - provides access to the global auction house.
|
||||
*/
|
||||
public class RoleAuctioneer extends RoleInterface {
|
||||
|
||||
// Configuration
|
||||
public boolean showActiveListings = true; // Show active listings tab
|
||||
public boolean showMyListings = true; // Show player's listings tab
|
||||
public boolean showMyBids = true; // Show player's bids tab
|
||||
public boolean showClaims = true; // Show claimable items tab
|
||||
public boolean allowCreatingListings = true; // Allow creating new listings
|
||||
public boolean allowBidding = true; // Allow bidding on items
|
||||
public boolean allowBuyout = true; // Allow buyout purchases
|
||||
|
||||
// Custom greeting messages
|
||||
public String welcomeMessage = "";
|
||||
public String noAuctionMessage = "";
|
||||
|
||||
public RoleAuctioneer(EntityNPCInterface npc) {
|
||||
super(npc);
|
||||
}
|
||||
|
||||
@Override
|
||||
public NBTTagCompound writeToNBT(NBTTagCompound compound) {
|
||||
compound.setBoolean("ShowActiveListings", showActiveListings);
|
||||
compound.setBoolean("ShowMyListings", showMyListings);
|
||||
compound.setBoolean("ShowMyBids", showMyBids);
|
||||
compound.setBoolean("ShowClaims", showClaims);
|
||||
compound.setBoolean("AllowCreatingListings", allowCreatingListings);
|
||||
compound.setBoolean("AllowBidding", allowBidding);
|
||||
compound.setBoolean("AllowBuyout", allowBuyout);
|
||||
compound.setString("WelcomeMessage", welcomeMessage);
|
||||
compound.setString("NoAuctionMessage", noAuctionMessage);
|
||||
return compound;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void readFromNBT(NBTTagCompound compound) {
|
||||
showActiveListings = compound.hasKey("ShowActiveListings") ?
|
||||
compound.getBoolean("ShowActiveListings") : true;
|
||||
showMyListings = compound.hasKey("ShowMyListings") ?
|
||||
compound.getBoolean("ShowMyListings") : true;
|
||||
showMyBids = compound.hasKey("ShowMyBids") ?
|
||||
compound.getBoolean("ShowMyBids") : true;
|
||||
showClaims = compound.hasKey("ShowClaims") ?
|
||||
compound.getBoolean("ShowClaims") : true;
|
||||
allowCreatingListings = compound.hasKey("AllowCreatingListings") ?
|
||||
compound.getBoolean("AllowCreatingListings") : true;
|
||||
allowBidding = compound.hasKey("AllowBidding") ?
|
||||
compound.getBoolean("AllowBidding") : true;
|
||||
allowBuyout = compound.hasKey("AllowBuyout") ?
|
||||
compound.getBoolean("AllowBuyout") : true;
|
||||
welcomeMessage = compound.getString("WelcomeMessage");
|
||||
noAuctionMessage = compound.getString("NoAuctionMessage");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void interact(EntityPlayer player) {
|
||||
// Check if auction system is enabled
|
||||
if (!ConfigMarket.AuctionEnabled) {
|
||||
if (!noAuctionMessage.isEmpty()) {
|
||||
npc.say(player, noAuctionMessage);
|
||||
} else {
|
||||
npc.say(player, "The auction house is currently closed.");
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Process expired auctions before opening GUI
|
||||
if (AuctionController.Instance != null) {
|
||||
AuctionController.Instance.processExpiredAuctions();
|
||||
}
|
||||
|
||||
// Say welcome message
|
||||
if (!welcomeMessage.isEmpty()) {
|
||||
npc.say(player, welcomeMessage);
|
||||
} else {
|
||||
npc.say(player, npc.advanced.getInteractLine());
|
||||
}
|
||||
|
||||
// Open auction GUI
|
||||
NoppesUtilServer.sendOpenGui(player, EnumGuiType.PlayerAuction, npc);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if player has claims waiting
|
||||
*/
|
||||
public boolean hasClaimsWaiting(EntityPlayer player) {
|
||||
if (AuctionController.Instance == null) {
|
||||
return false;
|
||||
}
|
||||
return !AuctionController.Instance.getClaimableListings(player.getUniqueID()).isEmpty();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get number of active listings in the auction house
|
||||
*/
|
||||
public int getActiveListingCount() {
|
||||
if (AuctionController.Instance == null) {
|
||||
return 0;
|
||||
}
|
||||
return AuctionController.Instance.getActiveListingCount();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get player's current listing count
|
||||
*/
|
||||
public int getPlayerListingCount(EntityPlayer player) {
|
||||
if (AuctionController.Instance == null) {
|
||||
return 0;
|
||||
}
|
||||
return AuctionController.Instance.getActiveListingsCount(player.getUniqueID());
|
||||
}
|
||||
|
||||
/**
|
||||
* Get player's maximum allowed listings
|
||||
*/
|
||||
public int getPlayerMaxListings(EntityPlayer player) {
|
||||
if (AuctionController.Instance == null) {
|
||||
return ConfigMarket.DefaultMaxListings;
|
||||
}
|
||||
return AuctionController.Instance.getMaxListings(player);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user