use of mc.dragons.core.gui.GUIElement in project DragonsOnline by UniverseCraft.
the class ChannelCommand method openGUI.
private void openGUI(User user) {
boolean staff = hasPermission(user, PermissionLevel.BUILDER);
GUI gui = new GUI(5, ChatColor.WHITE + "Chat Channels");
gui.add(new GUIElement(4, Material.BOOK, ChatColor.AQUA + "Chat Channels", List.of(ChatColor.WHITE + "Channels are different streams of chat", ChatColor.WHITE + "that you can speak or listen on.", "", ChatColor.WHITE + "You can listen to multiple channels,", ChatColor.WHITE + "but can only speak on one.", "", ChatColor.WHITE + "Do " + ChatColor.GRAY + "/channel <channel> " + ChatColor.WHITE + "to manually", ChatColor.WHITE + "change channels."), 1, u -> {
}));
// Assume we have 7 or fewer channels, otherwise overflow occurs
int i = 10;
for (ChatChannel channel : ChatChannel.values()) {
if (channel == ChatChannel.STAFF && !staff)
continue;
boolean speaking = user.getSpeakingChannel() == channel;
boolean listening = user.getActiveChatChannels().contains(channel);
gui.add(new GUIElement(i, Material.OAK_SIGN, ChatColor.YELLOW + "" + ChatColor.BOLD + channel, List.of(ChatColor.GRAY + channel.getDescription(), ChatColor.GRAY + "- " + (speaking ? ChatColor.GREEN + "You are speaking on this channel" : ChatColor.RED + "You are not speaking on this channel"), ChatColor.GRAY + "- " + (listening ? ChatColor.GREEN + "You are listening to this channel" : ChatColor.RED + "You are not speaking to this channel")), 1, u -> {
}));
gui.add(new GUIElement(i + 9, speaking ? Material.EMERALD_BLOCK : Material.STONE, speaking ? ChatColor.GRAY + "You are currently speaking on this channel" : ChatColor.GREEN + "Click to speak on " + channel, ChatColor.GRAY + "You can only speak on one channel at a time", u -> {
u.setSpeakingChannel(channel);
if (!u.getActiveChatChannels().contains(channel)) {
u.addActiveChatChannel(channel);
}
openGUI(u);
}));
gui.add(new GUIElement(i + 9 * 2, listening ? Material.EMERALD_BLOCK : Material.REDSTONE_BLOCK, listening ? speaking ? ChatColor.RED + "You must listen to the channel you're speaking on" : ChatColor.RED + "Click to stop listening to " + channel : ChatColor.GREEN + "Click to listen to " + channel, ChatColor.GRAY + "You can listen to multiple channels at once", u -> {
if (speaking && listening)
return;
if (listening) {
u.removeActiveChatChannel(channel);
} else {
u.addActiveChatChannel(channel);
}
openGUI(u);
}));
i++;
}
gui.open(user);
}
use of mc.dragons.core.gui.GUIElement 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;
}
use of mc.dragons.core.gui.GUIElement in project DragonsOnline by UniverseCraft.
the class ResEvents method onInteract.
@EventHandler
public void onInteract(PlayerInteractEvent event) {
if (event.getClickedBlock() == null)
return;
if (!(event.getClickedBlock().getBlockData() instanceof Door)) {
return;
}
Player player = event.getPlayer();
User user = UserLoader.fromPlayer(player);
Door door = (Door) event.getClickedBlock().getBlockData();
if (player.getWorld().getName().equals("res_temp")) {
player.performCommand("res exit");
event.setCancelled(true);
return;
}
if (!door.isOpen()) {
user.debug("R.Click on door (opening it)");
Location realLocation = door.getHalf() == Half.TOP ? event.getClickedBlock().getRelative(BlockFace.DOWN).getLocation() : event.getClickedBlock().getLocation();
user.debug("-Door base=" + StringUtil.locToString(realLocation));
ResPoint resPoint = resPointLoader.getResPointByDoorLocation(realLocation);
if (resPoint == null)
return;
user.debug("-Res point: " + resPoint.getName());
// ((Door) realLocation.getBlock().getState().getData()).setOpen(false);
event.setCancelled(true);
List<Residence> ownedHere = resLoader.getAllResidencesOf(user, resPoint);
if (ownedHere.size() == 0) {
user.debug("-Doesn't have any residences here");
if (resPoint.getPrice() > user.getGold()) {
player.sendMessage(ChatColor.RED + "You cannot afford this residence! (Costs " + resPoint.getPrice() + " gold)");
return;
}
if (resLoader.getAllResidencesOf(user).size() >= DragonsResidences.MAX_RES_PER_USER) {
player.sendMessage(ChatColor.RED + "You have reached the maximum number of residences per user! (" + DragonsResidences.MAX_RES_PER_USER + ")");
return;
}
GUI gui = new GUI(1, "Purchase a residence here?");
gui.add(new GUIElement(1, Material.EMERALD_BLOCK, ChatColor.GREEN + "✓ " + ChatColor.DARK_GREEN + "" + ChatColor.BOLD + "YES", u -> {
player.playSound(player.getLocation(), Sound.BLOCK_WOODEN_DOOR_OPEN, 1f, 1f);
u.takeGold(resPoint.getPrice());
Residence purchased = resLoader.addResidence(user, resPoint, ResAccess.PRIVATE);
resLoader.goToResidence(user, purchased.getId(), false);
resPointLoader.updateResHologramOn(user, resPoint);
u.closeGUI(true);
}));
gui.add(new GUIElement(4, Material.PAPER, ChatColor.YELLOW + "Price: " + ChatColor.GOLD + resPoint.getPrice() + " Gold"));
gui.add(new GUIElement(7, Material.REDSTONE_BLOCK, ChatColor.RED + "✘ " + ChatColor.DARK_RED + "" + ChatColor.BOLD + "NO", u -> u.closeGUI(true)));
gui.open(user);
} else {
user.debug("-Has a residence here, going there now");
player.playSound(player.getLocation(), Sound.BLOCK_WOODEN_DOOR_OPEN, 1f, 1f);
resLoader.goToResidence(user, ownedHere.get(0).getId(), false);
}
}
}
use of mc.dragons.core.gui.GUIElement in project DragonsOnline by UniverseCraft.
the class NPCAction method execute.
/**
* Run the specified action on the specified user and NPC.
*
* @param user
* @param npc
*/
public void execute(final User user, NPC npc) {
switch(type) {
case BEGIN_QUEST:
if (quest.isLocked()) {
user.getPlayer().sendMessage(ChatColor.RED + "This quest is currently locked! Try again later.");
return;
}
GUI confirmation = new GUI(1, "Accept quest?");
confirmation.add(new GUIElement(1, Material.EMERALD_BLOCK, ChatColor.GREEN + "✓ " + ChatColor.DARK_GREEN + ChatColor.BOLD + "Accept", ChatColor.GRAY + "You will be unable to interact with\n" + ChatColor.GRAY + "other players, mobs, or NPCs during\n" + ChatColor.GRAY + "quest dialogue.", u -> {
u.updateQuestProgress(quest, quest.getSteps().get(0));
u.closeGUI(true);
}));
confirmation.add(new GUIElement(4, Material.PAPER, ChatColor.YELLOW + "Quest Information", ChatColor.GRAY + "Quest: " + ChatColor.RESET + quest.getQuestName() + "\n" + ChatColor.GRAY + "Lv Min: " + ChatColor.RESET + quest.getLevelMin()));
confirmation.add(new GUIElement(7, Material.REDSTONE_BLOCK, ChatColor.RED + "✘ " + ChatColor.DARK_RED + ChatColor.BOLD + "Not Now", ChatColor.GRAY + "You can always come back later to\n" + ChatColor.GRAY + "start the quest.", u -> u.closeGUI(true)));
confirmation.open(user);
break;
case BEGIN_DIALOGUE:
user.setDialogueBatch(null, npcClass.getName(), dialogue);
new BukkitRunnable() {
@Override
public void run() {
if (!user.nextDialogue()) {
cancel();
}
}
}.runTaskTimer(Dragons.getInstance(), 0L, 40L);
break;
case TELEPORT_NPC:
npc.getEntity().teleport(to);
break;
case PATHFIND_NPC:
boolean hasAI = Dragons.getInstance().getBridge().hasAI(npc.getEntity());
if (hasAI) {
Dragons.getInstance().getBridge().setEntityAI(npc.getEntity(), false);
}
PathfindingUtil.walkToLocation(npc.getEntity(), to, 0.15D, (e) -> {
if (hasAI) {
Dragons.getInstance().getBridge().setEntityAI(e, true);
}
});
break;
case OPEN_SHOP:
int rows = 2 + (int) Math.ceil(shopItems.size() / 7.0D);
GUI shop = new GUI(rows, shopName);
user.debug("opening shop with " + rows + " rows and name " + shopName + " with " + shopItems.size() + " items");
int slot = 10;
for (ShopItem item : shopItems) {
ItemClass itemClass = itemClassLoader.getItemClassByClassName(item.getItemClassName());
shop.add(itemClass.getAsGuiElement(slot, item.getQuantity(), item.getCostPer(), false, u -> u.buyItem(itemClass, item.getQuantity(), item.getCostPer())));
slot++;
if ((slot + 1) % 9 == 0) {
slot += 2;
}
}
shop.open(user);
break;
}
}
use of mc.dragons.core.gui.GUIElement in project DragonsOnline by UniverseCraft.
the class DragonsDev method onEnable.
public void onEnable() {
enableDebugLogging();
saveDefaultConfig();
dragons = getDragonsInstance();
buildNotifier = new DiscordNotifier(getConfig().getString("discord-notifier-webhook-url"));
buildNotifier.setEnabled(getConfig().getBoolean("discord-notifier-enabled"));
ADVICE_BROADCASTER_PERIOD_SECONDS = getConfig().getInt("staff-advice.period-seconds", 60 * 2);
BACKUP_FOLDER = getConfig().getString("backup.folder", "C:\\DragonsBackups\\");
BACKUP_PERIOD_MINUTES = getConfig().getInt("backup.period-minutes", 60);
BACKUP_RETENTION_DAYS = getConfig().getInt("backup.retention-days", 30);
MAX_STARS = getConfig().getInt("stars.max-stars", 5);
MAX_ASSIGN_STARS = getConfig().getInt("stars.max-assign-stars", 10);
Map<String, Object> shop = getConfig().getConfigurationSection("stars.staff-shop").getValues(false);
ItemClassLoader itemClassLoader = GameObjectType.ITEM_CLASS.getLoader();
ItemLoader itemLoader = GameObjectType.ITEM.getLoader();
int rows = (int) Math.ceil(2 + (double) shop.size() / 7);
int slot = 10;
int run = 0;
STAFF_SHOP = new GUI(rows, "Staff Shop");
for (Entry<String, Object> entry : shop.entrySet()) {
String className = entry.getKey();
int price = (int) entry.getValue();
ItemClass itemClass = itemClassLoader.getItemClassByClassName(className);
if (itemClass == null) {
getLogger().warning("Could not add item to staff shop: No item class \"" + className + "\" exists");
continue;
}
List<String> lore = new ArrayList<>();
lore.add(ChatColor.GRAY + "Price: " + ChatColor.GOLD + price + TaskLoader.STAR);
lore.addAll(Item.getCompleteLore(itemClass.getData(), itemClass.getLore().<String>toArray(new String[itemClass.getLore().size()]), null, false, itemClass));
GUIElement elem = new GUIElement(slot, itemClass.getMaterial(), itemClass.getDecoratedName(), lore, 1, user -> {
int stars = DevUserHook.getStars(user);
if (stars < price) {
user.getPlayer().sendMessage(ChatColor.RED + "This item costs " + price + TaskLoader.STAR + "! (Need " + (price - stars) + " more)");
} else {
user.giveItem(itemLoader.registerNew(itemClass));
dragons.getStaffAlertHandler().sendGenericMessage(PermissionLevel.TESTER, ChatColor.GOLD + user.getName() + " redeemed " + price + TaskLoader.STAR + " for a " + itemClass.getDecoratedName() + "!");
DevUserHook.addStars(user, -price);
}
});
STAFF_SHOP.add(elem);
slot++;
run++;
if (run == 7) {
run = 0;
slot += 2;
}
}
TaskLoader taskLoader = new TaskLoader(dragons);
dragons.getLightweightLoaderRegistry().register(taskLoader);
DevUserHook hook = new DevUserHook();
dragons.getUserHookRegistry().registerHook(hook);
Bukkit.getPluginManager().registerEvents(hook, this);
CommandExecutor taskCommands = new TaskCommands(this);
getCommand("task").setExecutor(taskCommands);
getCommand("tasks").setExecutor(taskCommands);
getCommand("taskinfo").setExecutor(taskCommands);
getCommand("assign").setExecutor(taskCommands);
getCommand("unassign").setExecutor(taskCommands);
getCommand("done").setExecutor(taskCommands);
getCommand("approve").setExecutor(taskCommands);
getCommand("reject").setExecutor(taskCommands);
getCommand("close").setExecutor(taskCommands);
getCommand("taskloc").setExecutor(taskCommands);
getCommand("tasknote").setExecutor(taskCommands);
getCommand("gototask").setExecutor(taskCommands);
getCommand("togglediscordnotifier").setExecutor(taskCommands);
getCommand("discordnotifyraw").setExecutor(taskCommands);
getCommand("deletetask").setExecutor(taskCommands);
getCommand("taskhelp").setExecutor(taskCommands);
getCommand("reopen").setExecutor(taskCommands);
getCommand("reloadtasks").setExecutor(taskCommands);
getCommand("stars").setExecutor(taskCommands);
getCommand("takestars").setExecutor(taskCommands);
getCommand("givestars").setExecutor(taskCommands);
getCommand("getstars").setExecutor(taskCommands);
getCommand("taskrename").setExecutor(taskCommands);
getCommand("findtasks").setExecutor(taskCommands);
getCommand("staffshop").setExecutor(new StaffShopCommand());
getCommand("backup").setExecutor(new BackupCommand(this));
getCommand("starttrial").setExecutor(new StartTrialCommand());
getCommand("tips").setExecutor(new TipsCommand());
new AdviceBroadcaster().runTaskTimer(this, 20L * ADVICE_BROADCASTER_PERIOD_SECONDS, 20L * ADVICE_BROADCASTER_PERIOD_SECONDS);
syncPeriodic(() -> {
if (Bukkit.getOnlinePlayers().size() > 0) {
backupFloors();
}
}, 20 * 60 * BACKUP_PERIOD_MINUTES, 20 * 60 * BACKUP_PERIOD_MINUTES);
}
Aggregations