Added some languages and a configurable cooldown

This commit is contained in:
2025-08-31 10:51:25 +02:00
parent 4f05bcd479
commit 8252b23797
12 changed files with 450 additions and 22 deletions

View File

@@ -11,6 +11,9 @@ import org.bukkit.plugin.java.JavaPlugin;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
@@ -20,17 +23,25 @@ import java.util.logging.Level;
public class InfiniteHomes extends JavaPlugin {
private Map<UUID, Map<String, Location>> homes;
private Map<UUID, Long> cooldowns;
private FileConfiguration homesConfig;
private File homesFile;
private Map<String, FileConfiguration> translations;
private File translationsDir;
@Override
public void onEnable() {
homes = new HashMap<>();
cooldowns = new HashMap<>();
translations = new HashMap<>();
setupHomesConfig();
loadHomesFromConfig();
setupTranslations();
// Standardkonfiguration erstellen, falls nicht vorhanden
getConfig().addDefault("max-homes", -1);
getConfig().addDefault("home-cooldown", -1);
getConfig().options().copyDefaults(true);
saveConfig();
@@ -61,6 +72,87 @@ public class InfiniteHomes extends JavaPlugin {
homesConfig = YamlConfiguration.loadConfiguration(homesFile);
}
private void setupTranslations() {
translationsDir = new File(getDataFolder(), "translations");
if (!translationsDir.exists()) {
translationsDir.mkdirs();
}
// Standard-Übersetzung (Englisch) aus Ressourcen laden
saveResource("translations/texts_en.yml", false);
// Verfügbare Übersetzungen laden
loadTranslations();
}
private void loadTranslations() {
translations.clear();
File[] translationFiles = translationsDir.listFiles((dir, name) ->
name.startsWith("texts_") && name.endsWith(".yml"));
if (translationFiles != null) {
for (File file : translationFiles) {
try {
String locale = file.getName().replace("texts_", "").replace(".yml", "");
FileConfiguration config = YamlConfiguration.loadConfiguration(file);
translations.put(locale, config);
getLogger().info("Loaded translation: " + locale);
} catch (Exception e) {
getLogger().log(Level.WARNING, "Error loading translation file: " + file.getName(), e);
}
}
}
// Fallback: Englische Übersetzung aus Ressourcen laden
if (!translations.containsKey("en")) {
try {
InputStream stream = getResource("translations/texts_en.yml");
if (stream != null) {
FileConfiguration config = YamlConfiguration.loadConfiguration(
new InputStreamReader(stream, StandardCharsets.UTF_8));
translations.put("en", config);
}
} catch (Exception e) {
getLogger().log(Level.WARNING, "Error loading default English translation", e);
}
}
}
private String getMessage(Player player, String key) {
// Sprache des Clients ermitteln
String clientLanguage = player.getLocale().toLowerCase();
// Sprache auf Standardformat normalisieren (z.B. "de_de" -> "de")
String languageCode = clientLanguage.split("_")[0];
// Passende Übersetzung finden
FileConfiguration translation = translations.get(languageCode);
if (translation == null) {
// Fallback: Englisch
translation = translations.get("en");
if (translation == null) {
return "Translation not found for key: " + key;
}
}
// Nachricht aus der Übersetzung holen
String message = translation.getString(key);
if (message == null || message.isEmpty()) {
// Fallback: Englisch
FileConfiguration enTranslation = translations.get("en");
if (enTranslation != null) {
message = enTranslation.getString(key);
}
if (message == null || message.isEmpty()) {
return "Message not found: " + key;
}
}
return message;
}
private void loadHomesFromConfig() {
try {
for (String playerUuidString : homesConfig.getKeys(false)) {
@@ -114,7 +206,7 @@ public class InfiniteHomes extends JavaPlugin {
if (cmd.getName().equalsIgnoreCase("sethome")) {
if (args.length != 1) {
player.sendMessage("Usage: /sethome <name>");
player.sendMessage(getMessage(player, "usage.sethome"));
return true;
}
@@ -123,7 +215,7 @@ public class InfiniteHomes extends JavaPlugin {
if (maxHomes != -1) {
int currentHomes = homes.containsKey(playerUuid) ? homes.get(playerUuid).size() : 0;
if (currentHomes >= maxHomes) {
player.sendMessage("§cYou have reached the maximum number of homes (" + maxHomes + ").");
player.sendMessage(getMessage(player, "homes.limit.reached").replace("{max}", String.valueOf(maxHomes)));
return true;
}
}
@@ -135,13 +227,13 @@ public class InfiniteHomes extends JavaPlugin {
homes.get(playerUuid).put(homeName, player.getLocation());
saveHomesToConfig();
player.sendMessage("§aHome '" + homeName + "' set!");
player.sendMessage(getMessage(player, "home.set").replace("{home}", homeName));
return true;
}
if (cmd.getName().equalsIgnoreCase("delhome")) {
if (args.length != 1) {
player.sendMessage("Usage: /delhome <name>");
player.sendMessage(getMessage(player, "usage.delhome"));
return true;
}
@@ -149,25 +241,43 @@ public class InfiniteHomes extends JavaPlugin {
if (homes.containsKey(playerUuid) && homes.get(playerUuid).containsKey(homeName)) {
homes.get(playerUuid).remove(homeName);
saveHomesToConfig();
player.sendMessage("§aHome '" + homeName + "' deleted!");
player.sendMessage(getMessage(player, "home.deleted").replace("{home}", homeName));
} else {
player.sendMessage("§cHome '" + homeName + "' does not exist.");
player.sendMessage(getMessage(player, "home.not_exist").replace("{home}", homeName));
}
return true;
}
if (cmd.getName().equalsIgnoreCase("home")) {
if (args.length != 1) {
player.sendMessage("Usage: /home <name>");
player.sendMessage(getMessage(player, "usage.home"));
return true;
}
// Check cooldown
int cooldown = getConfig().getInt("home-cooldown", -1);
if (cooldown > 0) {
long currentTime = System.currentTimeMillis();
if (cooldowns.containsKey(playerUuid)) {
long lastUsed = cooldowns.get(playerUuid);
long timeLeft = ((lastUsed / 1000) + cooldown) - (currentTime / 1000);
if (timeLeft > 0) {
player.sendMessage(getMessage(player, "home.cooldown").replace("{time}", String.valueOf(timeLeft)));
return true;
}
}
// Set cooldown
cooldowns.put(playerUuid, currentTime);
}
String homeName = args[0].toLowerCase();
if (homes.containsKey(playerUuid) && homes.get(playerUuid).containsKey(homeName)) {
player.teleport(homes.get(playerUuid).get(homeName));
player.sendMessage("§aTeleported to home '" + homeName + "'!");
player.sendMessage(getMessage(player, "home.teleport").replace("{home}", homeName));
} else {
player.sendMessage("§cHome '" + homeName + "' does not exist.");
player.sendMessage(getMessage(player, "home.not_exist").replace("{home}", homeName));
}
return true;
}
@@ -175,7 +285,7 @@ public class InfiniteHomes extends JavaPlugin {
if (cmd.getName().equalsIgnoreCase("homes")) {
// List all homes of the player
if (!homes.containsKey(playerUuid) || homes.get(playerUuid).isEmpty()) {
player.sendMessage("§cYou don't have any homes set.");
player.sendMessage(getMessage(player, "homes.none"));
return true;
}
@@ -183,30 +293,32 @@ public class InfiniteHomes extends JavaPlugin {
int maxHomes = getConfig().getInt("max-homes", -1);
int currentHomes = homeNames.size();
String limitText = (maxHomes == -1) ? "unlimited" : String.valueOf(maxHomes);
player.sendMessage("§aYour homes (§e" + currentHomes + "§a/§e" + limitText + "§a):");
String limitText = (maxHomes == -1) ? getMessage(player, "homes.unlimited") : String.valueOf(maxHomes);
player.sendMessage(getMessage(player, "homes.list.header")
.replace("{current}", String.valueOf(currentHomes))
.replace("{max}", limitText));
// List all home names
StringBuilder homesList = new StringBuilder();
for (String home : homeNames) {
if (homesList.length() > 0) {
homesList.append("§a, ");
homesList.append(", ");
}
homesList.append("§e").append(home);
homesList.append(home);
}
player.sendMessage(homesList.toString());
player.sendMessage(getMessage(player, "homes.list.items").replace("{homes}", homesList.toString()));
return true;
}
if (cmd.getName().equalsIgnoreCase("homecount")) {
if (!player.isOp()) {
player.sendMessage("§cYou do not have permission to use this command.");
player.sendMessage(getMessage(player, "no_permission"));
return true;
}
if (args.length != 1) {
player.sendMessage("Usage: /homecount <number>");
player.sendMessage(getMessage(player, "usage.homecount"));
return true;
}
@@ -214,9 +326,41 @@ public class InfiniteHomes extends JavaPlugin {
int newMax = Integer.parseInt(args[0]);
getConfig().set("max-homes", newMax);
saveConfig();
player.sendMessage("§aGlobal home limit set to " + newMax + ".");
player.sendMessage(getMessage(player, "homes.limit.set").replace("{max}", String.valueOf(newMax)));
} catch (NumberFormatException e) {
player.sendMessage("§cPlease provide a valid number.");
player.sendMessage(getMessage(player, "invalid_number"));
}
return true;
}
if (cmd.getName().equalsIgnoreCase("homecooldown")) {
if (!player.isOp()) {
player.sendMessage(getMessage(player, "no_permission"));
return true;
}
if (args.length != 1) {
player.sendMessage(getMessage(player, "usage.homecooldown"));
return true;
}
try {
int cooldown = Integer.parseInt(args[0]);
if (cooldown < -1 || cooldown > 60) {
player.sendMessage(getMessage(player, "cooldown.range"));
return true;
}
getConfig().set("home-cooldown", cooldown);
saveConfig();
if (cooldown == -1) {
player.sendMessage(getMessage(player, "cooldown.disabled"));
} else {
player.sendMessage(getMessage(player, "cooldown.set").replace("{time}", String.valueOf(cooldown)));
}
} catch (NumberFormatException e) {
player.sendMessage(getMessage(player, "invalid_number"));
}
return true;
}

View File

@@ -1,2 +1,5 @@
# Default home limit (-1 = unlimited)
max-homes: -1
# Home-Limit Configuration
max-homes: -1
# Home-Cooldown in seconds (-1 um to disable)
home-cooldown: -1

View File

@@ -18,4 +18,7 @@ commands:
usage: /homes
homecount:
description: Set the global home limit (OP only).
usage: /homecount <number>
usage: /homecount <number>
homecooldown:
description: Set the global home cooldown (OP only).
usage: /homecooldown <seconds>

View File

@@ -0,0 +1,34 @@
# InfiniteHomes - Translation File
# You can create translations for different languages in the translations folder
# Name the files texts_[lang].yml (e.g., texts_de.yml for German)
# General messages
no_permission: "§cYou don't have permission to use this command."
invalid_number: "§cPlease provide a valid number."
cooldown.range: "§cCooldown must be between -1 and 60 seconds."
# Command usage
usage.sethome: "§cUsage: /sethome <name>"
usage.delhome: "§cUsage: /delhome <name>"
usage.home: "§cUsage: /home <name>"
usage.homecount: "§cUsage: /homecount <number>"
usage.homecooldown: "§cUsage: /homecooldown <seconds>"
# Home messages
home.set: "§aHome '{home}' set!"
home.deleted: "§aHome '{home}' deleted!"
home.not_exist: "§cHome '{home}' does not exist."
home.teleport: "§aTeleported to home '{home}'!"
home.cooldown: "§cYou must wait {time} seconds before using /home again."
# Homes list messages
homes.none: "§cYou don't have any homes set."
homes.unlimited: "unlimited"
homes.list.header: "§aYour homes (§e{current}§a/§e{max}§a):"
homes.list.items: "§e{homes}"
homes.limit.reached: "§cYou have reached the maximum number of homes ({max})."
homes.limit.set: "§aGlobal home limit set to {max}."
# Cooldown messages
cooldown.set: "§aGlobal home cooldown set to {time} seconds."
cooldown.disabled: "§aHome cooldown disabled."

View File

@@ -0,0 +1,32 @@
# InfiniteHomes - Deutsche Übersetzung
# Allgemeine Nachrichten
no_permission: "§cDu hast keine Berechtigung, diesen Befehl zu verwenden."
invalid_number: "§cBitte gib eine gültige Zahl ein."
cooldown.range: "§cCooldown muss zwischen -1 und 60 Sekunden liegen."
# Befehlsverwendung
usage.sethome: "§cVerwendung: /sethome <Name>"
usage.delhome: "§cVerwendung: /delhome <Name>"
usage.home: "§cVerwendung: /home <Name>"
usage.homecount: "§cVerwendung: /homecount <Zahl>"
usage.homecooldown: "§cVerwendung: /homecooldown <Sekunden>"
# Home-Nachrichten
home.set: "§aHome '{home}' gesetzt!"
home.deleted: "§aHome '{home}' gelöscht!"
home.not_exist: "§cHome '{home}' existiert nicht."
home.teleport: "§aZu Home '{home}' teleportiert!"
home.cooldown: "§cDu musst {time} Sekunden warten, bevor du /home wieder verwenden kannst."
# Home-Liste Nachrichten
homes.none: "§cDu hast keine Homes gesetzt."
homes.unlimited: "unbegrenzt"
homes.list.header: "§aDeine Homes (§e{current}§a/§e{max}§a):"
homes.list.items: "§e{homes}"
homes.limit.reached: "§cDu hast die maximale Anzahl an Homes ({max}) erreicht."
homes.limit.set: "§aGlobales Home-Limit auf {max} gesetzt."
# Cooldown-Nachrichten
cooldown.set: "§aGlobaler Home-Cooldown auf {time} Sekunden gesetzt."
cooldown.disabled: "§aHome-Cooldown deaktiviert."

View File

@@ -0,0 +1,32 @@
# InfiniteHomes - English Translation
# General messages
no_permission: "§cYou don't have permission to use this command."
invalid_number: "§cPlease provide a valid number."
cooldown.range: "§cCooldown must be between -1 and 60 seconds."
# Command usage
usage.sethome: "§cUsage: /sethome <name>"
usage.delhome: "§cUsage: /delhome <name>"
usage.home: "§cUsage: /home <name>"
usage.homecount: "§cUsage: /homecount <number>"
usage.homecooldown: "§cUsage: /homecooldown <seconds>"
# Home messages
home.set: "§aHome '{home}' set!"
home.deleted: "§aHome '{home}' deleted!"
home.not_exist: "§cHome '{home}' does not exist."
home.teleport: "§aTeleported to home '{home}'!"
home.cooldown: "§cYou must wait {time} seconds before using /home again."
# Homes list messages
homes.none: "§cYou don't have any homes set."
homes.unlimited: "unlimited"
homes.list.header: "§aYour homes (§e{current}§a/§e{max}§a):"
homes.list.items: "§e{homes}"
homes.limit.reached: "§cYou have reached the maximum number of homes ({max})."
homes.limit.set: "§aGlobal home limit set to {max}."
# Cooldown messages
cooldown.set: "§aGlobal home cooldown set to {time} seconds."
cooldown.disabled: "§aHome cooldown disabled."

View File

@@ -0,0 +1,30 @@
# Mensajes generales
no_permission: "§cNo tienes permiso para usar este comando."
invalid_number: "§cPor favor, proporciona un número válido."
cooldown.range: "§cEl tiempo de espera debe estar entre -1 y 60 segundos."
# Uso de comandos
usage.sethome: "§cUso: /sethome <nombre>"
usage.delhome: "§cUso: /delhome <nombre>"
usage.home: "§cUso: /home <nombre>"
usage.homecount: "§cUso: /homecount <número>"
usage.homecooldown: "§cUso: /homecooldown <segundos>"
# Mensajes de home
home.set: "§aHome '{home}' establecido!"
home.deleted: "§aHome '{home}' eliminado!"
home.not_exist: "§cHome '{home}' no existe."
home.teleport: "§aTeletransportado a home '{home}'!"
home.cooldown: "§cDebes esperar {time} segundos antes de usar /home de nuevo."
# Lista de homes
homes.none: "§cNo tienes ningún home establecido."
homes.unlimited: "ilimitado"
homes.list.header: "§aTus homes (§e{current}§a/§e{max}§a):"
homes.list.items: "§e{homes}"
homes.limit.reached: "§cHas alcanzado el número máximo de homes ({max})."
homes.limit.set: "§aLímite global de homes establecido a {max}."
# Mensajes de cooldown
cooldown.set: "§aCooldown global de homes establecido a {time} segundos."
cooldown.disabled: "§aCooldown de homes desactivado."

View File

@@ -0,0 +1,30 @@
# Messages générales
no_permission: "§cVous n'avez pas la permission d'utiliser cette commande."
invalid_number: "§cVeuillez fournir un nombre valide."
cooldown.range: "§cLe cooldown doit être compris entre -1 et 60 secondes."
# Utilisation des commandes
usage.sethome: "§cUtilisation : /sethome <nom>"
usage.delhome: "§cUtilisation : /delhome <nom>"
usage.home: "§cUtilisation : /home <nom>"
usage.homecount: "§cUtilisation : /homecount <nombre>"
usage.homecooldown: "§cUtilisation : /homecooldown <secondes>"
# Messages de home
home.set: "§aHome '{home}' défini !"
home.deleted: "§aHome '{home}' supprimé !"
home.not_exist: "§cHome '{home}' n'existe pas."
home.teleport: "§aTéléporté vers le home '{home}' !"
home.cooldown: "§cVous devez attendre {time} secondes avant d'utiliser /home à nouveau."
# Liste des homes
homes.none: "§cVous n'avez aucun home défini."
homes.unlimited: "illimité"
homes.list.header: "§aVos homes (§e{current}§a/§e{max}§a) :"
homes.list.items: "§e{homes}"
homes.limit.reached: "§cVous avez atteint le nombre maximum de homes ({max})."
homes.limit.set: "§aLimite globale de homes définie à {max}."
# Messages de cooldown
cooldown.set: "§aCooldown global des homes défini à {time} secondes."
cooldown.disabled: "§aCooldown des homes désactivé."

View File

@@ -0,0 +1,30 @@
# Messaggi generali
no_permission: "§cNon hai il permesso di usare questo comando."
invalid_number: "§cPer favore, inserisci un numero valido."
cooldown.range: "§cIl cooldown deve essere tra -1 e 60 secondi."
# Uso dei comandi
usage.sethome: "§cUso: /sethome <nome>"
usage.delhome: "§cUso: /delhome <nome>"
usage.home: "§cUso: /home <nome>"
usage.homecount: "§cUso: /homecount <numero>"
usage.homecooldown: "§cUso: /homecooldown <secondi>"
# Messaggi di home
home.set: "§aHome '{home}' impostata!"
home.deleted: "§aHome '{home}' eliminata!"
home.not_exist: "§cHome '{home}' non esiste."
home.teleport: "§aTeletrasportato a home '{home}'!"
home.cooldown: "§cDevi aspettare {time} secondi prima di usare di nuovo /home."
# Lista delle home
homes.none: "§cNon hai nessuna home impostata."
homes.unlimited: "illimitato"
homes.list.header: "§aLe tue home (§e{current}§a/§e{max}§a):"
homes.list.items: "§e{homes}"
homes.limit.reached: "§cHai raggiunto il numero massimo di home ({max})."
homes.limit.set: "§aLimite globale di home impostato a {max}."
# Messaggi di cooldown
cooldown.set: "§aCooldown globale delle home impostato a {time} secondi."
cooldown.disabled: "§aCooldown delle home disattivato."

View File

@@ -0,0 +1,30 @@
# Algemene berichten
no_permission: "§cJe hebt geen toestemming om dit commando te gebruiken."
invalid_number: "§cVoer een geldig nummer in."
cooldown.range: "§cCooldown moet tussen -1 en 60 seconden liggen."
# Gebruik van commando's
usage.sethome: "§cGebruik: /sethome <naam>"
usage.delhome: "§cGebruik: /delhome <naam>"
usage.home: "§cGebruik: /home <naam>"
usage.homecount: "§cGebruik: /homecount <nummer>"
usage.homecooldown: "§cGebruik: /homecooldown <seconden>"
# Home berichten
home.set: "§aHome '{home}' ingesteld!"
home.deleted: "§aHome '{home}' verwijderd!"
home.not_exist: "§cHome '{home}' bestaat niet."
home.teleport: "§aGeteleporteerd naar home '{home}'!"
home.cooldown: "§cJe moet {time} seconden wachten voordat je /home opnieuw kunt gebruiken."
# Home lijst
homes.none: "§cJe hebt geen homes ingesteld."
homes.unlimited: "onbeperkt"
homes.list.header: "§aJe homes (§e{current}§a/§e{max}§a):"
homes.list.items: "§e{homes}"
homes.limit.reached: "§cJe hebt het maximale aantal homes ({max}) bereikt."
homes.limit.set: "§aGlobale homelimit ingesteld op {max}."
# Cooldown berichten
cooldown.set: "§aGlobale home cooldown ingesteld op {time} seconden."
cooldown.disabled: "§aHome cooldown uitgeschakeld."

View File

@@ -0,0 +1,30 @@
# Mensagens gerais
no_permission: "§cVocê não tem permissão para usar este comando."
invalid_number: "§cPor favor, forneça um número válido."
cooldown.range: "§cO cooldown deve estar entre -1 e 60 segundos."
# Uso de comandos
usage.sethome: "§cUso: /sethome <nome>"
usage.delhome: "§cUso: /delhome <nome>"
usage.home: "§cUso: /home <nome>"
usage.homecount: "§cUso: /homecount <número>"
usage.homecooldown: "§cUso: /homecooldown <segundos>"
# Mensagens de home
home.set: "§aHome '{home}' definida!"
home.deleted: "§aHome '{home}' deletada!"
home.not_exist: "§cHome '{home}' não existe."
home.teleport: "§aTeleportado para a home '{home}'!"
home.cooldown: "§cVocê deve esperar {time} segundos antes de usar /home novamente."
# Lista de homes
homes.none: "§cVocê não tem nenhuma home definida."
homes.unlimited: "ilimitado"
homes.list.header: "§aSuas homes (§e{current}§a/§e{max}§a):"
homes.list.items: "§e{homes}"
homes.limit.reached: "§cVocê atingiu o número máximo de homes ({max})."
homes.limit.set: "§aLimite global de homes definido para {max}."
# Mensagens de cooldown
cooldown.set: "§aCooldown global de homes definido para {time} segundos."
cooldown.disabled: "§aCooldown de homes desativado."

View File

@@ -0,0 +1,30 @@
# Общие сообщения
no_permission: "§cУ вас нет разрешения на использование этой команды."
invalid_number: "§cПожалуйста, укажите корректное число."
cooldown.range: "§cВремя восстановления должно быть от -1 до 60 секунд."
# Использование команд
usage.sethome: "§cИспользование: /sethome <имя>"
usage.delhome: "§cИспользование: /delhome <имя>"
usage.home: "§cИспользование: /home <имя>"
usage.homecount: "§cИспользование: /homecount <число>"
usage.homecooldown: "§cИспользование: /homecooldown <секунды>"
# Сообщения о доме
home.set: "§aДом '{home}' установлен!"
home.deleted: "§aДом '{home}' удалён!"
home.not_exist: "§cДом '{home}' не существует."
home.teleport: "§aТелепортировано к дому '{home}'!"
home.cooldown: "§cВы должны подождать {time} секунд перед повторным использованием /home."
# Список домов
homes.none: "§cУ вас нет установленных домов."
homes.unlimited: "безлимитно"
homes.list.header: "§aВаши дома (§e{current}§a/§e{max}§a):"
homes.list.items: "§e{homes}"
homes.limit.reached: "§cВы достигли максимального числа домов ({max})."
homes.limit.set: "§aГлобальный лимит домов установлен на {max}."
# Сообщения о перезарядке
cooldown.set: "§aГлобальный таймер восстановления домов установлен на {time} секунд."
cooldown.disabled: "§aПерезарядка домов отключена."