Cristi Railean

Act as an expert Minecraft Spigot/Paper plugin developer. Write a complete, production-ready Java plugin (Paper API 1.20.4+) for a DonutSMP-style Crystal PvP / Economy server that adds a streamer-style CoinFlip / Gamble UI system.

Core Requirements:

  1. Economy Integration: Hook into Vault to handle player balances cleanly without duplication or race-condition exploits.
  2. Commands & Trigger Button:

• /gamble or /cf opens the main Gamble GUI. • Include a configurable option to give players a physical GUI Button Item (e.g., a glowing Nether Star or Sunflowers named &e&lGAMBLE MENU &7(Right-Click)) on join or via /gambleitem that opens the UI when right-clicked.

  1. Main Gamble UI (Chest GUI - 27 slots):

• Sleek dark-themed border using black and gray stained glass panes. • Active Matches Section: Display active player-created coinflips using the creator's Player Head, showing the bet amount, win chance (50/50), and a [CLICK TO JOIN] prompt. • Create Match Button (Slot 22): Opens a Bet Selection GUI with preset streamer-style bet buttons ($1,000, $10,000, $100,000, $1,000,000, and ALL-IN) plus a custom sign/chat input option. • Stats Item (Slot 26): Shows the player's total wins, losses, and net profit.

  1. Streamer-Style Rolling Animation UI:

• When two players enter a match, open a 27-slot Rolling Animation GUI for both players simultaneously. • Rapidly cycle the two players' heads across the center slot (Slot 13) with decreasing speed over 4 seconds, accompanied by crisp sound effects (BLOCK_NOTE_BLOCK_HAT ticking, ENTITY_PLAYER_LEVELUP / ENTITY_EXPERIENCE_ORB_PICKUP on win, ENTITY_VILLAGER_NO on loss). • Display a Title & Subtitle on the winner's screen (&a&lYOU WON! / &7+$<amount>) and broadcast high-roller wins over $500,000 in global chat with hoverable stats.

  1. Anti-Exploit & Safety:

• Refund bets automatically if a player disconnects while waiting for an opponent or if the server restarts. • Prevent inventory click exploits (InventoryClickEvent cancelled in all custom GUIs).

  1. Deliverables: Provide the full plugin.yml, config.yml, and clean, commented Java classes ready to compile with Maven/Gradle.
Kodari AI
KodariToday at 9:52 am 3
CoinFlipGamble
A streamer-style CoinFlip gambling plugin for Crystal PvP servers with a sleek dark-themed GUI system. Players create coinflip matches with preset bet amounts or custom values, and opponents join for a 50/50 chance to win. Features a dramatic rolling animation with player heads cycling across the screen, sound effects, and win/loss titles. Integrates Vault economy with race-condition protection, automatic refunds on disconnect or server restart, and global chat broadcasts for high-roller wins over $500,000. Includes a physical trigger item that opens the GUI on right-click, plus comprehensive stats tracking for wins, losses, and net profit.

I’ll build the Vault-backed menus, escrow and refunds, rolling animation, and persistent stats. Custom bets will use chat input.

Created the Vault-backed CoinFlip plugin with GUI menus, chat bet entry, rolling animation, stats, and refunds on disconnect or normal restart.

Safety limitation: Vault and the plugin’s data file cannot commit transactions atomically. A crash during a withdrawal or payout can require manual reconciliation; this implementation cannot guarantee duplicate-free recovery in that case.

Kodari can make mistakes. Review important code before using.
Files
src
build.gradle
Code
4 472
src/main/java/com/kodari/gamble/GamblePlugin.java
package com.kodari.gamble;

import com.cryptomorin.xseries.XEnchantment;
import com.cryptomorin.xseries.XItemFlag;
import com.cryptomorin.xseries.XMaterial;
import com.cryptomorin.xseries.XSound;
import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.api.chat.ComponentBuilder;
import net.md_5.bungee.api.chat.HoverEvent;
import net.md_5.bungee.api.chat.TextComponent;
import net.milkbowl.vault.economy.Economy;
import net.milkbowl.vault.economy.EconomyResponse;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryDragEvent;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.inventory.EquipmentSlot;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.SkullMeta;
import org.bukkit.persistence.PersistentDataType;
import org.bukkit.NamespacedKey;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitRunnable;

import java.io.File;
import java.io.IOException;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

public final class GamblePlugin extends JavaPlugin implements Listener {
    private Economy economy;
    private NamespacedKey buttonKey;
    private File dataFile;
    private YamlConfiguration data;
    private final Map<UUID, Match> waiting = new LinkedHashMap<>();
    private final Set<UUID> rolling = new HashSet<>();
    private final Set<UUID> chatInput = ConcurrentHashMap.newKeySet();
    private final SecureRandom random = new SecureRandom();
    private boolean storageFailed;

    private static final class Match {
        final UUID creator;
        final double bet;
        Match(UUID creator, double bet) { this.creator = creator; this.bet = bet; }
    }

    private static final class Menu implements InventoryHolder {
        final String type;
        final Map<Integer, UUID> matches = new HashMap<>();
        final int page;
        Inventory inventory;
        Menu(String type, int page) { this.type = type; this.page = page; }
        @Override public Inventory getInventory() { return inventory; }
    }

    @Override public void onEnable() {
        saveDefaultConfig();
        RegisteredServiceProvider<Economy> provider = getServer().getServicesManager().getRegistration(Economy.class);
        if (provider == null || provider.getProvider() == null) {
            getLogger().severe("Vault has no economy provider; disabling Gamble.");
            getServer().getPluginManager().disablePlugin(this);
            return;
        }
        economy = provider.getProvider();
        buttonKey = new NamespacedKey(this, "menu_button");
        dataFile = new File(getDataFolder(), "data.yml");
        data = YamlConfiguration.loadConfiguration(dataFile);
        getServer().getPluginManager().registerEvents(this, this);
        recoverEscrow();
    }

    @Override public void onDisable() {
        if (economy == null || data == null) return;
        for (Player player : Bukkit.getOnlinePlayers()) {
            if (player.getOpenInventory().getTopInventory().getHolder() instanceof Menu) player.closeInventory();
        }
        waiting.clear();
        rolling.clear();
        recoverEscrow();
    }

    private boolean saveData() {
        try {
            data.save(dataFile);
            return true;
        } catch (IOException ex) {
            storageFailed = true;
            getLogger().severe("Cannot save data.yml; gambling is disabled: " + ex.getMessage());
            return false;
        }
    }

    private String escrow(UUID id) { return "escrow." + id; }

    private void recoverEscrow() {
        if (data.getConfigurationSection("escrow") == null) return;
        for (String key : new HashSet<>(data.getConfigurationSection("escrow").getKeys(false))) {
            try { refund(UUID.fromString(key)); }
            catch (IllegalArgumentException ex) { getLogger().severe("Invalid escrow UUID: " + key); }
        }
    }

    private void refund(UUID id) {
        double amount = data.getDouble(escrow(id));
        if (amount <= 0 || !Double.isFinite(amount)) return;
        EconomyResponse response = economy.depositPlayer(Bukkit.getOfflinePlayer(id), amount);
        if (!response.transactionSuccess()) {
            getLogger().severe("Refund failed for " + id + ": " + response.errorMessage + ". It remains in data.yml for retry on restart.");
            return;
        }
        data.set(escrow(id), null);
        saveData();
        Player player = Bukkit.getPlayer(id);
        if (player != null) player.sendMessage(color("&eYour bet of " + money(amount) + " was refunded."));
    }

    private boolean takeBet(Player player, double amount) {
        if (storageFailed || data.contains(escrow(player.getUniqueId()))) {
            player.sendMessage(color("&cGambling is unavailable while an outstanding transaction needs attention."));
            return false;
        }
        double min = Math.max(0.01, getConfig().getDouble("minimum-bet", 1));
        double max = Math.min(1_000_000_000_000.0, getConfig().getDouble("maximum-bet", 1_000_000_000));
        int digits = economy.fractionalDigits();
        int scale = digits < 0 ? 2 : Math.min(digits, 2);
        double factor = Math.pow(10, scale);
        if (!Double.isFinite(amount) || amount < min || amount > max || Math.abs(amount * factor - Math.rint(amount * factor)) > 0.00001) {
            player.sendMessage(color("&cInvalid bet. Allowed: " + money(min) + " to " + money(max) + ", up to " + scale + " decimal places."));
            return false;
        }
        EconomyResponse response = economy.withdrawPlayer(player, amount);
        if (!response.transactionSuccess()) {
            player.sendMessage(color("&cCould not withdraw your bet: " + response.errorMessage));
            return false;
        }
        data.set(escrow(player.getUniqueId()), amount);
        if (!saveData()) {
            refund(player.getUniqueId());
            player.sendMessage(color("&cCould not save your bet; a refund was attempted."));
            return false;
        }
        return true;
    }

    @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
        if (!(sender instanceof Player)) { sender.sendMessage("Players only."); return true; }
        Player player = (Player) sender;
        if (command.getName().equalsIgnoreCase("gambleitem")) {
            giveButton(player);
        } else {
            openMain(player, 0);
        }
        return true;
    }

    private void giveButton(Player player) {
        for (ItemStack item : player.getInventory().getContents()) if (isButton(item)) {
            player.sendMessage(color("&eYou already have a gamble menu item.")); return;
        }
        ItemStack item = item(getConfig().getString("button.material", "NETHER_STAR"), getConfig().getString("button.name", "&e&lGAMBLE MENU &7(Right-Click)"));
        ItemMeta meta = item.getItemMeta();
        meta.getPersistentDataContainer().set(buttonKey, PersistentDataType.BYTE, (byte) 1);
        if (getConfig().getBoolean("button.glow", true)) {
            XEnchantment.matchXEnchantment("UNBREAKING").ifPresent(e -> meta.addEnchant(e.getEnchant(), 1, true));
            XItemFlag.of("HIDE_ENCHANTS").ifPresent(f -> f.set(meta));
        }
        item.setItemMeta(meta);
        if (!player.getInventory().addItem(item).isEmpty()) player.sendMessage(color("&cYour inventory is full."));
        else player.sendMessage(color("&aYou received a gamble menu item."));
    }

    private boolean isButton(ItemStack item) {
        return item != null && item.hasItemMeta() && item.getItemMeta().getPersistentDataContainer().has(buttonKey, PersistentDataType.BYTE);
    }