diff --git a/src/main/java/io/github/a5h73y/carz/Carz.java b/src/main/java/io/github/a5h73y/carz/Carz.java index 2ecc2f6..99adca2 100644 --- a/src/main/java/io/github/a5h73y/carz/Carz.java +++ b/src/main/java/io/github/a5h73y/carz/Carz.java @@ -3,9 +3,12 @@ import io.github.a5h73y.carz.commands.CarzAutoTabCompleter; import io.github.a5h73y.carz.commands.CarzCommands; import io.github.a5h73y.carz.commands.CarzConsoleCommands; -import io.github.a5h73y.carz.configuration.Settings; +import io.github.a5h73y.carz.configuration.CarzConfiguration; +import io.github.a5h73y.carz.configuration.ConfigManager; +import io.github.a5h73y.carz.configuration.impl.DefaultConfig; import io.github.a5h73y.carz.controllers.CarController; import io.github.a5h73y.carz.controllers.FuelController; +import io.github.a5h73y.carz.enums.ConfigType; import io.github.a5h73y.carz.listeners.PlayerListener; import io.github.a5h73y.carz.listeners.SignListener; import io.github.a5h73y.carz.listeners.VehicleListener; @@ -29,18 +32,26 @@ public class Carz extends JavaPlugin { private FuelController fuelController; private CarController carController; - private Settings settings; + private ConfigManager configManager; private ItemMetaUtils itemMetaUtils; + /** + * Get the plugin's instance. + * + * @return Carz plugin instance. + */ public static Carz getInstance() { return instance; } + /** + * Initialise the Carz plugin. + */ @Override public void onEnable() { instance = this; - settings = new Settings(this); + configManager = new ConfigManager(this.getDataFolder()); carController = new CarController(this); fuelController = new FuelController(this); itemMetaUtils = new ItemMetaUtils(); @@ -52,46 +63,47 @@ public void onEnable() { getLogger().info("Enabled Carz v" + getDescription().getVersion()); new MetricsLite(this, BUKKIT_PLUGIN_ID); - updatePlugin(); + checkForUpdates(); } + /** + * Shutdown the plugin. + */ @Override public void onDisable() { PluginUtils.log("Disabled Carz v" + getDescription().getVersion()); instance = null; } - private void setupPlugins() { - bountifulAPI = new BountifulAPI(); - economyAPI = new EconomyAPI(); - } - - private void registerCommands() { - getCommand("carz").setExecutor(new CarzCommands(this)); - getCommand("carzc").setExecutor(new CarzConsoleCommands(this)); - if (getConfig().getBoolean("Other.UseAutoTabCompletion")) { - getCommand("carz").setTabCompleter(new CarzAutoTabCompleter(this)); - } - } - - private void registerEvents() { - getServer().getPluginManager().registerEvents(new VehicleListener(this), this); - getServer().getPluginManager().registerEvents(new PlayerListener(this), this); - getServer().getPluginManager().registerEvents(new SignListener(this), this); - } - + /** + * The Carz message prefix. + * @return carz prefix from the config. + */ public static String getPrefix() { return TranslationUtils.getTranslation("Carz.Prefix", false); } - private void updatePlugin() { - if (getConfig().getBoolean("Other.UpdateCheck")) { - new CarzUpdater(this, SPIGOT_PLUGIN_ID).checkForUpdateAsync(); - } + /** + * Get the matching {@link CarzConfiguration} for the given {@link ConfigType}. + * + * @param type {@link ConfigType} + * @return matching {@link CarzConfiguration} + */ + public static CarzConfiguration getConfig(ConfigType type) { + return instance.configManager.get(type); + } + + /** + * Get the default config.yml file. + * + * @return {@link DefaultConfig} + */ + public static DefaultConfig getDefaultConfig() { + return (DefaultConfig) instance.configManager.get(ConfigType.DEFAULT); } - public Settings getSettings() { - return settings; + public ConfigManager getConfigManager() { + return configManager; } public FuelController getFuelController() { @@ -113,4 +125,29 @@ public EconomyAPI getEconomyAPI() { public ItemMetaUtils getItemMetaUtils() { return itemMetaUtils; } + + private void setupPlugins() { + bountifulAPI = new BountifulAPI(); + economyAPI = new EconomyAPI(); + } + + private void registerCommands() { + getCommand("carz").setExecutor(new CarzCommands(this)); + getCommand("carzc").setExecutor(new CarzConsoleCommands(this)); + if (getConfig().getBoolean("Other.UseAutoTabCompletion")) { + getCommand("carz").setTabCompleter(new CarzAutoTabCompleter(this)); + } + } + + private void registerEvents() { + getServer().getPluginManager().registerEvents(new VehicleListener(this), this); + getServer().getPluginManager().registerEvents(new PlayerListener(this), this); + getServer().getPluginManager().registerEvents(new SignListener(this), this); + } + + private void checkForUpdates() { + if (getConfig().getBoolean("Other.UpdateCheck")) { + new CarzUpdater(this, SPIGOT_PLUGIN_ID).checkForUpdateAsync(); + } + } } diff --git a/src/main/java/io/github/a5h73y/carz/commands/CarzAutoTabCompleter.java b/src/main/java/io/github/a5h73y/carz/commands/CarzAutoTabCompleter.java index caa1c7f..689b3a3 100644 --- a/src/main/java/io/github/a5h73y/carz/commands/CarzAutoTabCompleter.java +++ b/src/main/java/io/github/a5h73y/carz/commands/CarzAutoTabCompleter.java @@ -1,6 +1,7 @@ package io.github.a5h73y.carz.commands; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import io.github.a5h73y.carz.Carz; @@ -18,6 +19,8 @@ */ public class CarzAutoTabCompleter extends AbstractPluginReceiver implements TabCompleter { + private final List addRemoveList = Arrays.asList("climb", "speed", "launch", "placeable"); + public CarzAutoTabCompleter(final Carz carz) { super(carz); } @@ -32,14 +35,28 @@ public List onTabComplete(CommandSender sender, Command command, String return null; } - if (args.length > 1) { - return new ArrayList<>(); - } - final Player player = (Player) sender; List allowedCommands = new ArrayList<>(); List filteredCommands = new ArrayList<>(); + if (args.length == 1) { + allowedCommands = populateMainCommands(player); + + } else if (args.length == 2) { + allowedCommands = populateChildCommands(player, args[0].toLowerCase()); + } + + for (String allowedCommand : allowedCommands) { + if (allowedCommand.startsWith(args[args.length - 1])) { + filteredCommands.add(allowedCommand); + } + } + + return filteredCommands.isEmpty() ? allowedCommands : filteredCommands; + } + + private List populateMainCommands(Player player) { + List allowedCommands = new ArrayList<>(); allowedCommands.add("cmds"); allowedCommands.add("claim"); allowedCommands.add("details"); @@ -67,10 +84,8 @@ public List onTabComplete(CommandSender sender, Command command, String } if (PermissionUtils.hasStrictPermission(player, Permissions.ADMIN, false)) { - allowedCommands.add("addclimb"); - allowedCommands.add("addspeed"); - allowedCommands.add("removeclimb"); - allowedCommands.add("removespeed"); + allowedCommands.add("add"); + allowedCommands.add("remove"); allowedCommands.add("createtype"); allowedCommands.add("economy"); allowedCommands.add("reload"); @@ -80,12 +95,19 @@ public List onTabComplete(CommandSender sender, Command command, String } } - for (String allowedCommand : allowedCommands) { - if (allowedCommand.startsWith(args[args.length - 1])) { - filteredCommands.add(allowedCommand); - } + return allowedCommands; + } + + private List populateChildCommands(Player player, String command) { + List allowedCommands = new ArrayList<>(); + + switch (command) { + case "add": + case "remove": + allowedCommands = addRemoveList; + break; } - return filteredCommands.isEmpty() ? allowedCommands : filteredCommands; + return allowedCommands; } } diff --git a/src/main/java/io/github/a5h73y/carz/commands/CarzCommands.java b/src/main/java/io/github/a5h73y/carz/commands/CarzCommands.java index b8d4cac..dd91f3c 100644 --- a/src/main/java/io/github/a5h73y/carz/commands/CarzCommands.java +++ b/src/main/java/io/github/a5h73y/carz/commands/CarzCommands.java @@ -74,10 +74,6 @@ public boolean onCommand(CommandSender sender, Command command, String label, St return false; } - if (!DelayTasks.getInstance().delayPlayer(player, 4)) { - return false; - } - CarUtils.givePlayerCar(player, args.length > 1 ? args[1] : DEFAULT_CAR); TranslationUtils.sendTranslation("Car.Spawned", player); break; @@ -128,44 +124,23 @@ public boolean onCommand(CommandSender sender, Command command, String label, St carz.getCarController().stashCar(player); break; - case "addcb": - case "addclimb": - case "addclimbblock": + case "add": if (!PermissionUtils.hasStrictPermission(player, Permissions.ADMIN)) { return false; - } - PluginUtils.addClimbBlock(player, args); - break; - - case "removecb": - case "removeclimb": - case "removeclimbblock": - if (!PermissionUtils.hasStrictPermission(player, Permissions.ADMIN)) { - return false; - } - - PluginUtils.removeClimbBlock(player, args); - break; - - case "addsb": - case "addspeed": - case "addspeedblock": - if (!PermissionUtils.hasStrictPermission(player, Permissions.ADMIN)) { + } else if (!PluginUtils.validateArgs(player, args, 3, 4)) { return false; } - PluginUtils.addSpeedBlock(player, args); + PluginUtils.addBlockType(player, args); break; - case "removesb": - case "removespeed": - case "removespeedblock": + case "remove": if (!PermissionUtils.hasStrictPermission(player, Permissions.ADMIN)) { return false; } - PluginUtils.removeSpeedBlock(player, args); + PluginUtils.removeBlockType(player, args); break; case "createtype": @@ -240,7 +215,7 @@ public boolean onCommand(CommandSender sender, Command command, String label, St return false; } - carz.getSettings().reload(); + Carz.getInstance().getConfigManager().reloadConfigs(); TranslationUtils.sendTranslation("Carz.ConfigReloaded", player); break; diff --git a/src/main/java/io/github/a5h73y/carz/commands/CarzConsoleCommands.java b/src/main/java/io/github/a5h73y/carz/commands/CarzConsoleCommands.java index 93d191e..907d6c3 100644 --- a/src/main/java/io/github/a5h73y/carz/commands/CarzConsoleCommands.java +++ b/src/main/java/io/github/a5h73y/carz/commands/CarzConsoleCommands.java @@ -61,28 +61,16 @@ public boolean onCommand(CommandSender sender, Command command, String label, St TranslationUtils.sendTranslation("Car.Spawned", sender, player); break; - case "addcb": - case "addclimb": - case "addclimbblock": - PluginUtils.addClimbBlock(sender, args); - break; - - case "removecb": - case "removeclimb": - case "removeclimbblock": - PluginUtils.removeClimbBlock(sender, args); - break; + case "add": + if (!PluginUtils.validateArgs(sender, args, 3, 4)) { + return false; + } - case "addsb": - case "addspeed": - case "addspeedblock": - PluginUtils.addSpeedBlock(sender, args); + PluginUtils.addBlockType(sender, args); break; - case "removesb": - case "removespeed": - case "removespeedblock": - PluginUtils.removeSpeedBlock(sender, args); + case "remove": + PluginUtils.removeBlockType(sender, args); break; case "destroyall": @@ -91,7 +79,7 @@ public boolean onCommand(CommandSender sender, Command command, String label, St break; case "reload": - carz.getSettings().reload(); + Carz.getInstance().getConfigManager().reloadConfigs(); TranslationUtils.sendTranslation("Carz.ConfigReloaded", sender); break; diff --git a/src/main/java/io/github/a5h73y/carz/configuration/CarzConfiguration.java b/src/main/java/io/github/a5h73y/carz/configuration/CarzConfiguration.java new file mode 100644 index 0000000..68a298e --- /dev/null +++ b/src/main/java/io/github/a5h73y/carz/configuration/CarzConfiguration.java @@ -0,0 +1,91 @@ +package io.github.a5h73y.carz.configuration; + +import java.io.File; +import java.io.IOException; + +import io.github.a5h73y.carz.utility.PluginUtils; +import org.bukkit.configuration.InvalidConfigurationException; +import org.bukkit.configuration.file.YamlConfiguration; + +/** + * Base Carz configuration file. + */ +public abstract class CarzConfiguration extends YamlConfiguration { + + protected File file; + + /** + * The config file's name. + * + * @return file name + */ + protected abstract String getFileName(); + + /** + * Initialise the configuration file. + * + * @throws IOException io exception + */ + protected abstract void initializeConfig() throws IOException; + + /** + * Setup the file. + */ + void setupFile(File dataFolder) { + file = new File(dataFolder, getFileName()); + createIfNotExists(); + reload(); + + try { + initializeConfig(); + save(); + } catch (IOException e) { + PluginUtils.log("Failed to load " + getFileName(), 2); + e.printStackTrace(); + } + } + + /** + * Persist any changes to the file. + */ + public void save() { + try { + this.save(file); + + } catch (IOException e) { + PluginUtils.log("Failed to save file: " + getFileName(), 2); + e.printStackTrace(); + } + } + + /** + * Reload the configuration file. + */ + protected void reload() { + try { + this.load(file); + + } catch (IOException | InvalidConfigurationException e) { + PluginUtils.log("Failed to load file: " + getFileName(), 2); + e.printStackTrace(); + } + } + + /** + * Create the physical file if it doesn't exist. + */ + private void createIfNotExists() { + if (file.exists()) { + return; + } + + try { + file.createNewFile(); + PluginUtils.log("Created " + getFileName()); + + } catch (Exception e) { + PluginUtils.log("Failed to create file: " + getFileName(), 2); + e.printStackTrace(); + } + } +} diff --git a/src/main/java/io/github/a5h73y/carz/configuration/ConfigManager.java b/src/main/java/io/github/a5h73y/carz/configuration/ConfigManager.java new file mode 100644 index 0000000..264d684 --- /dev/null +++ b/src/main/java/io/github/a5h73y/carz/configuration/ConfigManager.java @@ -0,0 +1,45 @@ +package io.github.a5h73y.carz.configuration; + +import java.io.File; +import java.util.EnumMap; + +import io.github.a5h73y.carz.configuration.impl.BlocksConfig; +import io.github.a5h73y.carz.configuration.impl.DefaultConfig; +import io.github.a5h73y.carz.configuration.impl.StringsConfig; +import io.github.a5h73y.carz.enums.ConfigType; + +public class ConfigManager { + + private final File dataFolder; + + private final EnumMap carzConfigs = new EnumMap<>(ConfigType.class); + + public ConfigManager(File dataFolder) { + this.dataFolder = dataFolder; + createCarzFolder(); + + carzConfigs.put(ConfigType.DEFAULT, new DefaultConfig()); + carzConfigs.put(ConfigType.STRINGS, new StringsConfig()); + carzConfigs.put(ConfigType.BLOCKS, new BlocksConfig()); + + for (CarzConfiguration carzConfig: carzConfigs.values()) { + carzConfig.setupFile(dataFolder); + } + } + + private void createCarzFolder() { + if (!dataFolder.exists()) { + dataFolder.mkdirs(); + } + } + + public CarzConfiguration get(ConfigType type) { + return carzConfigs.get(type); + } + + public void reloadConfigs() { + for (CarzConfiguration carzrConfig: carzConfigs.values()) { + carzrConfig.reload(); + } + } +} diff --git a/src/main/java/io/github/a5h73y/carz/configuration/Settings.java b/src/main/java/io/github/a5h73y/carz/configuration/Settings.java deleted file mode 100644 index 1f06c9f..0000000 --- a/src/main/java/io/github/a5h73y/carz/configuration/Settings.java +++ /dev/null @@ -1,378 +0,0 @@ -package io.github.a5h73y.carz.configuration; - -import java.io.File; -import java.io.IOException; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import io.github.a5h73y.carz.Carz; -import io.github.a5h73y.carz.other.AbstractPluginReceiver; -import io.github.a5h73y.carz.utility.PluginUtils; -import io.github.a5h73y.carz.utility.StringUtils; -import io.github.a5h73y.carz.utility.TranslationUtils; -import org.bukkit.ChatColor; -import org.bukkit.Material; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.configuration.file.YamlConfiguration; - -/** - * Carz config convenience accessors. - */ -public class Settings extends AbstractPluginReceiver { - - private File stringsFile; - private FileConfiguration stringsConfig; - - private Set climbBlocks; - private Map speedBlocks; - - /** - * Carz configuration Settings. - * config.yml and strings.yml will be generated with default values. - * - * @param carz plugin instance - */ - public Settings(final Carz carz) { - super(carz); - - setupConfig(); - setupStrings(); - reloadClimbBlocks(); - reloadSpeedBlocks(); - } - - /** - * The strings.yml config. - * - * @return string.yml {@link FileConfiguration} - */ - public FileConfiguration getStringsConfig() { - return stringsConfig; - } - - /** - * Reload the Carz Configuration files. - */ - public void reload() { - carz.reloadConfig(); - stringsConfig = YamlConfiguration.loadConfiguration(stringsFile); - reloadClimbBlocks(); - reloadSpeedBlocks(); - } - - /** - * Initialise the config.yml on startup. - * Values will be defaulted if not set. - */ - private void setupConfig() { - carz.getConfig().options().header("==== Carz Config ==== #"); - - carz.getConfig().addDefault("Key.Material", "STICK"); - carz.getConfig().addDefault("Key.Glow", true); - carz.getConfig().addDefault("Key.GiveOnCarEnter", true); - carz.getConfig().addDefault("Key.RequireCarzKey", true); - carz.getConfig().addDefault("Key.ManualLocking.Enabled", true); - carz.getConfig().addDefault("Key.ManualLocking.ShiftAction", true); - - carz.getConfig().addDefault("Speed.Upgrade.Increment", 25.0); - carz.getConfig().addDefault("Speed.Upgrade.Max", 200.0); - - carz.getConfig().addDefault("CommandEnabled.Spawn", true); - carz.getConfig().addDefault("CommandEnabled.Purchase", true); - carz.getConfig().addDefault("CommandEnabled.Refuel", true); - carz.getConfig().addDefault("CommandEnabled.Upgrade", true); - - carz.getConfig().addDefault("Fuel.Enabled", true); - carz.getConfig().addDefault("Fuel.ScaleCost", true); - carz.getConfig().addDefault("Fuel.MaxCapacity", 3000.0); - carz.getConfig().addDefault("Fuel.GaugeScale", 40); - - carz.getConfig().addDefault("ClimbBlocks.AllBlocks", true); - carz.getConfig().addDefault("ClimbBlocks.Materials", new String[]{"GOLD_BLOCK"}); - carz.getConfig().addDefault("ClimbBlocks.Strength", 0.05D); - - carz.getConfig().addDefault("Vault.Enabled", true); - carz.getConfig().addDefault("Vault.ConfirmPurchases", true); - carz.getConfig().addDefault("Vault.Cost.Upgrade", 8.0); - carz.getConfig().addDefault("Vault.Cost.Refuel", 2.0); - - carz.getConfig().addDefault("BountifulAPI.Enabled", true); - - carz.getConfig().addDefault("PlaceholderAPI.Enabled", true); - - carz.getConfig().addDefault("Other.ControlCarsWhileFalling", true); - carz.getConfig().addDefault("Other.DamageEntities.Enabled", true); - carz.getConfig().addDefault("Other.DamageEntities.Damage", 5.0); - carz.getConfig().addDefault("Other.DestroyInLiquid", true); - carz.getConfig().addDefault("Other.AutomaticCarLock", true); - carz.getConfig().addDefault("Other.OnlyOwnedCarsDrive", false); - carz.getConfig().addDefault("Other.SignProtection", true); - carz.getConfig().addDefault("Other.UpdateCheck", true); - carz.getConfig().addDefault("Other.UseAutoTabCompletion", true); - carz.getConfig().addDefault("Other.UseEffects", true); - carz.getConfig().addDefault("Other.UsePermissions", true); - - carz.getConfig().addDefault("CarTypes.default.StartMaxSpeed", 60.0); - carz.getConfig().addDefault("CarTypes.default.MaxUpgradeSpeed", 200.0); - carz.getConfig().addDefault("CarTypes.default.Acceleration", 5.0); - carz.getConfig().addDefault("CarTypes.default.FuelUsage", 1.0); - carz.getConfig().addDefault("CarTypes.default.FillMaterial", "AIR"); - carz.getConfig().addDefault("CarTypes.default.Cost", 10.0); - - carz.getConfig().options().copyDefaults(true); - carz.saveConfig(); - } - - /** - * Initialise the strings.yml on startup. - * Values will be defaulted if not set. - */ - private void setupStrings() { - if (!setupStringsConfig()) { - return; - } - - stringsConfig.addDefault("Carz.Prefix", "&0[&bCarz&0]&7 "); - stringsConfig.addDefault("Carz.SignHeader", "&0[&bCarz&0]"); - stringsConfig.addDefault("Carz.Commands", "To display all commands enter &f/carz cmds"); - stringsConfig.addDefault("Carz.ConsoleCommands", "To display all commands enter &f/carzc cmds"); - stringsConfig.addDefault("Carz.ConfigReloaded", "The config has been reloaded."); - stringsConfig.addDefault("Carz.SignRemoved", "Carz sign removed!"); - stringsConfig.addDefault("Carz.CarsDestroyed", "All cars destroyed!"); - stringsConfig.addDefault("Carz.SignCreated", "%TYPE% sign created."); - stringsConfig.addDefault("Carz.Heading", "-- &9&l%TEXT% &r--"); - - stringsConfig.addDefault("Car.Spawned", "Car Spawned!"); - stringsConfig.addDefault("Car.EngineStart", "You switch the engine on."); - stringsConfig.addDefault("Car.EngineStop", "You switch the engine off."); - stringsConfig.addDefault("Car.CarLocked", "You lock the car."); - stringsConfig.addDefault("Car.CarUnlocked", "You unlock the car."); - stringsConfig.addDefault("Car.PlayerCar", "&b%PLAYER%&f's car"); - stringsConfig.addDefault("Car.FuelEmpty", "This car has run out of fuel!"); - stringsConfig.addDefault("Car.LiquidDamage", "Your car has been destroyed by liquid!"); - stringsConfig.addDefault("Car.UpgradeSpeed", "New top speed: %SPEED%"); - stringsConfig.addDefault("Car.Key.Display", "&b%PLAYER%&f's key"); - stringsConfig.addDefault("Car.Key.Received", "You receive a key."); - stringsConfig.addDefault("Car.Claimed", "You are now the owner of this car."); - - stringsConfig.addDefault("Purchase.Confirm.Purchase", "&7Enter &a/carz confirm &7to confirm, or &c/carz cancel &7to cancel the purchase."); - stringsConfig.addDefault("Purchase.Confirm.Car", "You are about to purchase a &b%TYPE% &7car, costing &b%COST%%CURRENCY%&7."); - stringsConfig.addDefault("Purchase.Confirm.Upgrade", "You are about to upgrade your car from &b%FROM% &7to &b%TO%&7, costing &b%COST%%CURRENCY%&7."); - stringsConfig.addDefault("Purchase.Confirm.Refuel", "You are about to refuel &b%PERCENT% &7of your car's fuel, costing &b%COST%%CURRENCY%&7."); - stringsConfig.addDefault("Purchase.Success.Car", "&f%TYPE% &7car Purchased!"); - stringsConfig.addDefault("Purchase.Success.Upgrade", "Car Upgraded!"); - stringsConfig.addDefault("Purchase.Success.Refuel", "Car Refuelled!"); - stringsConfig.addDefault("Purchase.Cancelled", "Purchase cancelled."); - - stringsConfig.addDefault("CarType.Create.Name", "&d What would you like this car to be called?"); - stringsConfig.addDefault("CarType.Create.StartMaxSpeed", "&d What should the Car's Start Speed be?\n&a (default = 60.0)"); - stringsConfig.addDefault("CarType.Create.MaxUpgradeSpeed", "&d What should the Car's Max Upgrade Speed be?\n&a (default = 120.0)"); - stringsConfig.addDefault("CarType.Create.Acceleration", "&d What should the Car's Acceleration be?\n&a (default = 1.0)"); - stringsConfig.addDefault("CarType.Create.FuelUsage", "&d What should the Fuel Usage be?\n&a (default = 1.0)"); - stringsConfig.addDefault("CarType.Create.FillMaterial", "&d What should the Fill Material be?\n&a (default = AIR)"); - stringsConfig.addDefault("CarType.Create.Cost", "&d How much should the car cost?\n&a (default = 10.0)"); - stringsConfig.addDefault("CarType.Create.Success", "&d All done, &a%VALUE% &dcreated."); - stringsConfig.addDefault("CarType.Error.InvalidName", "Invalid Car Type name."); - stringsConfig.addDefault("CarType.Error.InvalidValue", "Invalid Value."); - stringsConfig.addDefault("CarType.Error.AlreadyExists", "This Car Type already exists."); - - stringsConfig.addDefault("Error.NoPermission", "You do not have permission: &b%PERMISSION%"); - stringsConfig.addDefault("Error.SignProtected", "This sign is protected!"); - stringsConfig.addDefault("Error.UnknownCommand", "Unknown Command!"); - stringsConfig.addDefault("Error.UnknownSignCommand", "Unknown Sign Command!"); - stringsConfig.addDefault("Error.CommandDisabled", "This command has been disabled!"); - stringsConfig.addDefault("Error.InCar", "You are already in a car!"); - stringsConfig.addDefault("Error.NotInCar", "You are not in a car!"); - stringsConfig.addDefault("Error.HaveCar", "You already have a car!"); - stringsConfig.addDefault("Error.FuelDisabled", "Fuel is disabled."); - stringsConfig.addDefault("Error.PurchaseFailed", "Purchase failed. Cost: %COST%"); - stringsConfig.addDefault("Error.FullyUpgraded", "Your car is already fully upgraded!"); - stringsConfig.addDefault("Error.Owned", "This car is owned by %PLAYER%!"); - stringsConfig.addDefault("Error.UnknownCarType", "Unknown car type."); - stringsConfig.addDefault("Error.UnknownPlayer", "Unknown player."); - stringsConfig.addDefault("Error.UnknownMaterial", "Unknown Material: "); - stringsConfig.addDefault("Error.SpecifyPlayer", "Please specify a player."); - stringsConfig.addDefault("Error.PurchaseOutstanding", "You have an outstanding purchase."); - stringsConfig.addDefault("Error.NoPurchaseOutstanding", "You don't have an outstanding purchase."); - stringsConfig.addDefault("Error.CarNotDriven", "This can hasn't been driven yet."); - - stringsConfig.options().copyDefaults(true); - try { - stringsConfig.save(stringsFile); - } catch (IOException e) { - e.printStackTrace(); - } - } - - /** - * Add the Material to the list of Climb Blocks. - * - * @param material {@link Material} - */ - public void addClimbBlock(Material material) { - if (material == null) { - return; - } - - List materials = getRawClimbBlocks(); - materials.add(material.name()); - carz.getConfig().set("ClimbBlocks.Materials", materials); - carz.saveConfig(); - reloadClimbBlocks(); - } - - /** - * Remove the Material from the list of Climb Blocks. - * - * @param material {@link Material} - */ - public void removeClimbBlock(Material material) { - if (material == null) { - return; - } - - List materials = getRawClimbBlocks(); - materials.remove(material.name()); - carz.getConfig().set("ClimbBlocks.Materials", materials); - carz.saveConfig(); - reloadClimbBlocks(); - } - - /** - * Add the Material to the list of Speed Blocks. - * - * @param material {@link Material} - * @param speed speed - */ - public void addSpeedBlock(Material material, double speed) { - if (material == null) { - return; - } - - carz.getConfig().set("SpeedBlocks." + material.name(), speed); - carz.saveConfig(); - reloadSpeedBlocks(); - } - - /** - * Remove the Material from the list of Speed Blocks. - * - * @param material {@link Material} - */ - public void removeSpeedBlock(Material material) { - if (material == null) { - return; - } - - carz.getConfig().set("SpeedBlocks." + material.name(), null); - carz.saveConfig(); - reloadSpeedBlocks(); - } - - public Set getClimbBlocks() { - return this.climbBlocks; - } - - public boolean containsSpeedBlock(Material material) { - return this.speedBlocks.containsKey(material.name()); - } - - public Set getSpeedBlocks() { - return this.speedBlocks.keySet(); - } - - public Double getSpeedModifier(Material material) { - return this.speedBlocks.get(material.name()); - } - - public List getRawClimbBlocks() { - return carz.getConfig().getStringList("ClimbBlocks.Materials"); - } - - public Material getKey() { - return Material.getMaterial(carz.getConfig().getString("Key.Material")); - } - - public String getSignHeader() { - return TranslationUtils.getTranslation("Carz.SignHeader", false); - } - - public String getStrippedSignHeader() { - return ChatColor.stripColor(StringUtils.colour(getSignHeader())); - } - - public boolean isDestroyInLiquid() { - return carz.getConfig().getBoolean("Other.DestroyInLiquid"); - } - - public boolean isOnlyOwnedCarsDrive() { - return carz.getConfig().getBoolean("Other.OnlyOwnedCarsDrive"); - } - - public boolean isControlCarsWhileFalling() { - return carz.getConfig().getBoolean("Other.ControlCarsWhileFalling"); - } - - public boolean isFuelScaleCost() { - return carz.getConfig().getBoolean("Fuel.ScaleCost"); - } - - public boolean isAutomaticCarLock() { - return carz.getConfig().getBoolean("Other.AutomaticCarLock"); - } - - public double getUpgradeIncrement() { - return carz.getConfig().getDouble("Speed.Upgrade.Increment"); - } - - public double getUpgradeMaxSpeed() { - return carz.getConfig().getDouble("Speed.Upgrade.Max"); - } - - public double getClimbBlockStrength() { - return carz.getConfig().getDouble("ClimbBlocks.Strength"); - } - - /** - * Setup the strings.yml config. - * The file will be created if it doesn't exist. - * - * @return file setup was successful - */ - private boolean setupStringsConfig() { - stringsFile = new File(carz.getDataFolder(), "strings.yml"); - - if (!stringsFile.exists()) { - try { - if (stringsFile.createNewFile()) { - carz.getLogger().info("Created strings.yml"); - } - } catch (Exception ex) { - ex.printStackTrace(); - return false; - } - } - stringsConfig = YamlConfiguration.loadConfiguration(stringsFile); - return true; - } - - private void reloadClimbBlocks() { - this.climbBlocks = PluginUtils.convertToValidMaterials(getRawClimbBlocks()); - } - - private void reloadSpeedBlocks() { - this.speedBlocks = new HashMap<>(); - ConfigurationSection section = carz.getConfig().getConfigurationSection("SpeedBlocks"); - - if (section != null) { - Set test = PluginUtils.convertToValidMaterials(section.getKeys(false)); - - for (Material s : test) { - this.speedBlocks.put(s.name(), carz.getConfig().getDouble("SpeedBlocks." + s.name())); - } - } - } -} diff --git a/src/main/java/io/github/a5h73y/carz/configuration/impl/BlocksConfig.java b/src/main/java/io/github/a5h73y/carz/configuration/impl/BlocksConfig.java new file mode 100644 index 0000000..d61d459 --- /dev/null +++ b/src/main/java/io/github/a5h73y/carz/configuration/impl/BlocksConfig.java @@ -0,0 +1,163 @@ +package io.github.a5h73y.carz.configuration.impl; + +import java.io.IOException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import io.github.a5h73y.carz.configuration.CarzConfiguration; +import io.github.a5h73y.carz.enums.BlockType; +import io.github.a5h73y.carz.utility.PluginUtils; +import org.bukkit.Material; +import org.bukkit.configuration.ConfigurationSection; + +public class BlocksConfig extends CarzConfiguration { + + private Set climbBlocks; + private Set placeableBlocks; + private Map speedBlocks; + private Map launchBlocks; + + @Override + protected String getFileName() { + return "blocks.yml"; + } + + @Override + protected void initializeConfig() throws IOException { + + } + + @Override + public void reload() { + super.reload(); + + this.climbBlocks = extractMaterialBlocks(BlockType.CLIMB); + this.placeableBlocks = extractMaterialBlocks(BlockType.PLACEABLE); + this.speedBlocks = extractMaterialBlocksAmount(BlockType.SPEED); + this.launchBlocks = extractMaterialBlocksAmount(BlockType.LAUNCH); + } + + /** + * Set the amount of the block type. + * Setting the amount to null will delete it from the config. + * + * @param blockType {@link BlockType} + * @param material {@link Material} + * @param amount amount to set + */ + public void setBlock(BlockType blockType, Material material, Double amount) { + if (blockType == null || material == null) { + return; + } + + this.set(blockType.getConfigPath() + "." + material.name(), amount); + this.save(); + this.reload(); + } + + /** + * Add a Material to a the list of block types. + * + * @param blockType {@link BlockType} + * @param material {@link Material} + */ + public void addBlock(BlockType blockType, Material material) { + if (blockType == null || material == null) { + return; + } + + List rawMaterials = this.getStringList(blockType.getConfigPath()); + rawMaterials.add(material.name()); + this.set(blockType.getConfigPath(), rawMaterials); + this.save(); + this.reload(); + } + + /** + * Remove a Material from a list of block types. + * + * @param blockType {@link BlockType} + * @param material {@link Material} + */ + public void removeBlock(BlockType blockType, Material material) { + if (blockType == null || material == null) { + return; + } + + List rawMaterials = this.getStringList(blockType.getConfigPath()); + rawMaterials.remove(material.name()); + this.set(blockType.getConfigPath(), rawMaterials); + this.save(); + this.reload(); + } + + /** + * Determine if the Material already exists within the block types. + * + * @param blockType {@link BlockType} + * @param material {@link Material} + * @return material exists in block type + */ + public boolean alreadyExists(BlockType blockType, Material material) { + if (blockType.isHasAmount()) { + return get(blockType.getConfigPath() + "." + material.name()) != null; + + } else { + return getStringList(blockType.getConfigPath()).contains(material.name()); + } + } + + public Set getSpeedBlocks() { + return this.speedBlocks.keySet(); + } + + public Set getLaunchBlocks() { + return this.launchBlocks.keySet(); + } + + public Set getClimbBlocks() { + return this.climbBlocks; + } + + public Set getPlaceableBlocks() { + return this.placeableBlocks; + } + + public boolean containsSpeedBlock(Material material) { + return this.speedBlocks.containsKey(material.name()); + } + + public boolean containsLaunchBlock(Material material) { + return this.launchBlocks.containsKey(material.name()); + } + + public Double getSpeedModifier(Material material) { + return this.speedBlocks.get(material.name()); + } + + public Double getLaunchAmount(Material material) { + return this.launchBlocks.get(material.name()); + } + + private Set extractMaterialBlocks(BlockType blockType) { + return PluginUtils.convertToValidMaterials(getStringList(blockType.getConfigPath())); + } + + private Map extractMaterialBlocksAmount(BlockType blockType) { + Map values = new HashMap<>(); + ConfigurationSection section = this.getConfigurationSection(blockType.getConfigPath()); + + if (section != null) { + Set materials = PluginUtils.convertToValidMaterials(section.getKeys(false)); + + for (Material material : materials) { + values.put(material.name(), + this.getDouble(blockType.getConfigPath() + "." + material.name())); + } + } + + return values; + } +} diff --git a/src/main/java/io/github/a5h73y/carz/configuration/impl/DefaultConfig.java b/src/main/java/io/github/a5h73y/carz/configuration/impl/DefaultConfig.java new file mode 100644 index 0000000..0cf6db5 --- /dev/null +++ b/src/main/java/io/github/a5h73y/carz/configuration/impl/DefaultConfig.java @@ -0,0 +1,127 @@ +package io.github.a5h73y.carz.configuration.impl; + +import io.github.a5h73y.carz.configuration.CarzConfiguration; +import io.github.a5h73y.carz.utility.StringUtils; +import io.github.a5h73y.carz.utility.TranslationUtils; +import org.bukkit.ChatColor; +import org.bukkit.Material; + +public class DefaultConfig extends CarzConfiguration { + + @Override + protected String getFileName() { + return "config.yml"; + } + + /** + * Initialise the config.yml on startup. + * Values will be defaulted if not set. + */ + @Override + protected void initializeConfig() { + this.options().header("==== Carz Config ==== #"); + + this.addDefault("Key.Material", "STICK"); + this.addDefault("Key.Glow", true); + this.addDefault("Key.GiveOnCarEnter", true); + this.addDefault("Key.RequireCarzKey", true); + this.addDefault("Key.ManualLocking.Enabled", true); + this.addDefault("Key.ManualLocking.ShiftAction", true); + + this.addDefault("Speed.Upgrade.Increment", 25.0); + this.addDefault("Speed.Upgrade.Max", 200.0); + + this.addDefault("CommandEnabled.Spawn", true); + this.addDefault("CommandEnabled.Purchase", true); + this.addDefault("CommandEnabled.Refuel", true); + this.addDefault("CommandEnabled.Upgrade", true); + + this.addDefault("Fuel.Enabled", true); + this.addDefault("Fuel.ScaleCost", true); + this.addDefault("Fuel.MaxCapacity", 3000.0); + this.addDefault("Fuel.GaugeScale", 40); + + this.addDefault("ClimbBlocks.AllBlocks", true); + this.addDefault("ClimbBlocks.Materials", new String[]{"GOLD_BLOCK"}); + this.addDefault("ClimbBlocks.Strength", 0.05D); + + this.addDefault("Vault.Enabled", true); + this.addDefault("Vault.ConfirmPurchases", true); + this.addDefault("Vault.Cost.Upgrade", 8.0); + this.addDefault("Vault.Cost.Refuel", 2.0); + + this.addDefault("BountifulAPI.Enabled", true); + + this.addDefault("PlaceholderAPI.Enabled", true); + + this.addDefault("Other.ControlCarsWhileFalling", true); + this.addDefault("Other.DamageEntities.Enabled", true); + this.addDefault("Other.DamageEntities.Damage", 5.0); + this.addDefault("Other.DestroyInLiquid", true); + this.addDefault("Other.AutomaticCarLock", true); + this.addDefault("Other.OnlyOwnedCarsDrive", false); + this.addDefault("Other.MaxPlayerOwnedCars", 5); + this.addDefault("Other.SignProtection", true); + this.addDefault("Other.UpdateCheck", true); + this.addDefault("Other.UseAutoTabCompletion", true); + this.addDefault("Other.UseEffects", true); + this.addDefault("Other.UsePermissions", true); + + this.addDefault("CarTypes.default.StartMaxSpeed", 60.0); + this.addDefault("CarTypes.default.MaxUpgradeSpeed", 200.0); + this.addDefault("CarTypes.default.Acceleration", 5.0); + this.addDefault("CarTypes.default.FuelUsage", 1.0); + this.addDefault("CarTypes.default.FillMaterial", "AIR"); + this.addDefault("CarTypes.default.Cost", 10.0); + + this.options().copyDefaults(true); + } + + public Material getKey() { + return Material.getMaterial(this.getString("Key.Material")); + } + + public String getSignHeader() { + return TranslationUtils.getTranslation("Carz.SignHeader", false); + } + + public String getStrippedSignHeader() { + return ChatColor.stripColor(StringUtils.colour(getSignHeader())); + } + + public boolean isDestroyInLiquid() { + return this.getBoolean("Other.DestroyInLiquid"); + } + + public boolean isOnlyOwnedCarsDrive() { + return this.getBoolean("Other.OnlyOwnedCarsDrive"); + } + + public boolean isControlCarsWhileFalling() { + return this.getBoolean("Other.ControlCarsWhileFalling"); + } + + public boolean isFuelScaleCost() { + return this.getBoolean("Fuel.ScaleCost"); + } + + public boolean isAutomaticCarLock() { + return this.getBoolean("Other.AutomaticCarLock"); + } + + public double getUpgradeIncrement() { + return this.getDouble("Speed.Upgrade.Increment"); + } + + public double getUpgradeMaxSpeed() { + return this.getDouble("Speed.Upgrade.Max"); + } + + public double getClimbBlockStrength() { + return this.getDouble("ClimbBlocks.Strength"); + } + + public int getMaxPlayerOwnedCars() { + return this.getInt("Other.MaxPlayerOwnedCars"); + } +} diff --git a/src/main/java/io/github/a5h73y/carz/configuration/impl/StringsConfig.java b/src/main/java/io/github/a5h73y/carz/configuration/impl/StringsConfig.java new file mode 100644 index 0000000..973df2e --- /dev/null +++ b/src/main/java/io/github/a5h73y/carz/configuration/impl/StringsConfig.java @@ -0,0 +1,100 @@ +package io.github.a5h73y.carz.configuration.impl; + +import java.io.IOException; + +import io.github.a5h73y.carz.configuration.CarzConfiguration; + +public class StringsConfig extends CarzConfiguration { + + @Override + protected String getFileName() { + return "strings.yml"; + } + + /** + * Initialise the strings.yml on startup. + * Values will be defaulted if not set. + */ + @Override + protected void initializeConfig() throws IOException { + this.addDefault("Carz.Prefix", "&0[&bCarz&0]&7 "); + this.addDefault("Carz.SignHeader", "&0[&bCarz&0]"); + this.addDefault("Carz.Commands", "To display all commands enter &f/carz cmds"); + this.addDefault("Carz.ConsoleCommands", "To display all commands enter &f/carzc cmds"); + this.addDefault("Carz.ConfigReloaded", "The config has been reloaded."); + this.addDefault("Carz.SignRemoved", "Carz sign removed!"); + this.addDefault("Carz.CarsDestroyed", "All cars destroyed!"); + this.addDefault("Carz.SignCreated", "%TYPE% sign created."); + this.addDefault("Carz.Heading", "-- &9&l%TEXT% &r--"); + + this.addDefault("Car.Spawned", "Car Spawned."); + this.addDefault("Car.EngineStart", "You switch the engine on."); + this.addDefault("Car.EngineStop", "You switch the engine off."); + this.addDefault("Car.CarLocked", "You lock the car."); + this.addDefault("Car.CarUnlocked", "You unlock the car."); + this.addDefault("Car.PlayerCar", "&b%PLAYER%&f's car"); + this.addDefault("Car.FuelEmpty", "Your car has run out of fuel!"); + this.addDefault("Car.LiquidDamage", "Your car has been destroyed by liquid!"); + this.addDefault("Car.UpgradeSpeed", "New top speed: &b%SPEED%"); + this.addDefault("Car.Key.Display", "&b%PLAYER%&f's key"); + this.addDefault("Car.Key.Received", "You receive a key."); + this.addDefault("Car.Claimed", "You are now the owner of this car."); + + this.addDefault("Purchase.Confirm.Purchase", "&7Enter &a/carz confirm &7to confirm, or &c/carz cancel &7to cancel the purchase."); + this.addDefault("Purchase.Confirm.Car", "You are about to purchase a &b%TYPE% &7car, costing &b%COST%%CURRENCY%&7."); + this.addDefault("Purchase.Confirm.Upgrade", "You are about to upgrade your car from &b%FROM% &7to &b%TO%&7, costing &b%COST%%CURRENCY%&7."); + this.addDefault("Purchase.Confirm.Refuel", "You are about to refuel &b%PERCENT% &7of your car's fuel, costing &b%COST%%CURRENCY%&7."); + this.addDefault("Purchase.Success.Car", "&f%TYPE% &7car Purchased!"); + this.addDefault("Purchase.Success.Upgrade", "Car Upgraded!"); + this.addDefault("Purchase.Success.Refuel", "Car Refuelled!"); + this.addDefault("Purchase.Cancelled", "Purchase cancelled."); + + this.addDefault("CarType.Create.Name", "&d What would you like this car to be called?"); + this.addDefault("CarType.Create.StartMaxSpeed", "&d What should the Car's Start Speed be?\n&a (default = 60.0)"); + this.addDefault("CarType.Create.MaxUpgradeSpeed", "&d What should the Car's Max Upgrade Speed be?\n&a (default = 120.0)"); + this.addDefault("CarType.Create.Acceleration", "&d What should the Car's Acceleration be?\n&a (default = 1.0)"); + this.addDefault("CarType.Create.FuelUsage", "&d What should the Fuel Usage be?\n&a (default = 1.0)"); + this.addDefault("CarType.Create.FillMaterial", "&d What should the Fill Material be?\n&a (default = AIR)"); + this.addDefault("CarType.Create.Cost", "&d How much should the car cost?\n&a (default = 10.0)"); + this.addDefault("CarType.Create.Success", "&d All done, &a%VALUE% &dcreated."); + this.addDefault("CarType.Error.InvalidName", "Invalid Car Type name."); + this.addDefault("CarType.Error.InvalidValue", "Invalid Value."); + this.addDefault("CarType.Error.AlreadyExists", "This Car Type already exists."); + + this.addDefault("BlockTypes.Added.List", "&b%MATERIAL% &7added to &b%TYPE% &7blocks."); + this.addDefault("BlockTypes.Added.Amount", "&b%MATERIAL% &7added to &b%TYPE% &7blocks, with an amount of &b%AMOUNT%&7."); + this.addDefault("BlockTypes.Removed", "&b%MATERIAL% &7removed from &b%TYPE% &7blocks."); + + this.addDefault("Error.NoPermission", "You do not have permission: &b%PERMISSION%"); + this.addDefault("Error.SignProtected", "This sign is protected."); + this.addDefault("Error.UnknownCommand", "Unknown Command."); + this.addDefault("Error.UnknownSignCommand", "Unknown Sign Command."); + this.addDefault("Error.CommandDisabled", "This command has been disabled."); + this.addDefault("Error.InCar", "You are already in a car."); + this.addDefault("Error.NotInCar", "You are not in a car."); + this.addDefault("Error.HaveCar", "You already have a car."); + this.addDefault("Error.FuelDisabled", "Fuel is disabled."); + this.addDefault("Error.PurchaseFailed", "Purchase failed. Cost: %COST%"); + this.addDefault("Error.FullyUpgraded", "Your car is already fully upgraded."); + this.addDefault("Error.Owned", "This car is owned by %PLAYER%!"); + this.addDefault("Error.UnknownCarType", "Unknown car type."); + this.addDefault("Error.UnknownPlayer", "Unknown player."); + this.addDefault("Error.UnknownMaterial", "Unknown Material: "); + this.addDefault("Error.SpecifyPlayer", "Please specify a player."); + this.addDefault("Error.PurchaseOutstanding", "You have an outstanding purchase."); + this.addDefault("Error.NoPurchaseOutstanding", "You don't have an outstanding purchase."); + this.addDefault("Error.CarNotDriven", "This can hasn't been driven yet."); + this.addDefault("Error.TooManyArgs", "Too many arguments."); + this.addDefault("Error.NotEnoughArgs", "Not enough arguments."); + this.addDefault("Error.OwnedCarsLimit", "You have reached the amount of Owned cars you can place."); + this.addDefault("Error.InvalidPlaceableMaterial", "You are unable to place a Car here."); + this.addDefault("Error.InvalidNumber", "%VALUE% is not a valid number."); + + this.addDefault("Error.BlockTypes.Invalid", "Invalid Block Type."); + this.addDefault("Error.BlockTypes.AlreadyExists", "%MATERIAL% is already a %TYPE% block."); + this.addDefault("Error.BlockTypes.SpecifyAmount", "Invalid Syntax: /carz add %TYPE% (amount)"); + + this.options().copyDefaults(true); + } + +} diff --git a/src/main/java/io/github/a5h73y/carz/controllers/CarController.java b/src/main/java/io/github/a5h73y/carz/controllers/CarController.java index 3030726..a12bf84 100644 --- a/src/main/java/io/github/a5h73y/carz/controllers/CarController.java +++ b/src/main/java/io/github/a5h73y/carz/controllers/CarController.java @@ -238,7 +238,7 @@ private void upgradeCarSpeed(Minecart vehicle) { Car car = getCar(vehicle.getEntityId()); double currentMax = car.getMaxSpeed(); double maxSpeed = car.getCarDetails().getMaxUpgradeSpeed(); - double upgradeAmount = carz.getSettings().getUpgradeIncrement(); + double upgradeAmount = Carz.getDefaultConfig().getUpgradeIncrement(); if ((currentMax + upgradeAmount) > maxSpeed) { return; diff --git a/src/main/java/io/github/a5h73y/carz/enums/BlockType.java b/src/main/java/io/github/a5h73y/carz/enums/BlockType.java new file mode 100644 index 0000000..995123b --- /dev/null +++ b/src/main/java/io/github/a5h73y/carz/enums/BlockType.java @@ -0,0 +1,30 @@ +package io.github.a5h73y.carz.enums; + +/** + * Each type of Carz block. + * Each can be configured to be enabled / disabled. + */ +public enum BlockType { + + CLIMB("ClimbBlocks", false), + PLACEABLE("PlaceableBlocks", false), + + SPEED("SpeedBlocks", true), + LAUNCH("LaunchBlocks", true); + + private final String configPath; + private final boolean hasAmount; + + BlockType(String configPath, boolean hasAmount) { + this.configPath = configPath; + this.hasAmount = hasAmount; + } + + public String getConfigPath() { + return configPath; + } + + public boolean isHasAmount() { + return hasAmount; + } +} diff --git a/src/main/java/io/github/a5h73y/carz/enums/ConfigType.java b/src/main/java/io/github/a5h73y/carz/enums/ConfigType.java new file mode 100644 index 0000000..9923b44 --- /dev/null +++ b/src/main/java/io/github/a5h73y/carz/enums/ConfigType.java @@ -0,0 +1,7 @@ +package io.github.a5h73y.carz.enums; + +public enum ConfigType { + DEFAULT, + STRINGS, + BLOCKS +} diff --git a/src/main/java/io/github/a5h73y/carz/listeners/PlayerListener.java b/src/main/java/io/github/a5h73y/carz/listeners/PlayerListener.java index f9ab463..a4550da 100644 --- a/src/main/java/io/github/a5h73y/carz/listeners/PlayerListener.java +++ b/src/main/java/io/github/a5h73y/carz/listeners/PlayerListener.java @@ -2,12 +2,10 @@ import io.github.a5h73y.carz.Carz; import io.github.a5h73y.carz.controllers.CarController; -import io.github.a5h73y.carz.enums.Permissions; import io.github.a5h73y.carz.other.AbstractPluginReceiver; -import io.github.a5h73y.carz.other.DelayTasks; -import io.github.a5h73y.carz.utility.PermissionUtils; import io.github.a5h73y.carz.utility.PlayerUtils; import io.github.a5h73y.carz.utility.TranslationUtils; +import io.github.a5h73y.carz.utility.ValidationUtils; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; @@ -42,8 +40,7 @@ public PlayerListener(Carz carz) { */ @EventHandler public void onPlaceMinecart(PlayerInteractEvent event) { - if (!event.getAction().equals(Action.RIGHT_CLICK_AIR) - && !event.getAction().equals(Action.RIGHT_CLICK_BLOCK)) { + if (!event.getAction().equals(Action.RIGHT_CLICK_BLOCK)) { return; } @@ -59,7 +56,7 @@ public void onPlaceMinecart(PlayerInteractEvent event) { Player player = event.getPlayer(); - if (!PermissionUtils.hasPermission(player, Permissions.PLACE)) { + if (!ValidationUtils.canPlaceCar(player, event.getClickedBlock().getType())) { return; } @@ -67,18 +64,13 @@ public void onPlaceMinecart(PlayerInteractEvent event) { // if only owned cars can drive and it doesn't have a vehicle type, ignore it. if (!carz.getItemMetaUtils().has(VEHICLE_TYPE, carInHand)) { - if (carz.getSettings().isOnlyOwnedCarsDrive()) { + if (Carz.getDefaultConfig().isOnlyOwnedCarsDrive()) { return; } carz.getItemMetaUtils().setValue(VEHICLE_TYPE, carInHand, CarController.DEFAULT_CAR); } - // prevent the player from creating mass amounts of Minecarts - if (!DelayTasks.getInstance().delayPlayer(player, 3)) { - return; - } - // if the Minecart has an owner if (carz.getItemMetaUtils().has(VEHICLE_OWNER, carInHand)) { String owner = carz.getItemMetaUtils().getValue(VEHICLE_OWNER, carInHand); diff --git a/src/main/java/io/github/a5h73y/carz/listeners/SignListener.java b/src/main/java/io/github/a5h73y/carz/listeners/SignListener.java index 30aef5d..39eac9e 100644 --- a/src/main/java/io/github/a5h73y/carz/listeners/SignListener.java +++ b/src/main/java/io/github/a5h73y/carz/listeners/SignListener.java @@ -41,7 +41,7 @@ public SignListener(Carz carz) { */ @EventHandler public void onSignCreate(SignChangeEvent event) { - if (!carz.getSettings().getStrippedSignHeader().equalsIgnoreCase(event.getLine(0))) { + if (!Carz.getDefaultConfig().getStrippedSignHeader().equalsIgnoreCase(event.getLine(0))) { return; } @@ -85,7 +85,7 @@ public void onSignCreate(SignChangeEvent event) { String title = StringUtils.standardizeText(event.getLine(1)); player.sendMessage(TranslationUtils.getTranslation("Carz.SignCreated") .replace("%TYPE%", title)); - event.setLine(0, carz.getSettings().getSignHeader()); + event.setLine(0, Carz.getDefaultConfig().getSignHeader()); } /** @@ -111,7 +111,7 @@ public void onSignBreak(PlayerInteractEvent event) { String[] lines = ((Sign) event.getClickedBlock().getState()).getLines(); - if (!ChatColor.stripColor(lines[0]).equalsIgnoreCase(carz.getSettings().getStrippedSignHeader())) { + if (!ChatColor.stripColor(lines[0]).equalsIgnoreCase(Carz.getDefaultConfig().getStrippedSignHeader())) { return; } @@ -145,7 +145,7 @@ public void onSignInteract(PlayerInteractEvent event) { Sign sign = (Sign) event.getClickedBlock().getState(); String[] lines = sign.getLines(); - if (!ChatColor.stripColor(lines[0]).equalsIgnoreCase(carz.getSettings().getStrippedSignHeader())) { + if (!ChatColor.stripColor(lines[0]).equalsIgnoreCase(Carz.getDefaultConfig().getStrippedSignHeader())) { return; } diff --git a/src/main/java/io/github/a5h73y/carz/listeners/VehicleListener.java b/src/main/java/io/github/a5h73y/carz/listeners/VehicleListener.java index 17988c8..8ac134e 100644 --- a/src/main/java/io/github/a5h73y/carz/listeners/VehicleListener.java +++ b/src/main/java/io/github/a5h73y/carz/listeners/VehicleListener.java @@ -1,6 +1,7 @@ package io.github.a5h73y.carz.listeners; import io.github.a5h73y.carz.Carz; +import io.github.a5h73y.carz.configuration.impl.BlocksConfig; import io.github.a5h73y.carz.enums.Permissions; import io.github.a5h73y.carz.event.EngineStartEvent; import io.github.a5h73y.carz.event.EngineStopEvent; @@ -33,6 +34,7 @@ import org.bukkit.event.vehicle.VehicleUpdateEvent; import org.bukkit.util.Vector; +import static io.github.a5h73y.carz.enums.ConfigType.BLOCKS; import static io.github.a5h73y.carz.enums.VehicleDetailKey.VEHICLE_FUEL; import static io.github.a5h73y.carz.enums.VehicleDetailKey.VEHICLE_LOCKED; import static io.github.a5h73y.carz.enums.VehicleDetailKey.VEHICLE_OWNER; @@ -71,7 +73,7 @@ public void onVehicleEnter(VehicleEnterEvent event) { Player player = (Player) event.getEntered(); - if (!carz.getSettings().isAutomaticCarLock() && player.isSneaking()) { + if (!Carz.getDefaultConfig().isAutomaticCarLock() && player.isSneaking()) { return; } @@ -97,7 +99,7 @@ public void onVehicleEnter(VehicleEnterEvent event) { carz.getItemMetaUtils().remove(VEHICLE_LOCKED, minecart); TranslationUtils.sendTranslation("Car.CarUnlocked", player); } - } else if (carz.getSettings().isOnlyOwnedCarsDrive()) { + } else if (Carz.getDefaultConfig().isOnlyOwnedCarsDrive()) { return; } @@ -106,7 +108,7 @@ public void onVehicleEnter(VehicleEnterEvent event) { } if (carz.getConfig().getBoolean("Key.GiveOnCarEnter") - && !player.getInventory().contains(carz.getSettings().getKey())) { + && !player.getInventory().contains(Carz.getDefaultConfig().getKey())) { CarUtils.givePlayerKey(player); } } @@ -146,12 +148,12 @@ public void onEngineToggle(PlayerInteractEvent event) { Car car = carz.getCarController().getCar(vehicle.getEntityId()); - if (carz.getSettings().isOnlyOwnedCarsDrive() && !carz.getItemMetaUtils().has(VEHICLE_OWNER, vehicle)) { + if (Carz.getDefaultConfig().isOnlyOwnedCarsDrive() && !carz.getItemMetaUtils().has(VEHICLE_OWNER, vehicle)) { return; } if (carz.getConfig().getBoolean("Key.RequireCarzKey") - && PlayerUtils.getMaterialInPlayersHand(event.getPlayer()) != carz.getSettings().getKey()) { + && PlayerUtils.getMaterialInPlayersHand(event.getPlayer()) != Carz.getDefaultConfig().getKey()) { return; } @@ -202,14 +204,14 @@ public void onVehicleUpdate(VehicleUpdateEvent event) { } if (event.getVehicle().getLocation().getBlock().isLiquid() - && carz.getSettings().isDestroyInLiquid()) { + && Carz.getDefaultConfig().isDestroyInLiquid()) { carz.getCarController().destroyCar(event.getVehicle()); player.playEffect(player.getLocation(), Effect.EXTINGUISH, null); TranslationUtils.sendTranslation("Car.LiquidDamage", player); return; } - if (event.getVehicle().getFallDistance() > 1F && !carz.getSettings().isControlCarsWhileFalling()) { + if (event.getVehicle().getFallDistance() > 1F && !Carz.getDefaultConfig().isControlCarsWhileFalling()) { return; } @@ -228,12 +230,18 @@ public void onVehicleUpdate(VehicleUpdateEvent event) { Vector vehicleVelocity = event.getVehicle().getVelocity(); Vector playerLocationVelocity = player.getLocation().getDirection(); Material materialBelow = event.getVehicle().getLocation().subtract(0.0D, 1.0D, 0.0D).getBlock().getType(); + BlocksConfig blocksConfig = (BlocksConfig) Carz.getConfig(BLOCKS); - if (carz.getSettings().containsSpeedBlock(materialBelow)) { - Double modifier = carz.getSettings().getSpeedModifier(materialBelow); + if (blocksConfig.containsSpeedBlock(materialBelow)) { + Double modifier = blocksConfig.getSpeedModifier(materialBelow); drivingCar.applySpeedModifier(modifier); } + if (blocksConfig.containsLaunchBlock(materialBelow)) { + Double amount = blocksConfig.getLaunchAmount(materialBelow); + vehicleVelocity.setY(vehicleVelocity.getY() + amount); + } + double carSpeed = drivingCar.getCurrentSpeed(); vehicleVelocity.setX((playerLocationVelocity.getX() / 100.0) * carSpeed); @@ -245,9 +253,12 @@ public void onVehicleUpdate(VehicleUpdateEvent event) { Location twoBlocksAhead = playerLocation.add(playerLocation.getDirection().multiply(2)); twoBlocksAhead.setY(Math.max(playerLocation.getY() + 1, twoBlocksAhead.getY())); + boolean isClimbable = twoBlocksAhead.getBlock().getType() != Material.AIR + && ((blocksConfig.getClimbBlocks().isEmpty() || twoBlocksAhead.getBlock().getBlockData() instanceof Slab) + || blocksConfig.getClimbBlocks().contains(twoBlocksAhead.getBlock().getType())); + // if there is a block ahead of us - if (twoBlocksAhead.getBlock().getType() != Material.AIR - || twoBlocksAhead.getBlock().getBlockData() instanceof Slab) { + if (isClimbable && materialBelow != Material.AIR) { Location above = twoBlocksAhead.add(0, 1, 0); // if the block above it is AIR, allow to climb @@ -331,7 +342,7 @@ public void onVehicleExit(VehicleExitEvent event) { TranslationUtils.sendTranslation("Car.EngineStop", player); } - if (carz.getSettings().isAutomaticCarLock() + if (Carz.getDefaultConfig().isAutomaticCarLock() && carz.getItemMetaUtils().has(VEHICLE_OWNER, vehicle) && player.getName().equals(carz.getItemMetaUtils().getValue(VEHICLE_OWNER, vehicle))) { carz.getItemMetaUtils().setValue(VEHICLE_LOCKED, vehicle, "true"); @@ -406,7 +417,7 @@ public void onCarLockToggle(PlayerInteractEntityEvent event) { return; } - if (PlayerUtils.getMaterialInPlayersHand(event.getPlayer()) != carz.getSettings().getKey()) { + if (PlayerUtils.getMaterialInPlayersHand(event.getPlayer()) != Carz.getDefaultConfig().getKey()) { return; } diff --git a/src/main/java/io/github/a5h73y/carz/plugin/EconomyAPI.java b/src/main/java/io/github/a5h73y/carz/plugin/EconomyAPI.java index e8203b1..0a028d1 100644 --- a/src/main/java/io/github/a5h73y/carz/plugin/EconomyAPI.java +++ b/src/main/java/io/github/a5h73y/carz/plugin/EconomyAPI.java @@ -209,7 +209,7 @@ private boolean purchase(Player player, double cost) { public double getRefuelCost(double remainingFuel) { double cost = Carz.getInstance().getConfig().getDouble("Vault.Cost.Refuel"); - if (Carz.getInstance().getSettings().isFuelScaleCost()) { + if (Carz.getDefaultConfig().isFuelScaleCost()) { cost *= Carz.getInstance().getFuelController().determineScaleOfCostMultiplier(remainingFuel); } diff --git a/src/main/java/io/github/a5h73y/carz/purchases/UpgradePurchase.java b/src/main/java/io/github/a5h73y/carz/purchases/UpgradePurchase.java index f7bda14..618d556 100644 --- a/src/main/java/io/github/a5h73y/carz/purchases/UpgradePurchase.java +++ b/src/main/java/io/github/a5h73y/carz/purchases/UpgradePurchase.java @@ -22,7 +22,7 @@ public class UpgradePurchase extends Purchasable { * @param currentCar car */ public UpgradePurchase(Car currentCar) { - double upgradeAmount = Carz.getInstance().getSettings().getUpgradeIncrement(); + double upgradeAmount = Carz.getDefaultConfig().getUpgradeIncrement(); previousTopSpeed = currentCar.getMaxSpeed(); newTopSpeed = currentCar.getMaxSpeed() + upgradeAmount; } diff --git a/src/main/java/io/github/a5h73y/carz/utility/CarUtils.java b/src/main/java/io/github/a5h73y/carz/utility/CarUtils.java index 8b722b4..8fa2b5c 100644 --- a/src/main/java/io/github/a5h73y/carz/utility/CarUtils.java +++ b/src/main/java/io/github/a5h73y/carz/utility/CarUtils.java @@ -5,10 +5,8 @@ import org.bukkit.Material; import org.bukkit.World; import org.bukkit.enchantments.Enchantment; -import org.bukkit.entity.Entity; import org.bukkit.entity.Minecart; import org.bukkit.entity.Player; -import org.bukkit.entity.Vehicle; import org.bukkit.inventory.ItemFlag; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; @@ -26,14 +24,32 @@ public class CarUtils { */ public static void destroyAllCars() { for (World world : Bukkit.getWorlds()) { - for (Entity entity : world.getEntities()) { - if (entity instanceof Minecart) { - Carz.getInstance().getCarController().removeCar((Vehicle) entity); - } + for (Minecart entity : world.getEntitiesByClass(Minecart.class)) { + Carz.getInstance().getCarController().removeCar(entity); } } } + /** + * Get the number of owned Minecart entities for the player. + * + * @param player requesting player + * @return player owned minecarts + */ + public static int numberOfOwnedCars(Player player) { + int number = 0; + + ItemMetaUtils itemMetaUtils = Carz.getInstance().getItemMetaUtils(); + for (Minecart vehicle : player.getWorld().getEntitiesByClass(Minecart.class)) { + if (itemMetaUtils.has(VEHICLE_OWNER, vehicle) + && itemMetaUtils.getValue(VEHICLE_OWNER, vehicle).equals(player.getName())) { + number++; + } + } + + return number; + } + /** * Place a Car (Minecart) of the specified type in the player's inventory. * The car will not have an owner. @@ -126,7 +142,7 @@ public static void setOwnerDisplayName(ItemStack itemStack, String playerName) { * @param player target player */ public static void givePlayerKey(Player player) { - ItemStack itemStack = new ItemStack(Carz.getInstance().getSettings().getKey()); + ItemStack itemStack = new ItemStack(Carz.getDefaultConfig().getKey()); String keyName = TranslationUtils.getTranslation("Car.Key.Display", false) .replace("%PLAYER%", player.getName()); diff --git a/src/main/java/io/github/a5h73y/carz/utility/PluginUtils.java b/src/main/java/io/github/a5h73y/carz/utility/PluginUtils.java index a3c0944..fbf56cf 100644 --- a/src/main/java/io/github/a5h73y/carz/utility/PluginUtils.java +++ b/src/main/java/io/github/a5h73y/carz/utility/PluginUtils.java @@ -5,10 +5,12 @@ import java.util.Set; import io.github.a5h73y.carz.Carz; +import io.github.a5h73y.carz.configuration.impl.BlocksConfig; +import io.github.a5h73y.carz.enums.BlockType; import io.github.a5h73y.carz.enums.Commands; +import io.github.a5h73y.carz.enums.ConfigType; import org.bukkit.Material; import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; /** * Plugin related utility methods. @@ -34,7 +36,28 @@ public static boolean commandEnabled(CommandSender sender, Commands command) { } /** - * Used for logging plugin events, varying in severity. + * Validate the range of the arguments before allowing it to be processed further. + * + * @param sender command sender + * @param args command arguments + * @param minimum minimum args length + * @param maximum maximum args length + * @return whether the arguments match the criteria + */ + public static boolean validateArgs(CommandSender sender, String[] args, int minimum, int maximum) { + if (args.length < minimum) { + sender.sendMessage(TranslationUtils.getTranslation("Error.NotEnoughArgs") + " (between " + minimum + " and " + maximum + ")"); + return false; + + } else if (args.length > maximum) { + sender.sendMessage(TranslationUtils.getTranslation("Error.TooManyArgs") + " (between " + minimum + " and " + maximum + ")"); + return false; + } + return true; + } + + /** + * Log plugin events, varying in severity. * 0 - Info; 1 - Warn; 2 - Severe. * * @param message log message @@ -55,6 +78,11 @@ public static void log(String message, int severity) { } } + /** + * Log plugin info message. + * + * @param message log message + */ public static void log(String message) { log(message, 0); } @@ -79,118 +107,120 @@ public static Set convertToValidMaterials(Collection rawMateri return validMaterials; } - /** - * Add a ClimbBlock to the configured list. - * - * @param player player requesting - * @param args command arguments - */ - public static void addClimbBlock(CommandSender player, String[] args) { - if (args.length < 2) { - player.sendMessage(Carz.getPrefix() + "Invalid syntax: /carz addcb (material)"); + public static void addBlockType(CommandSender player, String[] args) { + BlockType chosenType = extractBlockType(args[1].toLowerCase()); + + if (chosenType == null) { + TranslationUtils.sendTranslation("Error.BlockTypes.Invalid", player); return; } - Material material = Material.getMaterial(args[1].toUpperCase()); + Material material = Material.getMaterial(args[2].toUpperCase()); + String chosenTypeName = StringUtils.standardizeText(chosenType.name()); + BlocksConfig config = (BlocksConfig) Carz.getConfig(ConfigType.BLOCKS); if (material == null) { - player.sendMessage(Carz.getPrefix() + args[1] + " is not a valid Material!"); + player.sendMessage(TranslationUtils.getTranslation("Error.UnknownMaterial") + args[2]); return; } - if (Carz.getInstance().getSettings().getClimbBlocks().contains(material)) { - player.sendMessage(Carz.getPrefix() + args[1] + " is already a climb block!"); + if (config.alreadyExists(chosenType, material)) { + player.sendMessage(TranslationUtils.getTranslation("Error.BlockTypes.AlreadyExists") + .replace("%MATERIAL%", material.name()) + .replace("%TYPE%", chosenTypeName)); return; } - Carz.getInstance().getSettings().addClimbBlock(material); - player.sendMessage(Carz.getPrefix() + material.name() + " added to ClimbBlocks!"); - } + if (chosenType.isHasAmount()) { + if (args.length != 4) { + player.sendMessage(TranslationUtils.getTranslation("Error.BlockTypes.SpecifyAmount") + .replace("%TYPE%", chosenTypeName)); + return; + } - /** - * Remove a ClimbBlock from the configured list. - * - * @param player player requesting - * @param args command arguments - */ - public static void removeClimbBlock(CommandSender player, String[] args) { - if (args.length < 2) { - player.sendMessage(Carz.getPrefix() + "Invalid syntax: /carz removeclimb (material)"); - return; - } + if (!ValidationUtils.isDouble(args[3])) { + player.sendMessage(TranslationUtils.getTranslation("Error.InvalidNumber") + .replace("%VALUE%", args[3])); + return; + } - Material material = Material.getMaterial(args[1].toUpperCase()); + double amount = Double.parseDouble(args[3]); - if (material == null || !Carz.getInstance().getSettings().getClimbBlocks().contains(material)) { - player.sendMessage(Carz.getPrefix() + args[1] + " is not a climb block!"); - return; - } + if (amount < 0 || amount > 100) { + player.sendMessage(Carz.getPrefix() + "Invalid Amount."); + player.sendMessage(Carz.getPrefix() + "If you are sure this is what you want, edit the blocks.yml file manually."); + return; + } - Carz.getInstance().getSettings().removeClimbBlock(material); - player.sendMessage(Carz.getPrefix() + material.name() + " removed from climb blocks!"); + config.setBlock(chosenType, material, amount); + player.sendMessage(TranslationUtils.getTranslation("BlockTypes.Added.Amount") + .replace("%MATERIAL%", material.name()) + .replace("%TYPE%", chosenTypeName) + .replace("%AMOUNT%", String.valueOf(amount))); + + } else { + config.addBlock(chosenType, material); + player.sendMessage(TranslationUtils.getTranslation("BlockTypes.Added.List") + .replace("%MATERIAL%", material.name()) + .replace("%TYPE%", chosenTypeName)); + } } - /** - * Add a SpeedBlock to the configured list. - * - * @param player player requesting - * @param args command arguments - */ - public static void addSpeedBlock(CommandSender player, String[] args) { - if (args.length < 3) { - player.sendMessage(Carz.getPrefix() + "Invalid syntax: /carz addspeed (material) (speed)"); + public static void removeBlockType(CommandSender player, String[] args) { + BlockType chosenType = extractBlockType(args[1].toLowerCase()); + + if (chosenType == null) { + player.sendMessage("Invalid."); return; } - Material material = Material.getMaterial(args[1].toUpperCase()); + Material material = Material.getMaterial(args[2].toUpperCase()); + String chosenTypeName = StringUtils.standardizeText(chosenType.name()); + BlocksConfig config = (BlocksConfig) Carz.getConfig(ConfigType.BLOCKS); if (material == null) { - player.sendMessage(Carz.getPrefix() + args[1] + " is not a valid Material!"); + player.sendMessage(TranslationUtils.getTranslation("Error.UnknownMaterial") + args[2]); return; } - if (Carz.getInstance().getSettings().getSpeedBlocks().contains(material.name())) { - player.sendMessage(Carz.getPrefix() + args[1] + " is already a speed block!"); + if (!config.alreadyExists(chosenType, material)) { + player.sendMessage(material.name() + " isn't a " + chosenTypeName + " block."); return; } - if (!ValidationUtils.isDouble(args[2])) { - player.sendMessage(Carz.getPrefix() + args[2] + " is not a valid number!"); - return; - } - - double speed = Double.parseDouble(args[2]); + if (chosenType.isHasAmount()) { + config.setBlock(chosenType, material, null); - if (speed < 0 || speed > 100) { - player.sendMessage(Carz.getPrefix() + "Invalid Speed Modifier."); - player.sendMessage(Carz.getPrefix() + "If you are sure this is what you want, edit the config.yml file manually."); - return; + } else { + config.removeBlock(chosenType, material); } - Carz.getInstance().getSettings().addSpeedBlock(material, speed); - player.sendMessage(Carz.getPrefix() + material.name() + " added as a speed block!"); + player.sendMessage(TranslationUtils.getTranslation("BlockTypes.Removed") + .replace("%MATERIAL%", material.name()) + .replace("%TYPE%", chosenTypeName)); } - /** - * Remove a SpeedBlock from the configured list. - * - * @param player player requesting - * @param args command arguments - */ - public static void removeSpeedBlock(CommandSender player, String[] args) { - if (args.length < 2) { - player.sendMessage(Carz.getPrefix() + "Invalid syntax: /carz removespeed (material)"); - return; - } + private static BlockType extractBlockType(String command) { + BlockType chosenType = null; - Material material = Material.getMaterial(args[1].toUpperCase()); + switch (command) { + case "climb": + chosenType = BlockType.CLIMB; + break; - if (material == null || !Carz.getInstance().getSettings().getSpeedBlocks().contains(args[1].toUpperCase())) { - player.sendMessage(Carz.getPrefix() + args[1] + " is not a speed block!"); - return; - } + case "placeable": + chosenType = BlockType.PLACEABLE; + break; + + case "launch": + chosenType = BlockType.LAUNCH; + break; - Carz.getInstance().getSettings().removeSpeedBlock(material); - player.sendMessage(Carz.getPrefix() + material.name() + " removed from speed blocks!"); + case "speed": + chosenType = BlockType.SPEED; + break; + + } + return chosenType; } } diff --git a/src/main/java/io/github/a5h73y/carz/utility/TranslationUtils.java b/src/main/java/io/github/a5h73y/carz/utility/TranslationUtils.java index 1e15555..3aafaf2 100644 --- a/src/main/java/io/github/a5h73y/carz/utility/TranslationUtils.java +++ b/src/main/java/io/github/a5h73y/carz/utility/TranslationUtils.java @@ -1,6 +1,7 @@ package io.github.a5h73y.carz.utility; import io.github.a5h73y.carz.Carz; +import io.github.a5h73y.carz.enums.ConfigType; import org.bukkit.command.CommandSender; import static io.github.a5h73y.carz.utility.StringUtils.colour; @@ -24,7 +25,7 @@ public static String getTranslation(String translationKey, boolean prefix) { return "Invalid translation."; } - String translated = Carz.getInstance().getSettings().getStringsConfig().getString(translationKey); + String translated = Carz.getConfig(ConfigType.STRINGS).getString(translationKey); translated = translated != null ? colour(translated) : "String not found: " + translationKey; return prefix ? Carz.getPrefix().concat(translated) : translated; } diff --git a/src/main/java/io/github/a5h73y/carz/utility/ValidationUtils.java b/src/main/java/io/github/a5h73y/carz/utility/ValidationUtils.java index 4fecf5d..e47ab1b 100644 --- a/src/main/java/io/github/a5h73y/carz/utility/ValidationUtils.java +++ b/src/main/java/io/github/a5h73y/carz/utility/ValidationUtils.java @@ -1,9 +1,12 @@ package io.github.a5h73y.carz.utility; import io.github.a5h73y.carz.Carz; +import io.github.a5h73y.carz.configuration.impl.BlocksConfig; +import io.github.a5h73y.carz.enums.ConfigType; import io.github.a5h73y.carz.enums.Permissions; import io.github.a5h73y.carz.enums.VehicleDetailKey; import io.github.a5h73y.carz.model.Car; +import io.github.a5h73y.carz.other.DelayTasks; import org.bukkit.Material; import org.bukkit.block.data.Rail; import org.bukkit.entity.Minecart; @@ -153,7 +156,7 @@ public static boolean canPurchaseUpgrade(Player player, boolean checkEconomy) { Car currentCar = Carz.getInstance().getCarController().getCar(player.getVehicle().getEntityId()); - if (currentCar.getMaxSpeed() >= Carz.getInstance().getSettings().getUpgradeMaxSpeed()) { + if (currentCar.getMaxSpeed() >= Carz.getDefaultConfig().getUpgradeMaxSpeed()) { TranslationUtils.sendTranslation("Error.FullyUpgraded", player); return false; } @@ -234,4 +237,39 @@ public static boolean canClaimCar(Player player) { return true; } + + /** + * Validate if the player is currently able to place a car. + * There is no permission node to claim a car. + * + * @param player target player + * @param placedMaterial material to place upon + * @return player can claim car + */ + public static boolean canPlaceCar(Player player, Material placedMaterial) { + if (!PermissionUtils.hasPermission(player, Permissions.PLACE)) { + return false; + } + + // prevent the player from creating mass amounts of Minecarts + if (!DelayTasks.getInstance().delayPlayer(player, 3)) { + return false; + } + + BlocksConfig blocksConfig = (BlocksConfig) Carz.getConfig(ConfigType.BLOCKS); + if (!blocksConfig.getPlaceableBlocks().isEmpty() + && !blocksConfig.getPlaceableBlocks().contains(placedMaterial)) { + TranslationUtils.sendTranslation("Error.InvalidPlaceableMaterial", player); + return false; + } + + int maxOwnedCars = Carz.getDefaultConfig().getMaxPlayerOwnedCars(); + if (maxOwnedCars > 0 + && CarUtils.numberOfOwnedCars(player) >= maxOwnedCars) { + TranslationUtils.sendTranslation("Error.OwnedCarsLimit", player); + return false; + } + + return true; + } }