1
0
mirror of https://github.com/nkomarn/harbor.git synced 2024-11-16 07:05:22 +01:00

Merge pull request #36 from rolandvonrotz/master

Add bed enter/leave events with messages & add time skip interval to config
This commit is contained in:
Mykyta 2019-10-08 06:48:26 -07:00 committed by GitHub
commit 3500efa178
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
8 changed files with 210 additions and 170 deletions

View File

@ -4,6 +4,7 @@ import com.earth2me.essentials.Essentials;
import org.bukkit.Bukkit;
import org.bukkit.plugin.java.JavaPlugin;
import xyz.nkomarn.Harbor.command.HarborCommand;
import xyz.nkomarn.Harbor.listener.PlayerListener;
import xyz.nkomarn.Harbor.task.Checker;
import xyz.nkomarn.Harbor.util.Config;
import xyz.nkomarn.Harbor.util.Metrics;
@ -23,6 +24,7 @@ public class Harbor extends JavaPlugin {
}
getCommand("harbor").setExecutor(new HarborCommand());
getServer().getPluginManager().registerEvents(new PlayerListener(), this);
// bStats
final Metrics metrics = new Metrics(this);
@ -30,9 +32,4 @@ public class Harbor extends JavaPlugin {
// Essentials hook
essentials = (Essentials) Bukkit.getServer().getPluginManager().getPlugin("Essentials");
}
public void onDisable() {
}
}

View File

@ -1,23 +1,24 @@
package xyz.nkomarn.Harbor.command;
import org.bukkit.World;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import xyz.nkomarn.Harbor.Harbor;
import xyz.nkomarn.Harbor.util.Updater;
public class HarborCommand implements CommandExecutor {
int changeTimeTask = 0;
@Override
public boolean onCommand(final CommandSender commandSender, final Command command, final String s, final String[] strings) {
final Player player = (Player) commandSender;
final World world = player.getWorld();
//Updater.check();
//Updater.upgrade();
public boolean onCommand(final CommandSender sender, final Command command, final String label, final String[] args) {
if (args.length == 1 && "reload".equalsIgnoreCase(args[0]) && sender.hasPermission("harbor.reload")) {
Harbor.instance.reloadConfig();
sender.sendMessage("§1[Harbor]: §2 Reloaded");
}
return true;
}
private void checkForUpdate() {
Updater.check();
Updater.upgrade();
}
}

View File

@ -0,0 +1,39 @@
package xyz.nkomarn.Harbor.listener;
import org.bukkit.World;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerBedEnterEvent;
import org.bukkit.event.player.PlayerBedLeaveEvent;
import xyz.nkomarn.Harbor.task.Checker;
import xyz.nkomarn.Harbor.util.Message;
public class PlayerListener implements Listener {
@EventHandler(priority = EventPriority.HIGH)
public void onBedEnter(final PlayerBedEnterEvent event) {
if (event.getBedEnterResult() != PlayerBedEnterEvent.BedEnterResult.OK) {
return;
}
final World world = event.getPlayer().getWorld();
if (morePlayerNeeded(world, 1)) {
Message.SendChatMessage(world, "messages.chat.sleeping", event.getPlayer().getDisplayName(), 1);
Message.SendActionbarMessage(world, "messages.actionbar.sleeping", event.getPlayer().getDisplayName(), 1);
}
}
@EventHandler(priority = EventPriority.HIGH)
public void onBedLeave(final PlayerBedLeaveEvent event) {
final World world = event.getPlayer().getWorld();
if (Checker.isNight(world) && !Checker.skippingWorlds.contains(world) && morePlayerNeeded(world, 0)) {
Message.SendChatMessage(world, "messages.chat.left", event.getPlayer().getDisplayName(), 0);
}
}
private boolean morePlayerNeeded(final World world, final int change) {
final int sleeping = Checker.getSleeping(world) + change;
final int needed = Checker.getNeeded(world) - change;
return sleeping > 0 && needed > 0;
}
}

View File

@ -0,0 +1,40 @@
package xyz.nkomarn.Harbor.task;
import org.bukkit.Statistic;
import org.bukkit.World;
import org.bukkit.scheduler.BukkitRunnable;
import xyz.nkomarn.Harbor.util.Config;
import xyz.nkomarn.Harbor.util.Message;
public class AccelerateNightTask extends BukkitRunnable {
private final World world;
public AccelerateNightTask(final World world) {
this.world = world;
}
@Override
public void run() {
final long time = world.getTime();
if (!(time >= 450 && time <= 1000)) {
world.setTime(time + Config.getInteger("values.timeSkipInterval"));
} else {
// Announce night skip and clear queue
Message.SendRandomChatMessage(world, "messages.chat.skipped");
Checker.skippingWorlds.remove(world);
// Reset sleep statistic if phantoms are disabled
if (!Config.getBoolean("features.phantoms")) {
world.getPlayers().forEach(player -> player.setStatistic(Statistic.TIME_SINCE_REST, 0));
}
// Clear weather
if (Config.getBoolean("features.weather")) {
world.setStorm(false);
world.setThundering(false);
}
this.cancel();
}
}
}

View File

@ -1,22 +1,21 @@
package xyz.nkomarn.Harbor.task;
import net.md_5.bungee.api.ChatMessageType;
import net.md_5.bungee.api.chat.TextComponent;
import org.bukkit.*;
import org.bukkit.Bukkit;
import org.bukkit.GameMode;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;
import xyz.nkomarn.Harbor.Harbor;
import xyz.nkomarn.Harbor.util.Config;
import xyz.nkomarn.Harbor.util.Message;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import static java.util.stream.Collectors.toList;
public class Checker implements Runnable {
private static final List<World> skippingWorlds = new ArrayList<>();
public static final List<World> skippingWorlds = new ArrayList<>();
@Override
public void run() {
@ -27,14 +26,38 @@ public class Checker implements Runnable {
.forEach(this::checkWorld);
}
private void checkWorld(final World world) {
final int sleeping = getSleeping(world).size(); // <- 0
final int needed = getNeeded(world);
public static int getSleeping(final World world) {
return world.getPlayers().stream().filter(Player::isSleeping).collect(toList()).size();
}
// Send actionbar notification
if (sleeping > 0 && needed > 0 && Config.getBoolean("messages.actionbar.actionbar")) {
world.getPlayers().forEach(this::sendActionBar);
}
public static int getNeeded(final World world) {
return Math.max(0, (int) Math.ceil((getPlayers(world))
* (Config.getDouble("values.percent") / 100)
- Checker.getSleeping(world)));
}
public static int getPlayers(final World world) {
return Math.max(0, world.getPlayers().size() - getExcluded(world).size());
}
public static boolean isNight(final World world) {
return world.getTime() > 12950 || world.getTime() < 23950;
}
private static List<Player> getExcluded(final World world) {
return world.getPlayers().stream().filter(Checker::isExcluded).collect(toList());
}
private static boolean isExcluded(final Player p) {
final boolean excludedByGameMode = Config.getBoolean("features.ignore") && p.getGameMode() != GameMode.SURVIVAL;
final boolean excludedByPermission = Config.getBoolean("features.bypass") && p.hasPermission("harbor.bypass");
final boolean excludedByAfk = Harbor.essentials != null && Harbor.essentials.getUser(p).isAfk(); // Essentials AFK detection
return excludedByGameMode || excludedByPermission || excludedByAfk;
}
private void checkWorld(final World world) {
final int sleeping = getSleeping(world);
final int needed = getNeeded(world);
// Check if world is applicable for skipping
if (needed == 0 && sleeping > 0) {
@ -54,94 +77,9 @@ public class Checker implements Runnable {
return !Config.getList("blacklist").contains(world.getName());
}
private boolean isNight(final World world) {
return world.getTime() > 12950 || world.getTime() < 23950;
}
private void sendActionBar(final Player player) {
final World world = player.getWorld();
final String message = Config.getString("messages.actionbar.sleeping");
player.spigot().sendMessage(ChatMessageType.ACTION_BAR, TextComponent.fromLegacyText(
ChatColor.translateAlternateColorCodes('&', message
.replace("[sleeping]", String.valueOf(getSleeping(world).size()))
.replace("[players]", String.valueOf(world.getPlayers().size()))
.replace("[needed]", String.valueOf(getSkipAmount(world)))
.replace("[more]", String.valueOf(getNeeded(world))))));
}
private List<Player> getSleeping(final World world) {
return world.getPlayers().stream().filter(Player::isSleeping).collect(toList());
}
private int getSkipAmount(final World world) {
return (int) Math.ceil(getPlayers(world) * (Config.getDouble("values.percent") / 100));
}
private int getPlayers(final World world) {
return Math.max(0, world.getPlayers().size() - getExcluded(world).size());
}
private int getNeeded(final World world) {
return Math.max(0, (int) Math.ceil((getPlayers(world))
* (Config.getDouble("values.percent") / 100)
- getSleeping(world).size()));
}
private List<Player> getExcluded(final World world) {
return world.getPlayers().stream().filter(this::isExcluded).collect(toList());
}
private boolean isExcluded(final Player p) {
final boolean excludedByGameMode = Config.getBoolean("features.ignore") && p.getGameMode() != GameMode.SURVIVAL;
final boolean excludedByPermission = Config.getBoolean("features.bypass") && p.hasPermission("harbor.bypass");
final boolean excludedByAfk = Harbor.essentials != null && Harbor.essentials.getUser(p).isAfk(); // Essentials AFK detection
return excludedByGameMode || excludedByPermission || excludedByAfk;
}
private String randomMessage(final String list) {
final List<String> messages = Config.getList(list);
final Random random = new Random();
final int index = random.nextInt(messages.size());
return ChatColor.translateAlternateColorCodes('&', messages.get(index));
}
private void sendChatMessage(final String message) {
if (!Config.getBoolean("messages.chat.chat")) return;
if (message.length() < 1) return;
Bukkit.broadcastMessage(message);
}
private void accelerateNight(final World world) {
Bukkit.broadcastMessage(Config.getString("messages.chat.accelerateNight"));
new BukkitRunnable() {
@Override
public void run() {
final long time = world.getTime();
if (!(time >= 450 && time <= 1000)) {
world.setTime(time + 60);
} else {
// Announce night skip and clear queue
sendChatMessage(randomMessage("messages.chat.skipped"));
skippingWorlds.remove(world);
// Reset sleep statistic if phantoms are disabled
if (!Config.getBoolean("features.phantoms")) {
world.getPlayers().forEach(player -> player.setStatistic(Statistic.TIME_SINCE_REST, 0));
}
// Clear weather
if (Config.getBoolean("features.weather")) {
world.setStorm(false);
world.setThundering(false);
}
this.cancel();
}
}
}.runTaskTimer(Harbor.instance, 20, 1);
Message.SendChatMessage(world, "messages.chat.accelerateNight", "", 0);
Message.SendActionbarMessage(world, "messages.actionbar.everyone", "", 0);
new AccelerateNightTask(world).runTaskTimer(Harbor.instance, 0L, 1);
}
}

View File

@ -4,84 +4,55 @@ import xyz.nkomarn.Harbor.Harbor;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
public class Config {
/**
* Report an error in reading the configuration
* @param e Exception generated from reading configuration
*/
private static void error(Exception e) {
e.printStackTrace();
}
/**
* Fetches a boolean from the configuration
* if location is not found, <code>false</code> is returned
*
* @param location Configuration location of the boolean
*/
public static boolean getBoolean(String location) {
try {
return Harbor.instance.getConfig().getBoolean(location);
}
catch (Exception e) {
error(e);
return false;
}
public static boolean getBoolean(final String location) {
return Harbor.instance.getConfig().getBoolean(location, false);
}
/**
* Fetches a string from the configuration
* if location is not found, <code>empty String</code> is returned
*
* @param location Configuration location of the string
*/
public static String getString(String location) {
try {
return Harbor.instance.getConfig().getString(location);
}
catch (Exception e) {
error(e);
return "";
}
public static String getString(final String location) {
return Harbor.instance.getConfig().getString(location, "");
}
/**
* Fetches an integer from the configuration
* if location is not found, <code>0</code> is returned
*
* @param location Configuration location of the integer
*/
public static int getInteger(String location) {
try {
return Harbor.instance.getConfig().getInt(location);
}
catch (Exception e) {
error(e);
return 0;
}
public static int getInteger(final String location) {
return Harbor.instance.getConfig().getInt(location, 0);
}
/**
* Fetches a double from the configuration
* if location is not found, <code>0.0</code> is returned
*
* @param location Configuration location of the double
*/
public static double getDouble(String location) {
try {
return Double.parseDouble(Objects.requireNonNull(Harbor.instance.getConfig().getString(location)));
}
catch (Exception e) {
error(e);
return 0.0;
}
public static double getDouble(final String location) {
return Harbor.instance.getConfig().getDouble(location, 0.0);
}
/**
* Fetches a double from the configuration
* @param location Configuration location of the double
* Fetches a list from the configuration
* if location is not found, <code>empty list</code> is returned
*
* @param location Configuration location of the list
*/
public static List<String> getList(String location) {
try {
return Harbor.instance.getConfig().getStringList(location);
}
catch (Exception e) {
error(e);
return new ArrayList<>();
}
public static List<String> getList(final String location) {
return (List<String>) Harbor.instance.getConfig().getList(location, new ArrayList<>());
}
}

View File

@ -0,0 +1,53 @@
package xyz.nkomarn.Harbor.util;
import net.md_5.bungee.api.ChatMessageType;
import net.md_5.bungee.api.chat.TextComponent;
import org.bukkit.ChatColor;
import org.bukkit.World;
import org.bukkit.entity.Player;
import xyz.nkomarn.Harbor.task.Checker;
import java.util.List;
import java.util.Random;
public class Message {
public static void SendChatMessage(final World world, final String messageLocation, final String playerName, final int change) {
if (Config.getBoolean("messages.chat.chat")) {
final String message = prepareMessageWithParams(Config.getString(messageLocation), world, playerName, change);
world.getPlayers().forEach(p -> sendChatMessage(p, message));
}
}
public static void SendActionbarMessage(final World world, final String messageLocation, final String playerName, final int change) {
if (Config.getBoolean("messages.actionbar.actionbar")) {
final String message = prepareMessageWithParams(Config.getString(messageLocation), world, playerName, change);
world.getPlayers().forEach(p -> sendActionbarMessage(p, message));
}
}
public static void SendRandomChatMessage(final World world, final String messageListLocation) {
final List<String> messages = Config.getList(messageListLocation);
final int index = new Random().nextInt(messages.size());
world.getPlayers().forEach(p -> sendChatMessage(p, messages.get(index)));
}
private static void sendChatMessage(final Player player, final String message) {
player.sendMessage(ChatColor.translateAlternateColorCodes('&', message));
}
private static void sendActionbarMessage(final Player player, final String message) {
player.spigot().sendMessage(ChatMessageType.ACTION_BAR, TextComponent.fromLegacyText(message));
}
private static int getSkipAmount(final World world) {
return (int) Math.ceil(Checker.getPlayers(world) * (Config.getDouble("values.percent") / 100));
}
private static String prepareMessageWithParams(final String message, final World world, final String playerName, final int change) {
return ChatColor.translateAlternateColorCodes('&', message
.replace("[sleeping]", String.valueOf(Checker.getSleeping(world) + change))
.replace("[needed]", String.valueOf(getSkipAmount(world)))
.replace("[more]", String.valueOf(Checker.getNeeded(world) - change))
.replace("[player]", playerName));
}
}

View File

@ -11,6 +11,7 @@
values:
timer: 2 # How often to run the clock task (used to detect sleep, AFK players, time actionbar, etc.)
percent: 100 # Percent of players that need to sleep to skip night (must be between 0 to 100)
timeSkipInterval: 60 # Time skip interval that is added when the night get accelerated.
features:
skip: true # Toggle night skipping feature. Configure amount of players needed to skip above (percent)
@ -28,8 +29,8 @@ messages:
- "&eThe night has been skipped."
- "&eAhhh, finally morning."
- "&eArghh, it's so bright outside."
sleeping: "&e[player] is now sleeping ([sleeping]/[online], [needed] more needed to skip)." # Display which player went to bed
left: "&e[player] got out of bed ([sleeping]/[online], [needed] more needed to skip)." # Display when a player left their bed
sleeping: "&e[player] is now sleeping ([sleeping]/[needed], [more] more needed to skip)." # Display which player went to bed
left: "&e[player] got out of bed ([sleeping]/[needed], [more] more needed to skip)." # Display when a player left their bed
accelerateNight: "Harbor - Accelerating time." # Display when the night get accelerated.
actionbar:
actionbar: true # Enable/disable actionbar messages