下面列出了org.bukkit.ChatColor#stripColor ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static Boolean containsEnchantment(String toTest, CEnchantment ce) {
if (toTest.startsWith(ChatColor.YELLOW + "" + ChatColor.ITALIC + "\""))
toTest = lorePrefix + ChatColor.stripColor(toTest.replace("\"", ""));
String next = "";
if (toTest.startsWith(lorePrefix + ce.getOriginalName()))
next = lorePrefix + ce.getOriginalName();
if (toTest.startsWith(ce.getDisplayName()))
next = ce.getDisplayName();
if (next.isEmpty())
return false;
String nextTest = toTest.replace(next, "");
if (nextTest.startsWith(" ") || nextTest.isEmpty())
return true;
return false;
}
public static boolean hasEnchantment(ItemStack item, String ench) {
Enchantment vanilla = Enchantment.getByName(ench.toUpperCase());
if (vanilla != null) {
int lvl = (item.getEnchantmentLevel(vanilla));
return lvl > 0;
} else {
String enchantment = SettingsManager.lang.getString("enchantments." + ench.toLowerCase());
if (enchantment != null) {
String currEnch = ChatColor.stripColor(Util.toColor(enchantment));
List<String> lores = item.getItemMeta().getLore();
for (int i = 0; i < lores.size(); i++) {
String[] curr = ChatColor.stripColor(lores.get(i)).split(
" ");
if (curr.length > 0 && curr[0].equals(currEnch)) {
return true;
}
}
}
}
return false;
}
public static boolean isRentSign(Block block) {
if (!isSign(block)) {
return false;
}
final Sign sign = (Sign) block.getState();
final String header = ChatColor.stripColor(sign.getLine(0));
if (header.equalsIgnoreCase(RENT_SIGN)) {
return true;
}
return false;
}
public static boolean isSellSign(Sign sign) {
if (sign == null) {
return false;
}
final String header = ChatColor.stripColor(sign.getLine(0));
if (header.equalsIgnoreCase(SELL_SIGN)) {
return true;
}
return false;
}
public static boolean isRentSign(Sign sign) {
if (sign == null) {
return false;
}
final String header = ChatColor.stripColor(sign.getLine(0));
if (header.equalsIgnoreCase(RENT_SIGN)) {
return true;
}
return false;
}
@EventHandler(priority = EventPriority.NORMAL)
public void onInventoryClick(InventoryClickEvent e) {
final Player player = (Player) e.getWhoClicked();
final GameMap gameMap = MatchManager.get().getSpectatorMap(player);
if (gameMap == null) {
return;
}
int slot = e.getSlot();
if (slot == 8) {
player.closeInventory();
gameMap.getSpectators().remove(player.getUniqueId());
MatchManager.get().removeSpectator(player);
} else if (slot >= 9 && slot <= 35) {
player.closeInventory();
ItemStack item = e.getCurrentItem();
if (item != null && !item.getType().equals(Material.AIR)) {
String name = ChatColor.stripColor(item.getItemMeta().getDisplayName());
Player toSpec = SkyWarsReloaded.get().getServer().getPlayer(name);
if (toSpec != null) {
if (!gameMap.mapContainsDead(toSpec.getUniqueId()) && player != null) {
player.teleport(toSpec.getLocation(), TeleportCause.END_PORTAL);
}
}
}
}
}
public static boolean allow(String input, IPet pet) {
YAMLConfig config = ConfigOptions.instance.getConfig();
String nameToCheck = ChatColor.stripColor(input);
ConfigurationSection cs = config.getConfigurationSection("petNames");
if (cs != null) {
for (String key : cs.getKeys(false)) {
if (key.equalsIgnoreCase(nameToCheck)) {
String value = config.getString("petNames." + key);
return pet.getOwner().hasPermission("echopet.pet.name.override") || !(value.equalsIgnoreCase("deny") || value.equalsIgnoreCase("false"));
}
}
}
if (config.getBoolean("petNamesRegexMatching")) {
List<Map<String, String>> csRegex = (List<Map<String, String>>) config.get("petNamesRegex");
if (!csRegex.isEmpty()) {
for (Map<String, String> regexMap : csRegex) {
for (Map.Entry<String, String> entry : regexMap.entrySet()) {
if (nameToCheck.matches(entry.getKey())) {
return pet.getOwner().hasPermission("echopet.pet.name.override")
|| !(entry.getValue().equalsIgnoreCase("deny")
|| entry.getValue().equalsIgnoreCase("false"));
}
}
}
}
}
return true;
}
public static boolean allow(String input, IPet pet) {
YAMLConfig config = ConfigOptions.instance.getConfig();
String nameToCheck = ChatColor.stripColor(input);
ConfigurationSection cs = config.getConfigurationSection("petNames");
if (cs != null) {
for (String key : cs.getKeys(false)) {
if (key.equalsIgnoreCase(nameToCheck)) {
String value = config.getString("petNames." + key);
return pet.getOwner().hasPermission("echopet.pet.name.override") || !(value.equalsIgnoreCase("deny") || value.equalsIgnoreCase("false"));
}
}
}
if (config.getBoolean("petNamesRegexMatching")) {
List<Map<String, String>> csRegex = (List<Map<String, String>>) config.get("petNamesRegex");
if (!csRegex.isEmpty()) {
for (Map<String, String> regexMap : csRegex) {
for (Map.Entry<String, String> entry : regexMap.entrySet()) {
if (nameToCheck.matches(entry.getKey())) {
return pet.getOwner().hasPermission("echopet.pet.name.override")
|| !(entry.getValue().equalsIgnoreCase("deny")
|| entry.getValue().equalsIgnoreCase("false"));
}
}
}
}
}
return true;
}
/**
* Checks if an item is a valid plugin generated item.
*
* @param item
* @param displayName
* @return
*/
public static boolean isPluginItem(ItemStack item, String displayName) {
if (item != null && item.hasItemMeta() && item.getItemMeta()
.hasDisplayName()) {
String itemName = item.getItemMeta().getDisplayName();
String stripped = ChatColor.stripColor(itemName);
if (!itemName.equals(stripped) && stripped.equals(ChatColor
.stripColor(displayName))) {
return true;
}
}
return false;
}
private String formatTags(String format, UCChannel ch, MessageReceivedEvent e, String sender, String message) {
format = format.replace("{ch-color}", ch.getColor())
.replace("{ch-alias}", ch.getAlias())
.replace("{ch-name}", ch.getName());
if (e != null) {
sender = ChatColor.stripColor(ChatColor.translateAlternateColorCodes('&', e.getMember().getEffectiveName()));
format = format.replace("{sender}", sender)
.replace("{dd-channel}", e.getChannel().getName())
.replace("{message}", e.getMessage().getContentRaw());
if (!e.getMember().getRoles().isEmpty()) {
Role role = e.getMember().getRoles().get(0);
if (role.getColor() != null) {
format = format.replace("{dd-rolecolor}", fromRGB(
role.getColor().getRed(),
role.getColor().getGreen(),
role.getColor().getBlue()).toString());
}
format = format.replace("{dd-rolename}", role.getName());
}
if (e.getMember().getNickname() != null) {
format = format.replace("{nickname}", ChatColor.stripColor(ChatColor.translateAlternateColorCodes('&', e.getMember().getNickname())));
} else {
format = format.replace("{nickname}", sender);
}
}
//if not filtered
format = format
.replace("{sender}", sender)
.replace("{message}", message);
format = format.replaceAll("\\{.*\\}", "");
return ChatColor.translateAlternateColorCodes('&', format);
}
public static void translateItem(Civilian civilian, ItemStack itemStack) {
Player player = Bukkit.getPlayer(civilian.getUuid());
String itemDisplayName = itemStack.getItemMeta().getLore().get(1);
String nameString = ChatColor.stripColor(itemDisplayName
.replace(ChatColor.stripColor(ConfigManager.getInstance().getCivsItemPrefix()), "").toLowerCase());
String displayName = LocaleManager.getInstance().getTranslationWithPlaceholders(player,
"item-" + nameString + LocaleConstants.NAME_SUFFIX);
List<String> lore = new ArrayList<>();
lore.add(ChatColor.BLACK + nameString);
lore.addAll(Util.textWrap(civilian,
LocaleManager.getInstance().getTranslationWithPlaceholders(player,
"item-" + nameString + LocaleConstants.DESC_SUFFIX)));
itemStack.getItemMeta().setDisplayName(displayName);
itemStack.getItemMeta().setLore(lore);
}
@SuppressWarnings("deprecation")
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled=true)
public void onInventoryClick(InventoryClickEvent event) {
Inventory inventory = event.getInventory(); // The inventory that was clicked in
if (inventory.getName() == null) {
return;
}
// The player that clicked the item
final Player player = (Player) event.getWhoClicked();
String title = inventory.getTitle();
if (!inventory.getTitle().startsWith(plugin.myLocale().warpsTitle + " #")) {
return;
}
event.setCancelled(true);
if (event.getSlotType().equals(SlotType.OUTSIDE)) {
player.closeInventory();
return;
}
if (event.getClick().equals(ClickType.SHIFT_RIGHT)) {
player.closeInventory();
player.updateInventory();
return;
}
ItemStack clicked = event.getCurrentItem(); // The item that was clicked
if (DEBUG)
plugin.getLogger().info("DEBUG: inventory size = " + inventory.getSize());
if (DEBUG)
plugin.getLogger().info("DEBUG: clicked = " + clicked);
if (DEBUG)
plugin.getLogger().info("DEBUG: rawslot = " + event.getRawSlot());
if (event.getRawSlot() >= event.getInventory().getSize() || clicked.getType() == Material.AIR) {
return;
}
int panelNumber = 0;
try {
panelNumber = Integer.valueOf(title.substring(title.indexOf('#')+ 1));
} catch (Exception e) {
panelNumber = 0;
}
if (clicked.getItemMeta().hasDisplayName()) {
String command = ChatColor.stripColor(clicked.getItemMeta().getDisplayName());
if (DEBUG)
plugin.getLogger().info("DEBUG: command = " + command);
if (command != null) {
if (command.equalsIgnoreCase(ChatColor.stripColor(plugin.myLocale().warpsNext))) {
player.closeInventory();
Util.runCommand(player, Settings.ISLANDCOMMAND + " warps " + (panelNumber+1));
} else if (command.equalsIgnoreCase(ChatColor.stripColor(plugin.myLocale().warpsPrevious))) {
player.closeInventory();
Util.runCommand(player, Settings.ISLANDCOMMAND + " warps " + (panelNumber-1));
} else {
player.closeInventory();
Util.sendMessage(player, ChatColor.GREEN + plugin.myLocale(player.getUniqueId()).warpswarpToPlayersSign.replace("<player>", command));
Util.runCommand(player, Settings.ISLANDCOMMAND + " warp " + command);
}
}
}
}
/**
* This sets off a verbose message.
*
* @param s the message that will be sent
* @param force_console whether the verbose message should appear in the console even when verbose for console is deactivated.
* @param error whether the message should be marked as an error
*/
public void sendVerboseMessage(final String s, final boolean force_console, final boolean error)
{
// Remove color codes
final String logMessage = ChatColor.stripColor(s);
if (writeToFile) {
try {
// Get the logfile that is in use currently or create a new one if needed.
final LocalDateTime now = LocalDateTime.now();
// Doesn't need to check for logFile == null as the currentDayOfYear will be -1 in the beginning.
if (currentDayOfYear != now.getDayOfYear() || !logFile.exists()) {
currentDayOfYear = now.getDayOfYear();
logFile = FileUtil.createFile(new File(AACAdditionPro.getInstance().getDataFolder().getPath() + "/logs/" + now.format(DateTimeFormatter.ISO_LOCAL_DATE) + ".log"));
}
// Reserve the required builder size.
// Time length is always 12, together with 2 brackets and one space this will result in 15.
final StringBuilder verboseMessage = new StringBuilder(15 + logMessage.length());
// Add the beginning of the PREFIX
verboseMessage.append('[');
// Get the current time
verboseMessage.append(now.format(DateTimeFormatter.ISO_LOCAL_TIME));
// Add a 0 if it is too short
// Technically only 12, but we already appended the "[", thus one more.
while (verboseMessage.length() < 13) {
verboseMessage.append('0');
}
// Add the rest of the PREFIX and the message
verboseMessage.append("] ");
verboseMessage.append(logMessage);
verboseMessage.append('\n');
// Log the message
Files.write(logFile.toPath(), verboseMessage.toString().getBytes(), StandardOpenOption.APPEND);
} catch (final IOException e) {
AACAdditionPro.getInstance().getLogger().log(Level.SEVERE, "Something went wrong while trying to write to the log file.", e);
}
}
if (writeToConsole || force_console) {
AACAdditionPro.getInstance().getLogger().log(error ?
Level.SEVERE :
Level.INFO, logMessage);
}
// Prevent errors on disable as of scheduling
if (allowedToRegisterTasks && writeToPlayers) {
Bukkit.getScheduler().runTask(AACAdditionPro.getInstance(), () -> {
for (User user : UserManager.getVerboseUsers()) {
user.getPlayer().sendMessage(PRE_STRING + s);
}
});
}
}
@SuppressWarnings("deprecation")
public boolean addPlayer(Player player) {
BedwarsPlayerJoinTeamEvent playerJoinTeamEvent = new BedwarsPlayerJoinTeamEvent(this, player);
BedwarsRel.getInstance().getServer().getPluginManager().callEvent(playerJoinTeamEvent);
if (playerJoinTeamEvent.isCancelled()) {
return false;
}
if (BedwarsRel.getInstance().isSpigot()) {
if (this.getScoreboardTeam().getEntries().size() >= this.getMaxPlayers()) {
return false;
}
} else {
if (this.getScoreboardTeam().getPlayers().size() >= this.getMaxPlayers()) {
return false;
}
}
String displayName = player.getDisplayName();
String playerListName = player.getPlayerListName();
if (BedwarsRel.getInstance().getBooleanConfig("overwrite-names", false)) {
displayName = this.getChatColor() + ChatColor.stripColor(player.getName());
playerListName = this.getChatColor() + ChatColor.stripColor(player.getName());
}
if (BedwarsRel.getInstance().getBooleanConfig("teamname-on-tab", true)) {
playerListName = this.getChatColor() + this.getName() + ChatColor.WHITE + " | "
+ this.getChatColor() + ChatColor.stripColor(player.getDisplayName());
}
BedwarsPlayerSetNameEvent playerSetNameEvent =
new BedwarsPlayerSetNameEvent(this, displayName, playerListName, player);
BedwarsRel.getInstance().getServer().getPluginManager().callEvent(playerSetNameEvent);
if (!playerSetNameEvent.isCancelled()) {
player.setDisplayName(playerSetNameEvent.getDisplayName());
player.setPlayerListName(playerSetNameEvent.getPlayerListName());
}
if (BedwarsRel.getInstance().isSpigot()) {
this.getScoreboardTeam().addEntry(player.getName());
} else {
this.getScoreboardTeam().addPlayer(player);
}
this.equipPlayerWithLeather(player);
return true;
}
@EventHandler
public void onPlayerInteract(PlayerInteractEvent event) {
Player player = event.getPlayer();
/* Check if a sign was interacted with */
if (event.getAction() == Action.RIGHT_CLICK_BLOCK) {
if (event.getClickedBlock().getState() instanceof Sign) {
Sign sign = (Sign) event.getClickedBlock().getState();
GameArena gameArena = plugin.getGameArena();
for (Door door : gameArena.getDoors()) {
if (door.matches(sign)) {
if (door.isNukeroom()) {
if (gameArena.getGameState() != GameState.NUKEROOM) {
door.activate(player, sign, plugin);
gameArena.setGameState(GameState.NUKEROOM);
Messages.NUKEROOM_ACTIVATED.broadcast(player.getName());
NukeRoomTask nukeRoomTask = new NukeRoomTask(gameArena, gameArena.getNukeRoom(), plugin);
nukeRoomTask.runTaskTimer(plugin, 0, 20);
gameArena.setNukeRoomTask(nukeRoomTask);
}
} else {
door.activate(player, sign, plugin);
}
break;
}
}
}
}
/* Check for kit/selector interaction */
ItemStack item = event.getItem();
if (item != null && item.hasItemMeta() && item.getItemMeta().hasDisplayName()) {
String stackName = ChatColor.stripColor(item.getItemMeta().getDisplayName());
switch (stackName) {
case "Vote":
plugin.getMenuManager().getMenu("vote").show(player);
break;
case "Human Kits":
plugin.getMenuManager().getMenu("hkits").show(player);
break;
case "Zombie Kits":
plugin.getMenuManager().getMenu("zkits").show(player);
break;
default:
/* We know iteration is O(N), however the N in this case is very small */
for (KitType kitType : KitType.values()) {
if (kitType.getName().equals(stackName)) {
/* Activates the kit callback */
kitType.getKitAction().interact(event, event.getPlayer(), item);
break;
}
}
}
}
}
public String getDisplayNameStripped() {
return ChatColor.stripColor(this.displayItem.getName());
}
public void clean() {
PlayerInventory inv = this.player.getInventory();
inv.setArmorContents(new ItemStack[4]);
inv.setContents(new ItemStack[]{});
this.player.setAllowFlight(false);
this.player.setFlying(false);
this.player.setExp(0.0F);
this.player.setLevel(0);
this.player.setSneaking(false);
this.player.setSprinting(false);
this.player.setFoodLevel(20);
this.player.setSaturation(10);
this.player.setExhaustion(0);
this.player.setMaxHealth(20.0D);
this.player.setHealth(20.0D);
this.player.setFireTicks(0);
boolean teamnameOnTab = BedwarsRel.getInstance().getBooleanConfig("teamname-on-tab", true);
boolean overwriteNames = BedwarsRel.getInstance().getBooleanConfig("overwrite-names", false);
String displayName = this.player.getDisplayName();
String playerListName = this.player.getPlayerListName();
if (overwriteNames || teamnameOnTab) {
Game game = BedwarsRel.getInstance().getGameManager().getGameOfPlayer(this.player);
if (game != null) {
game.setPlayerGameMode(player);
Team team = game.getPlayerTeam(this.player);
if (overwriteNames) {
if (team != null) {
displayName = team.getChatColor() + ChatColor.stripColor(this.player.getName());
} else {
displayName = ChatColor.stripColor(this.player.getName());
}
}
if (teamnameOnTab) {
if (team != null) {
playerListName = team.getChatColor() + team.getName() + ChatColor.WHITE + " | "
+ team.getChatColor() + ChatColor.stripColor(this.player.getDisplayName());
} else {
playerListName = ChatColor.stripColor(this.player.getDisplayName());
}
}
BedwarsPlayerSetNameEvent playerSetNameEvent =
new BedwarsPlayerSetNameEvent(team, displayName, playerListName, player);
BedwarsRel.getInstance().getServer().getPluginManager().callEvent(playerSetNameEvent);
if (!playerSetNameEvent.isCancelled()) {
this.player.setDisplayName(playerSetNameEvent.getDisplayName());
this.player.setPlayerListName(playerSetNameEvent.getPlayerListName());
}
}
}
if (this.player.isInsideVehicle()) {
this.player.leaveVehicle();
}
for (PotionEffect e : this.player.getActivePotionEffects()) {
this.player.removePotionEffect(e.getType());
}
this.player.updateInventory();
}
public static String processItemName(String input) {
input = ChatColor.stripColor(input);
return input.replace(ChatColor.stripColor(ConfigManager.getInstance().getCivsItemPrefix()), "").toLowerCase();
}
/**
* Removes colors from a string
*
* @param msg the message
* @return new message
*/
public static String removeColors(String msg) {
return ChatColor.stripColor(fixColors(msg));
}
/**
* Show a GUI that shows all statistics. Each statistic is shown by an item and is able to be clicked by the player.
*
* @param inventoryViewer Player that the GUI should be shown to.
* @param targetUUID UUID of the player we should show the statistics for. If null, the uuid of the
* player parameter will be used.
*/
public void showStatisticsOverviewInventory(Player inventoryViewer, UUID targetUUID, String targetPlayerName) {
PaginatedGUI menu = new PaginatedGUI(this.inventoryTitle + targetPlayerName);
PlayerInfo data = plugin.getDataManager().getPlayerInfo(targetUUID);
if (data == null) {
data = plugin.getDataManager().loadPlayerData(targetUUID);
}
int count = 0;
List<PlayerStat> statistics = data.getStatistics();
// Sort so we always have the same order.
statistics.sort(Comparator.comparing(Enum::toString));
for (PlayerStat statType : statistics) {
// Skip Players statistic
if (statType == PlayerStat.PLAYERS) {
continue;
}
List<Query> storedRows = data.getRows(statType);
boolean hasStoredInfo = storedRows != null && !storedRows.isEmpty();
// Only show statistics that have data.
if (!hasStoredInfo) continue;
// Get icon of this stat type
Material iconMaterial = plugin.getStatisticDescriptionConfig().getIconMaterial(statType);
// Find display name of this item.
String displayName = plugin.getStatisticDescriptionConfig().getHumanFriendlyTitle(statType);
// Create a list of messages shown when hovering over the item
List<String> messages = new ArrayList<>();
// Create temp playerinfo object to obtain description
PlayerInfo tempInfo = new PlayerInfo(targetUUID);
tempInfo.setData(statType, storedRows);
String totalDescription = ChatColor.stripColor(DescriptionMatcher.getTotalDescription(tempInfo,
statType));
if (totalDescription != null) {
messages.add(ChatColor.YELLOW + totalDescription);
}
if (statType != PlayerStat.JOINS && statType != PlayerStat.VOTES) {
messages.add("");
messages.add(ChatColor.RED + "Click me for more info!");
}
// Create an itemstack to show in the inventory
GUIButton button = new GUIButton(
ItemBuilder.start(iconMaterial).name(displayName).lore(messages).build()
);
// Add a listener to each button.
button.setListener(event -> {
// When a button has been pressed, open the inventory that shows a specific statistic.
event.setCancelled(true);
event.getWhoClicked().closeInventory();
this.showSpecificStatisticInventory(inventoryViewer, targetUUID, targetPlayerName, statType);
});
int position = 1 + 2 * (count % 4) + 9 * (count / 4);
menu.setButton(position, button);
count++;
}
this.showInventory(inventoryViewer, menu.getInventory());
}