Search in sources :

Example 6 with Item

use of mc.dragons.core.gameobject.item.Item in project DragonsOnline by UniverseCraft.

the class LootTable method getDrops.

/**
 * @param loc
 * @return The items the NPC dropped at a specified location.
 *
 * @implNote Probabilities are factored in to this, so identical
 * 	calls may not produce identical results.
 */
public Set<Item> getDrops(Location loc) {
    if (lootTable == null) {
        return new HashSet<>();
    }
    double multiplier = Dragons.getInstance().getServerOptions().getDropChanceMultiplier();
    Set<Region> regions = regionLoader.getRegionsByLocation(loc);
    Set<Item> drops = new HashSet<>();
    for (Region region : regions) {
        Document regionLoots = (Document) lootTable.get(region.getName());
        if (regionLoots == null) {
            continue;
        }
        for (Entry<String, Object> loot : (Iterable<Entry<String, Object>>) regionLoots.entrySet()) {
            double chance = (double) loot.getValue();
            if (Math.random() < chance * multiplier / 100.0D) {
                ItemClass itemClass = itemClassLoader.getItemClassByClassName(loot.getKey());
                Item item = itemLoader.registerNew(itemClass);
                drops.add(item);
            }
        }
    }
    return drops;
}
Also used : Item(mc.dragons.core.gameobject.item.Item) ItemClass(mc.dragons.core.gameobject.item.ItemClass) Region(mc.dragons.core.gameobject.region.Region) Document(org.bson.Document) HashSet(java.util.HashSet)

Example 7 with Item

use of mc.dragons.core.gameobject.item.Item in project DragonsOnline by UniverseCraft.

the class RestatCommand method onCommand.

@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
    if (!requirePermission(sender, PermissionLevel.GM) || !requirePlayer(sender))
        return true;
    User user = user(sender);
    if (args.length == 0) {
        sender.sendMessage(ChatColor.RED + "/restat armor <ArmorValue>");
        sender.sendMessage(ChatColor.RED + "/restat cooldown <CooldownSeconds>");
        sender.sendMessage(ChatColor.RED + "/restat damage <DamageValue>");
        sender.sendMessage(ChatColor.RED + "/restat lvmin <LevelMin>");
        sender.sendMessage(ChatColor.RED + "/restat stacksize <MaxStackSize>");
        sender.sendMessage(ChatColor.RED + "/restat speedboost <SpeedBoost>");
        sender.sendMessage(ChatColor.RED + "/restat unbreakable <Unbreakable>");
        sender.sendMessage(ChatColor.RED + "/restat undroppable <Undroppable>");
        return true;
    }
    Item heldItem = ItemLoader.fromBukkit(user.getPlayer().getInventory().getItemInMainHand());
    if (heldItem == null) {
        sender.sendMessage(ChatColor.RED + "You must hold the item you want to restat!");
        return true;
    }
    if (args[0].equalsIgnoreCase("armor")) {
        heldItem.setArmor(Double.valueOf(args[1]));
        sender.sendMessage(ChatColor.GREEN + "Updated item armor value to " + args[1]);
    } else if (args[0].equalsIgnoreCase("cooldown")) {
        heldItem.setCooldown(Double.valueOf(args[1]));
        sender.sendMessage(ChatColor.GREEN + "Updated item cooldown to " + args[1]);
    } else if (args[0].equalsIgnoreCase("damage")) {
        heldItem.setDamage(Double.valueOf(args[1]));
        sender.sendMessage(ChatColor.GREEN + "Updated item damage value to " + args[1]);
    } else if (args[0].equalsIgnoreCase("lvmin")) {
        heldItem.setLevelMin(Integer.valueOf(args[1]));
        sender.sendMessage(ChatColor.GREEN + "Updated item level min to " + args[1]);
    } else if (args[0].equalsIgnoreCase("stacksize")) {
        heldItem.setMaxStackSize(Integer.valueOf(args[1]));
        sender.sendMessage(ChatColor.GREEN + "Updated item max stack size to " + args[1]);
    } else if (args[0].equalsIgnoreCase("speedboost")) {
        heldItem.setSpeedBoost(Double.valueOf(args[1]));
        sender.sendMessage(ChatColor.GREEN + "Updated item speed boost to " + args[1]);
    } else if (args[0].equalsIgnoreCase("unbreakable")) {
        heldItem.setUnbreakable(Boolean.valueOf(args[1]));
        sender.sendMessage(ChatColor.GREEN + "Updated item unbreakability flag to " + args[1]);
    } else if (args[0].equalsIgnoreCase("undroppable")) {
        heldItem.setUndroppable(Boolean.valueOf(args[1]));
        sender.sendMessage(ChatColor.GREEN + "Updated item undroppability flag to " + args[1]);
    } else {
        sender.sendMessage(ChatColor.RED + "Invalid arguments! /restat");
        return true;
    }
    heldItem.setCustom(true);
    heldItem.updateItemStackData();
    user.getPlayer().getInventory().setItemInMainHand(heldItem.getItemStack());
    return true;
}
Also used : Item(mc.dragons.core.gameobject.item.Item) User(mc.dragons.core.gameobject.user.User)

Example 8 with Item

use of mc.dragons.core.gameobject.item.Item in project DragonsOnline by UniverseCraft.

the class ItemCommand method giveItemOfClass.

private void giveItemOfClass(CommandSender sender, String[] args) {
    if (args.length == 1) {
        sender.sendMessage(ChatColor.RED + "Insufficient arguments! /item give <ClassName> [Player] [Quantity]");
        return;
    }
    ItemClass itemClass = lookupItemClass(sender, args[1]);
    if (itemClass == null)
        return;
    Item item = itemLoader.registerNew(itemClass);
    if (args.length > 3) {
        Integer quantityOpt = parseInt(sender, args[3]);
        if (quantityOpt == null)
            return;
        item.setQuantity(quantityOpt);
    }
    if (args.length > 2) {
        Player target = Bukkit.getPlayerExact(args[2]);
        if (target == null) {
            sender.sendMessage(ChatColor.RED + "That player is not online!");
            return;
        }
        User targetUser = UserLoader.fromPlayer(target);
        targetUser.giveItem(item);
    } else if (!isPlayer(sender)) {
        sender.sendMessage(ChatColor.RED + "Console must specify a player to give the item to!");
    } else {
        user(sender).giveItem(item);
    }
}
Also used : ItemClass(mc.dragons.core.gameobject.item.ItemClass) Item(mc.dragons.core.gameobject.item.Item) Player(org.bukkit.entity.Player) User(mc.dragons.core.gameobject.user.User)

Example 9 with Item

use of mc.dragons.core.gameobject.item.Item in project DragonsOnline by UniverseCraft.

the class RenameCommand method onCommand.

@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
    if (!requirePermission(sender, PermissionLevel.GM) || !requirePlayer(sender))
        return true;
    User user = user(sender);
    if (args.length == 0) {
        sender.sendMessage(ChatColor.RED + "Specify a new name for the item! /rename <NewItemName>");
        return true;
    }
    String renameTo = ChatColor.YELLOW + ChatColor.translateAlternateColorCodes('&', StringUtil.concatArgs(args, 0));
    Item heldItem = ItemLoader.fromBukkit(user.getPlayer().getInventory().getItemInMainHand());
    if (heldItem == null) {
        sender.sendMessage(ChatColor.RED + "You must hold the item you want to rename!");
        return true;
    }
    heldItem.setCustom(true);
    user.getPlayer().getInventory().setItemInMainHand(heldItem.rename(renameTo));
    sender.sendMessage(ChatColor.GREEN + "Renamed your held item to " + renameTo);
    return true;
}
Also used : Item(mc.dragons.core.gameobject.item.Item) User(mc.dragons.core.gameobject.user.User)

Example 10 with Item

use of mc.dragons.core.gameobject.item.Item in project DragonsOnline by UniverseCraft.

the class ExperimentalCommands method onCommand.

@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
    if (!requirePermission(sender, SystemProfileFlag.DEVELOPMENT))
        return true;
    Player player = player(sender);
    User user = user(sender);
    if (label.equalsIgnoreCase("testmineregen")) {
        int minutesPerSecond = Integer.valueOf(args[0]);
        int radius = Integer.valueOf(args[1]);
        double alpha = Double.valueOf(args[2]);
        double beta = Double.valueOf(args[3]);
        final Player fPlayer = player;
        final Location center = player.getLocation();
        int maxIterations = Integer.valueOf(args[4]);
        Bukkit.broadcastMessage("==Beginning simulation of mining regen. SimulatedMinutesPerSecond=" + minutesPerSecond + ", Radius=" + radius + ", Alpha=" + alpha + ", Beta=" + beta + ", MaxIterations=" + maxIterations);
        new BukkitRunnable() {

            private int iterations = 0;

            @Override
            public void run() {
                int players = (int) fPlayer.getNearbyEntities(radius, radius, radius).stream().filter(e -> e.getType() == EntityType.PLAYER).count();
                int mined = 0;
                int cX = center.getBlockX();
                int cY = center.getBlockY();
                int cZ = center.getBlockZ();
                for (int x = cX - radius; x <= cX + radius; x++) {
                    for (int y = cY - radius; y <= cY + radius; y++) {
                        for (int z = cZ - radius; z <= cZ + radius; z++) {
                            Block block = center.getWorld().getBlockAt(x, y, z);
                            if (block.getType() == Material.AIR) {
                                mined++;
                            }
                        }
                    }
                }
                if (mined == 0) {
                    Bukkit.broadcastMessage("==No blocks left to regenerate, ending simulation (" + iterations + " iterations)==");
                    this.cancel();
                    return;
                }
                int regen = (int) Math.ceil(mined * (alpha + beta * players));
                Bukkit.broadcastMessage("Regenerating " + regen + " blocks (players=" + players + ", mined=" + mined + ")");
                int done = 0;
                for (int x = cX - radius; x <= cX + radius; x++) {
                    for (int y = cY - radius; y <= cY + radius; y++) {
                        for (int z = cZ - radius; z <= cZ + radius; z++) {
                            Block block = center.getWorld().getBlockAt(x, y, z);
                            if (block.getType() == Material.AIR && done < regen) {
                                done++;
                                block.setType(Material.GOLD_BLOCK);
                            }
                        }
                    }
                }
                iterations++;
                if (iterations >= maxIterations) {
                    Bukkit.broadcastMessage("==Completed simulation==");
                    this.cancel();
                }
            }
        }.runTaskTimer(Dragons.getInstance(), 20L, 20L / minutesPerSecond);
    } else if (label.equalsIgnoreCase("testpermission")) {
        if (player.hasPermission(args[0])) {
            sender.sendMessage("Yes you have it");
        } else {
            sender.sendMessage("No you don't have it");
        }
    } else if (label.equalsIgnoreCase("helditemdata") || label.equalsIgnoreCase("whatamiholding")) {
        ItemStack itemStack = player.getInventory().getItemInMainHand();
        sender.sendMessage("pdc=" + itemStack.getItemMeta().getPersistentDataContainer());
        sender.sendMessage("uuid=" + itemStack.getItemMeta().getPersistentDataContainer().get(Item.ITEM_UUID_KEY, PersistentDataType.STRING));
        sender.sendMessage("bukkit amt=" + itemStack.getAmount());
        Item item = ItemLoader.fromBukkit(itemStack);
        sender.sendMessage("item=" + item);
        if (item != null) {
            sender.sendMessage("db amt=" + item.getQuantity());
            sender.sendMessage("item class=" + item.getClassName());
            sender.sendMessage("item data=" + item.getData().toJson());
        }
        if (args.length > 0 && args[0].equalsIgnoreCase("-verbose")) {
            sender.sendMessage("item stack data=" + itemStack);
        }
    } else if (label.equalsIgnoreCase("getitemuuid")) {
        Item item = ItemLoader.fromBukkit(player.getInventory().getItemInMainHand());
        if (item == null)
            return true;
        sender.spigot().sendMessage(StringUtil.clickableHoverableText("" + item.getUUID(), "" + item.getUUID(), true, "Click to copy"), StringUtil.clickableHoverableText(" (" + item.getClassName() + ")", "/item " + item.getClassName() + " ", true, "Click to manage class"));
    } else if (label.equalsIgnoreCase("testlocaluserstorage")) {
        sender.sendMessage(ChatColor.YELLOW + "METHOD ONE (Full object scan):");
        int n_fullscan = 0;
        for (GameObject gameObject : Dragons.getInstance().getGameObjectRegistry().getRegisteredObjects(GameObjectType.USER)) {
            User u = (User) gameObject;
            sender.sendMessage("- User: " + u);
            sender.sendMessage("    - name=" + u.getName());
            sender.sendMessage("    - player=" + u.getPlayer());
            n_fullscan++;
        }
        int n_cached = 0;
        sender.sendMessage(ChatColor.YELLOW + "METHOD TWO (UserLoader cache):");
        for (User test : UserLoader.allUsers()) {
            sender.sendMessage("- User: " + test);
            sender.sendMessage("    - name=" + test.getName());
            sender.sendMessage("    - player=" + test.getPlayer());
            n_cached++;
        }
        if (n_fullscan != n_cached) {
            sender.sendMessage(ChatColor.RED + "WARNING: Different methods gave different results (fullscan=" + n_fullscan + " vs cached=" + n_cached + ")");
        }
    } else if (label.equalsIgnoreCase("testgui")) {
        GUI gui = new GUI(3, "Test GUI").add(new GUIElement(11, Material.COBBLESTONE, "I matter!", "Multi-line\nlore\n\nis cool", 2, u -> u.debug("Clicked the cobble"))).add(new GUIElement(13, Material.APPLE, "iApple", "", 5, u -> u.debug("Clicked da appel"))).add(itemClassLoader.getItemClassByClassName("GMSword").getAsGuiElement(15, 3, 1999.99, false, u -> u.debug("Purchasing GM Sword!!!")));
        gui.open(user);
    } else if (label.equalsIgnoreCase("testhdfont")) {
        player.sendMessage(StringUtil.toHdFont(StringUtil.concatArgs(args, 0)));
    } else if (label.equalsIgnoreCase("rawtext")) {
        player.sendMessage(ChatColor.translateAlternateColorCodes('&', StringUtil.concatArgs(args, 0)));
    } else if (label.equalsIgnoreCase("testtabname")) {
        lookupPlayer(sender, args[0]).setPlayerListName(ChatColor.translateAlternateColorCodes('&', StringUtil.concatArgs(args, 1)));
    } else if (label.equalsIgnoreCase("whoami")) {
        sender.sendMessage("Player=" + player);
        sender.sendMessage("User=" + user);
        for (User test : UserLoader.allUsers()) {
            if (user.getIdentifier().equals(test.getIdentifier()) && !test.equals(user)) {
                sender.sendMessage("-Also user " + test + " => " + test.getPlayer());
            }
        }
        sender.sendMessage("StorageAccess=" + (user == null ? "null" : user.getStorageAccess()));
    } else if (label.equalsIgnoreCase("testpathfinding")) {
        Location spawnLoc = player.getLocation().add(player.getLocation().getDirection().clone().setY(0).normalize().multiply(10.0));
        LivingEntity e = (LivingEntity) Bukkit.getWorld("undead_forest").spawnEntity(spawnLoc, EntityType.VILLAGER);
        Dragons.getInstance().getBridge().setEntityAI(e, false);
        PathfindingUtil.walkToLocation(e, player.getLocation(), 0.2, unused -> {
        });
    } else if (label.equalsIgnoreCase("testphasing")) {
        Entity entity = player.getWorld().spawnEntity(player.getLocation(), EntityType.valueOf(args[0]));
        if (entity instanceof ArmorStand) {
            ((ArmorStand) entity).setCustomName("Test test test");
            ((ArmorStand) entity).setCustomNameVisible(true);
        }
        Dragons.getInstance().getEntityHider().hideEntity(player, entity);
    } else if (label.equalsIgnoreCase("testtpsrecord")) {
        List<Double> record = Dragons.getInstance().getTPSRecord();
        int back = Integer.valueOf(args[0]);
        sender.sendMessage(record.size() + " records");
        sender.sendMessage("starting from " + back + " records back");
        for (int i = record.size() - 1 - back; i < record.size(); i++) {
            sender.sendMessage("#" + i + " = " + record.get(i) + " (" + (record.size() - 1 - i) + " frames back)");
        }
    } else if (label.equalsIgnoreCase("stresstest")) {
        int n = Integer.valueOf(args[0]);
        Location loc = player.getLocation();
        for (int i = 0; i < n; i++) {
            npcLoader.registerNew(loc, "F2-UndeadZombie");
        }
        player.sendMessage(ChatColor.GREEN + "Spawned " + n + " undead zombies at your location.");
    } else if (label.equalsIgnoreCase("killmobs")) {
        int n = 0;
        for (Entity e : player.getWorld().getEntities()) {
            NPC npc = NPCLoader.fromBukkit(e);
            if (npc == null)
                continue;
            if (npc.getNPCType().isPersistent())
                continue;
            npc.remove();
            n++;
        }
        player.sendMessage(ChatColor.GREEN + "Killed " + n + " non-persistent mobs.");
    } else if (label.equalsIgnoreCase("testarmorstandpose")) {
        ArmorStand armorStand = (ArmorStand) player.getWorld().spawnEntity(player.getLocation(), EntityType.ARMOR_STAND);
        armorStand.setLeftLegPose(new EulerAngle(Double.valueOf(args[0]), Double.valueOf(args[1]), Double.valueOf(args[2])));
        armorStand.setRightLegPose(new EulerAngle(Double.valueOf(args[3]), Double.valueOf(args[4]), Double.valueOf(args[5])));
    } else if (label.equalsIgnoreCase("testlogging")) {
        for (Level level : new Level[] { Level.OFF, Level.SEVERE, Level.WARNING, Level.INFO, Level.CONFIG, Level.FINE, Level.FINER, Level.FINEST, Level.ALL }) {
            Dragons.getInstance().getLogger().log(level, "Testing log message on level " + level);
        }
    } else if (label.equalsIgnoreCase("testleveling")) {
        player.sendMessage("level=" + user.getLevel());
        player.sendMessage("xp=" + user.getXP());
        int prevMax = User.calculateMaxXP(user.getLevel());
        player.sendMessage("prevMax=" + prevMax);
        int nextMax = User.calculateMaxXP(user.getLevel() + 1);
        player.sendMessage("nextMax=" + nextMax);
        int n = user.getXP() - prevMax;
        int d = nextMax - prevMax;
        player.sendMessage("numerator=" + n);
        player.sendMessage("denominator=" + d);
        player.sendMessage("progress=" + ((float) n / d));
        player.sendMessage("progress=" + ((double) n / d));
        player.sendMessage("progress=" + user.getLevelProgress());
    } else if (label.equalsIgnoreCase("testexceptions")) {
        sender.sendMessage("Throwing an NPE");
        // Throws an NPE
        ((User) null).autoSave();
    } else if (label.equalsIgnoreCase("testuuidlookup")) {
        UserLoader.uuidFromUsername(args[0], uuid -> {
            sender.sendMessage("UUID of " + args[0] + " is " + uuid);
        });
    } else if (label.equalsIgnoreCase("testcorrelationlogging")) {
        CorrelationLogger loader = Dragons.getInstance().getLightweightLoaderRegistry().getLoader(CorrelationLogger.class);
        UUID id = loader.registerNewCorrelationID();
        loader.log(id, Level.INFO, "hewwo uwu");
        loader.log(id, Level.SEVERE, "ouch");
        sender.sendMessage("correlation id=" + id);
    } else if (label.equalsIgnoreCase("testbase64encoding")) {
        String encoded = Base64.getEncoder().encodeToString(StringUtil.concatArgs(args, 0).getBytes());
        sender.sendMessage("encoded: " + encoded);
        String decoded = new String(Base64.getDecoder().decode(encoded));
        sender.sendMessage("decoded: " + decoded);
    } else if (label.equalsIgnoreCase("testnetworkmessage")) {
        debugHandler.send(new Document("payload", new Document("babey", "babey")), args[0]);
    } else if (label.equalsIgnoreCase("testdocumentdelta")) {
        Document a = new Document("a", 1).append("b", 2).append("c", new Document("x", 3).append("y", 4));
        Document b = new Document("a", 2).append("b", 2).append("d", 3).append("c", new Document("x", 3).append("y", 2));
        Document delta = StorageUtil.getDelta(a, b);
        Document result = StorageUtil.applyDelta(b, delta);
        sender.sendMessage("a=" + a.toJson());
        sender.sendMessage("b=" + b.toJson());
        sender.sendMessage("delta=" + delta.toJson());
        sender.sendMessage("result=" + result.toJson());
    } else if (label.equalsIgnoreCase("testnewfonts")) {
        String[] fonts = { "minecraft:default", "minecraft:uniform", "minecraft:alt" };
        String text = StringUtil.concatArgs(args, 0);
        for (String font : fonts) {
            TextComponent tc = new TextComponent(text);
            tc.setFont(font);
            sender.spigot().sendMessage(new TextComponent(font + " "), tc);
        }
    } else if (label.equalsIgnoreCase("testuserlookup")) {
        User target = lookupUser(sender, args[0]);
        if (target == null) {
            sender.sendMessage("Not found");
        } else {
            sender.sendMessage("User is " + target);
        }
    } else if (label.equalsIgnoreCase("writelog")) {
        Level level = this.lookup(sender, () -> Level.parse(args[0].toUpperCase()), ChatColor.RED + "Invalid log level! /writelog <level> <message>");
        String message = StringUtil.concatArgs(args, 1);
        if (level == null || message == null)
            return true;
        dragons.getLogger().log(level, message);
        sender.sendMessage("Log entry written successfully");
    } else if (label.equalsIgnoreCase("testheader")) {
        player.setPlayerListHeader(user.tablistText(StringUtil.concatArgs(args, 0)));
    } else if (label.equalsIgnoreCase("testfooter")) {
        player.setPlayerListFooter(user.tablistText(StringUtil.concatArgs(args, 0)));
    } else if (label.equalsIgnoreCase("testinvisibleslimes")) {
        boolean allOK = true;
        for (Entity entity : player.getWorld().getEntities()) {
            if (entity instanceof Slime) {
                Slime slime = (Slime) entity;
                if (!slime.isInvisible()) {
                    sender.sendMessage(ChatColor.RED + "SLIME #" + slime.getEntityId() + " is NOT invisible (" + StringUtil.locToString(slime.getLocation()) + ")");
                    allOK = false;
                } else {
                    sender.sendMessage(ChatColor.GREEN + "SLIME #" + slime.getEntityId() + " IS invisible (" + StringUtil.locToString(slime.getLocation()) + ")");
                }
            }
        }
        if (!allOK) {
            sender.sendMessage(ChatColor.RED + "-- One or more slimes in this world are visible --");
        }
    } else if (label.equalsIgnoreCase("testrevealslimes")) {
        for (Entity entity : player.getWorld().getEntities()) {
            if (entity instanceof Slime) {
                Slime slime = (Slime) entity;
                slime.setInvisible(false);
                player.spawnParticle(Particle.DRIP_LAVA, slime.getLocation(), 10);
            }
        }
    } else if (label.equalsIgnoreCase("testhideslimes")) {
        for (Entity entity : player.getWorld().getEntities()) {
            if (entity instanceof Slime) {
                Slime slime = (Slime) entity;
                slime.setInvisible(true);
                player.spawnParticle(Particle.DRIP_LAVA, slime.getLocation(), 10);
            }
        }
    } else if (label.equalsIgnoreCase("testdestroyslimes")) {
        for (Entity entity : player.getWorld().getEntities()) {
            if (entity instanceof Slime) {
                Slime slime = (Slime) entity;
                player.spawnParticle(Particle.DRIP_LAVA, slime.getLocation(), 10);
                HologramUtil.unclickableifySlime(slime);
                slime.remove();
            }
        }
    } else if (label.equalsIgnoreCase("testbadslimes")) {
        int total = 0;
        for (World world : Bukkit.getWorlds()) {
            total += world.getEntitiesByClass(Slime.class).size();
            for (Slime slime : world.getEntitiesByClass(Slime.class)) {
                Dragons.getInstance().getLogger().severe("BAD SLIME YOU SUCK: " + StringUtil.entityToString(slime) + " - allow:" + slime.hasMetadata("allow") + " - nRClickHandlers:" + PlayerEventListeners.getRightClickHandlers(slime) + " - ClickySlime:" + slime.hasMetadata(HologramUtil.KEY_CLICKABLE_SLIME));
            }
        }
        Dragons.getInstance().getLogger().debug("THERE ARE " + total + " SLIMES");
    } else if (label.equalsIgnoreCase("mockuser")) {
        Document data = Document.parse(user(sender).getData().toJson());
        data.append("_id", UUID.randomUUID());
        data.append("username", args[0]);
        data.append("currentServer", args[1]);
        data.append("mock", true);
        dragons.getMongoConfig().getDatabase().getCollection("gameobjects").insertOne(data);
        sender.sendMessage("UUID: " + data.get("_id", UUID.class));
    } else if (label.equalsIgnoreCase("mocksudo")) {
        Document data = dragons.getMongoConfig().getDatabase().getCollection("gameobjects").find(new Document("username", args[0])).first();
        if (data.getBoolean("mock", false)) {
            dragons.getRemoteAdminHandler().sendRemoteSudo(data.getString("currentServer"), data.get("_id", UUID.class), StringUtil.concatArgs(args, 1));
        }
    } else if (label.equalsIgnoreCase("mockinject")) {
        StorageManager storageManager = dragons.getPersistentStorageManager();
        StorageAccess storageAccess = storageManager.getStorageAccess(GameObjectType.USER, new Document("username", args[0]));
        MockPlayer mockPlayer = new MockPlayer(storageAccess.getIdentifier().getUUID(), args[0]);
        MockUser mockUser = new MockUser(null, storageManager, storageAccess);
        dragons.getGameObjectRegistry().getRegisteredObjects().removeIf(obj -> obj instanceof User && ((User) obj).getName().equalsIgnoreCase(args[0]));
        dragons.getGameObjectRegistry().getRegisteredObjects().add(mockUser);
        UserLoader.allUsers().removeIf(u -> u.getName().equalsIgnoreCase(args[0]));
        UserLoader.allUsers().add(mockUser);
        UserLoader.assign(mockPlayer, mockUser);
        mockUser.setPlayer(mockPlayer);
        sender.sendMessage("UUID: " + mockUser.getUUID());
        sender.sendMessage("Server: " + mockUser.getServerName() + " ?= " + storageAccess.get("currentServer", String.class));
        sender.sendMessage("Player: " + mockPlayer);
        sender.sendMessage("CommandSender: " + mockUser.getCommandSender());
        sender.sendMessage("CommandSender is player: " + (mockUser.getCommandSender() instanceof Player));
        sender.sendMessage("Passes for player: " + (mockPlayer instanceof Player));
        sender.sendMessage("Passes for user:" + (mockUser instanceof User));
        sender.sendMessage("Player casted from sender: " + ((Player) mockUser.getCommandSender()));
        sender.sendMessage("User lookup: " + UserLoader.fromPlayer(mockPlayer));
        sender.sendMessage("User lookup by sender: " + UserLoader.fromPlayer((Player) mockUser.getCommandSender()));
        sender.sendMessage("Exists in UserLoader cache: " + UserLoader.allUsers().contains(mockUser));
        sender.sendMessage("Exists in game object registry: " + dragons.getGameObjectRegistry().getRegisteredObjects().contains(mockUser));
        sender.sendMessage("Exists in filtered game object registry: " + dragons.getGameObjectRegistry().getRegisteredObjects(GameObjectType.USER).contains(mockUser));
    } else if (label.equalsIgnoreCase("mockdelete")) {
        User target = lookupUser(sender, args[0]);
        if (target.getData().getBoolean("mock", false)) {
            dragons.getGameObjectRegistry().removeFromDatabase(target);
            dragons.getGameObjectRegistry().getRegisteredObjects().remove(target);
            UserLoader.allUsers().remove(target);
            sender.sendMessage("Deleted mock user " + target.getName() + " and removed from primary local caches");
        }
    } else if (label.equalsIgnoreCase("mocklist")) {
        Set<User> mocks = dragons.getPersistentStorageManager().getAllStorageAccess(GameObjectType.USER, new Document("mock", true)).stream().map(sa -> userLoader.loadObject(sa)).collect(Collectors.toSet());
        sender.sendMessage("USERNAME  -  UUID  -  CURRENT SERVER");
        for (User mock : mocks) {
            sender.sendMessage(mock.getName() + "  -  " + mock.getUUID() + "  -  " + mock.getServerName());
        }
    } else if (label.equalsIgnoreCase("mockserver")) {
        StorageAccess storageAccess = dragons.getPersistentStorageManager().getStorageAccess(GameObjectType.USER, new Document("username", args[0]));
        storageAccess.set("currentServer", args[1]);
    } else if (label.equalsIgnoreCase("testitemstash")) {
        user.stashItems(questLoader.getQuestByName(args[0]), Material.valueOf(args[1]));
        sender.sendMessage("Stash: " + user.getData().get("questStash", new Document()).toJson());
    } else if (label.equalsIgnoreCase("testitemunstash")) {
        user.unstashItems(questLoader.getQuestByName(args[0]), Material.valueOf(args[1]));
        sender.sendMessage("Stash: " + user.getData().get("questStash", new Document()).toJson());
    } else if (label.equalsIgnoreCase("testmobai")) {
        boolean ai = Boolean.valueOf(args[0]);
        boolean gravity = Boolean.valueOf(args[1]);
        boolean collidable = Boolean.valueOf(args[2]);
        LivingEntity entity = (LivingEntity) player.getWorld().spawnEntity(player.getLocation(), EntityType.ZOMBIE);
        entity.setAI(ai);
        entity.setGravity(gravity);
        entity.setCollidable(collidable);
    } else if (label.equalsIgnoreCase("testtakeitem")) {
        Item item = itemLoader.registerNew(args[0]);
        int quantity = Integer.valueOf(args[1]);
        user.takeItem(item, quantity, true, true, true);
    } else if (label.equalsIgnoreCase("testupdateinventory")) {
        player.updateInventory();
    } else if (label.equalsIgnoreCase("testnametag")) {
        User target = lookupUser(sender, args[0]);
        String prefix = StringUtil.colorize(args[2]);
        String suffix = StringUtil.colorize(StringUtil.concatArgs(args, 3));
        target.setPrimaryNameTag(ChatColor.valueOf(args[1]), prefix, suffix);
    } else if (label.equalsIgnoreCase("testnametag2")) {
        User target = lookupUser(sender, args[0]);
        String text = StringUtil.colorize(StringUtil.concatArgs(args, 1));
        target.setSecondaryNameTag(text);
    } else if (label.equalsIgnoreCase("testupdatenametag")) {
        user.updatePrimaryNameTag();
    } else if (label.equalsIgnoreCase("testrollingasync")) {
        rollingAsync(() -> {
            String name = Thread.currentThread().getName();
            sync(() -> {
                player.sendMessage("hey (" + name + ")");
            });
        });
    } else if (label.equalsIgnoreCase("testinternalnetworkedmsg")) {
        User to = lookupUser(sender, args[0]);
        dragons.getInternalMessageHandler().sendRawMsg(to.getServerName(), to.getUUID(), StringUtil.concatArgs(args, 1));
    } else if (StringUtil.equalsAnyIgnoreCase(label, "testplayernpc", "npctool")) {
        if (args.length == 0) {
            sender.sendMessage("/" + label + " <rot|loc|info|set <pitch> <yaw>>  (all changes are local)");
            return true;
        }
        for (Entity e : player.getNearbyEntities(30, 30, 30)) {
            NPC npc = NPCLoader.fromBukkit(e);
            if (npc == null)
                continue;
            if (npc.getEntityType() == EntityType.PLAYER) {
                PlayerNPC pnpc = npc.getPlayerNPC();
                if (args[0].equalsIgnoreCase("rot")) {
                    pnpc.refreshRotationFor(player);
                } else if (args[0].equalsIgnoreCase("loc")) {
                    pnpc.updateLocationFor(player, e.getLocation().getPitch(), e.getLocation().getYaw());
                } else if (args[0].equalsIgnoreCase("set")) {
                    pnpc.updateLocationFor(player, parseFloat(sender, args[1]), parseFloat(sender, args[2]));
                } else if (args[0].equalsIgnoreCase("info")) {
                    player.sendMessage(e.getEntityId() + ": " + StringUtil.locToString(e.getLocation()) + " [" + e.getLocation().getPitch() + ", " + e.getLocation().getYaw() + "]");
                }
            }
        }
        player.sendMessage("You: " + player.getLocation().getPitch() + ", " + player.getLocation().getYaw());
    } else if (label.equalsIgnoreCase("testrevealallinvisible")) {
        for (Entity e : player.getWorld().getEntities()) {
            if (e instanceof LivingEntity) {
                ((LivingEntity) e).setInvisible(false);
            }
        }
    } else if (label.equalsIgnoreCase("testinventoryreload")) {
        if (args.length == 0) {
            sender.sendMessage("/" + label + " <simple|full>");
        } else if (args[0].equalsIgnoreCase("simple")) {
            player.updateInventory();
        } else if (args[0].equalsIgnoreCase("full")) {
            Document inv = new Document(user.getInventoryAsDocument());
            player.getInventory().clear();
            user.loadInventory(LOGGER.newCID(), inv);
        }
    } else if (label.equalsIgnoreCase("tptoentity")) {
        if (args.length == 0) {
            sender.sendMessage("/tptoentity <entity id>");
            return true;
        }
        int id = parseInt(sender, args[0]);
        for (Entity entity : dragons.getEntities()) {
            if (entity.getEntityId() == id) {
                player.teleport(entity);
                NPC npc = NPCLoader.fromBukkit(entity);
                if (npc != null) {
                    player.sendMessage("NPC: " + npc.getNPCClass().getClassName());
                }
                return true;
            }
        }
        player.sendMessage("Not found");
    } else {
        sender.sendMessage(ChatColor.RED + "Invalid experimental command! Was it removed or registered improperly?");
    }
    return true;
}
Also used : Document(org.bson.Document) MessageHandler(mc.dragons.core.networking.MessageHandler) NPCLoader(mc.dragons.core.gameobject.npc.NPCLoader) CorrelationLogger(mc.dragons.core.logging.correlation.CorrelationLogger) Slime(org.bukkit.entity.Slime) User(mc.dragons.core.gameobject.user.User) Player(org.bukkit.entity.Player) ItemLoader(mc.dragons.core.gameobject.item.ItemLoader) Block(org.bukkit.block.Block) Location(org.bukkit.Location) World(org.bukkit.World) StorageUtil(mc.dragons.core.storage.StorageUtil) Material(org.bukkit.Material) Bukkit(org.bukkit.Bukkit) StringUtil(mc.dragons.core.util.StringUtil) CommandSender(org.bukkit.command.CommandSender) UserLoader(mc.dragons.core.gameobject.user.UserLoader) Entity(org.bukkit.entity.Entity) Set(java.util.Set) UUID(java.util.UUID) Item(mc.dragons.core.gameobject.item.Item) EntityType(org.bukkit.entity.EntityType) LivingEntity(org.bukkit.entity.LivingEntity) SystemProfileFlag(mc.dragons.core.gameobject.user.permission.SystemProfile.SystemProfileFlags.SystemProfileFlag) Collectors(java.util.stream.Collectors) ItemStack(org.bukkit.inventory.ItemStack) Base64(java.util.Base64) List(java.util.List) EulerAngle(org.bukkit.util.EulerAngle) GameObject(mc.dragons.core.gameobject.GameObject) GUI(mc.dragons.core.gui.GUI) StorageManager(mc.dragons.core.storage.StorageManager) BukkitUtil.sync(mc.dragons.core.util.BukkitUtil.sync) HologramUtil(mc.dragons.core.util.HologramUtil) Command(org.bukkit.command.Command) PersistentDataType(org.bukkit.persistence.PersistentDataType) GUIElement(mc.dragons.core.gui.GUIElement) Level(java.util.logging.Level) TextComponent(net.md_5.bungee.api.chat.TextComponent) GameObjectType(mc.dragons.core.gameobject.GameObjectType) DragonsCommandExecutor(mc.dragons.core.commands.DragonsCommandExecutor) PlayerNPC(mc.dragons.core.bridge.PlayerNPC) PathfindingUtil(mc.dragons.core.util.PathfindingUtil) BukkitRunnable(org.bukkit.scheduler.BukkitRunnable) Dragons(mc.dragons.core.Dragons) Particle(org.bukkit.Particle) StorageAccess(mc.dragons.core.storage.StorageAccess) ArmorStand(org.bukkit.entity.ArmorStand) ChatColor(org.bukkit.ChatColor) NPC(mc.dragons.core.gameobject.npc.NPC) BukkitUtil.rollingAsync(mc.dragons.core.util.BukkitUtil.rollingAsync) PlayerEventListeners(mc.dragons.core.events.PlayerEventListeners) PlayerNPC(mc.dragons.core.bridge.PlayerNPC) NPC(mc.dragons.core.gameobject.npc.NPC) Entity(org.bukkit.entity.Entity) LivingEntity(org.bukkit.entity.LivingEntity) User(mc.dragons.core.gameobject.user.User) StorageManager(mc.dragons.core.storage.StorageManager) GUIElement(mc.dragons.core.gui.GUIElement) CorrelationLogger(mc.dragons.core.logging.correlation.CorrelationLogger) Document(org.bson.Document) World(org.bukkit.World) LivingEntity(org.bukkit.entity.LivingEntity) Item(mc.dragons.core.gameobject.item.Item) ArmorStand(org.bukkit.entity.ArmorStand) GameObject(mc.dragons.core.gameobject.GameObject) GUI(mc.dragons.core.gui.GUI) UUID(java.util.UUID) StorageAccess(mc.dragons.core.storage.StorageAccess) TextComponent(net.md_5.bungee.api.chat.TextComponent) Player(org.bukkit.entity.Player) BukkitRunnable(org.bukkit.scheduler.BukkitRunnable) Slime(org.bukkit.entity.Slime) Block(org.bukkit.block.Block) Level(java.util.logging.Level) ItemStack(org.bukkit.inventory.ItemStack) EulerAngle(org.bukkit.util.EulerAngle) PlayerNPC(mc.dragons.core.bridge.PlayerNPC) Location(org.bukkit.Location)

Aggregations

Item (mc.dragons.core.gameobject.item.Item)33 ItemStack (org.bukkit.inventory.ItemStack)19 User (mc.dragons.core.gameobject.user.User)15 Player (org.bukkit.entity.Player)11 EventHandler (org.bukkit.event.EventHandler)11 NPC (mc.dragons.core.gameobject.npc.NPC)9 Document (org.bson.Document)9 UUID (java.util.UUID)6 ArrayList (java.util.ArrayList)5 Entity (org.bukkit.entity.Entity)5 List (java.util.List)4 Dragons (mc.dragons.core.Dragons)4 GameObjectType (mc.dragons.core.gameobject.GameObjectType)4 ItemClass (mc.dragons.core.gameobject.item.ItemClass)4 ChatColor (org.bukkit.ChatColor)4 Location (org.bukkit.Location)4 BukkitRunnable (org.bukkit.scheduler.BukkitRunnable)4 HashMap (java.util.HashMap)3 Map (java.util.Map)3 Floor (mc.dragons.core.gameobject.floor.Floor)3