first commit

This commit is contained in:
Patrick
2026-05-01 19:08:47 +02:00
commit 31664370d8
15 changed files with 1254 additions and 0 deletions
+4
View File
@@ -0,0 +1,4 @@
.gradle
.idea
build
gradle
+61
View File
@@ -0,0 +1,61 @@
plugins {
id 'java'
id("xyz.jpenilla.run-paper") version "2.3.1"
}
group = 'de.winniepat'
version = '1.1'
repositories {
mavenCentral()
maven {
name = "papermc-repo"
url = "https://repo.papermc.io/repository/maven-public/"
}
}
dependencies {
compileOnly("io.papermc.paper:paper-api:1.21.8-R0.1-SNAPSHOT")
}
tasks {
runServer {
minecraftVersion("1.21")
}
}
def targetJavaVersion = 21
java {
def javaVersion = JavaVersion.toVersion(targetJavaVersion)
sourceCompatibility = javaVersion
targetCompatibility = javaVersion
if (JavaVersion.current() < javaVersion) {
toolchain.languageVersion = JavaLanguageVersion.of(targetJavaVersion)
}
}
tasks.withType(JavaCompile).configureEach {
options.encoding = 'UTF-8'
if (targetJavaVersion >= 10 || JavaVersion.current().isJava10Compatible()) {
options.release.set(targetJavaVersion)
}
}
processResources {
def props = [version: version]
inputs.properties props
filteringCharset 'UTF-8'
filesMatching('plugin.yml') {
expand props
}
}
build.doLast {
copy {
from("$buildDir/libs") {
include "EventPlugin*.jar"
}
into("C:/Users/Administrator/Documents/1.21.8-Server/plugins")
}
}
View File
Vendored
+249
View File
@@ -0,0 +1,249 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"
Vendored
+92
View File
@@ -0,0 +1,92 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
+1
View File
@@ -0,0 +1 @@
rootProject.name = 'EventPlugin'
@@ -0,0 +1,311 @@
package de.winniepat.eventPlugin;
import de.winniepat.eventPlugin.manager.CombatManager;
import de.winniepat.eventPlugin.manager.DataManager;
import de.winniepat.eventPlugin.player.PlayerData;
import de.winniepat.eventPlugin.player.PlayerListener;
import de.winniepat.eventPlugin.util.TimeUtils;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.scoreboard.DisplaySlot;
import org.bukkit.scoreboard.Objective;
import org.bukkit.scoreboard.Scoreboard;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
public final class EventPlugin extends JavaPlugin {
private static final long DAILY_PLAYTIME_MINUTES = 15;
private static final String TIMEZONE = "Europe/Berlin";
private Map<UUID, PlayerData> playerDataMap;
private Map<UUID, Long> sessionStartTimes;
private Map<UUID, Scoreboard> playerScoreboards;
private DataManager dataManager;
private CombatManager combatManager;
@Override
public void onEnable() {
this.playerDataMap = new HashMap<>();
this.sessionStartTimes = new HashMap<>();
this.playerScoreboards = new HashMap<>();
this.dataManager = new DataManager(this);
this.combatManager = new CombatManager(this);
dataManager.loadPlayerData(playerDataMap);
getServer().getPluginManager().registerEvents(new PlayerListener(this), this);
if (getCommand("varo") != null) {
VaroCommand varoCommand = new VaroCommand(this);
getCommand("varo").setExecutor(varoCommand);
getCommand("varo").setTabCompleter(varoCommand);
} else {
getLogger().warning("Command 'varo' not found in plugin.yml! Please check your plugin.yml configuration.");
}
startResetScheduler();
startRealTimePlaytimeChecker();
startScoreboardUpdater();
getLogger().info("Varo Event Plugin enabled successfully!");
}
@Override
public void onDisable() {
for (Player player : Bukkit.getOnlinePlayers()) {
stopPlaytimeTracking(player.getUniqueId());
removeScoreboard(player.getUniqueId());
}
dataManager.savePlayerData(playerDataMap);
combatManager.cleanup();
getLogger().info("Varo Event Plugin disabled!");
}
public void startPlaytimeTracking(UUID playerId) {
if (hasPlaytimeLeft(playerId)) {
sessionStartTimes.put(playerId, System.currentTimeMillis());
Player player = Bukkit.getPlayer(playerId);
if (player != null) {
createScoreboard(player);
}
}
}
public void stopPlaytimeTracking(UUID playerId) {
Player player = Bukkit.getPlayer(playerId);
if (player != null && combatManager.isInCombat(player)) {
combatManager.handleCombatLog(player);
return;
}
Long startTime = sessionStartTimes.remove(playerId);
if (startTime != null) {
PlayerData data = playerDataMap.get(playerId);
if (data != null) {
long sessionTime = System.currentTimeMillis() - startTime;
data.addPlayedTime(sessionTime);
dataManager.savePlayerData(playerDataMap);
}
}
removeScoreboard(playerId);
}
public boolean hasPlaytimeLeft(UUID playerId) {
PlayerData data = playerDataMap.get(playerId);
if (data == null) {
data = new PlayerData();
playerDataMap.put(playerId, data);
}
if (!TimeUtils.isSameDay(data.getLastPlayDate(), TIMEZONE)) {
data.resetPlaytime();
dataManager.savePlayerData(playerDataMap);
}
return data.getPlayedTime() < TimeUnit.MINUTES.toMillis(DAILY_PLAYTIME_MINUTES);
}
public long getRemainingPlaytime(UUID playerId) {
PlayerData data = playerDataMap.get(playerId);
if (data == null) return TimeUnit.MINUTES.toMillis(DAILY_PLAYTIME_MINUTES);
long played = data.getPlayedTime();
Long sessionStart = sessionStartTimes.get(playerId);
if (sessionStart != null) {
played += (System.currentTimeMillis() - sessionStart);
}
long totalAllowed = TimeUnit.MINUTES.toMillis(DAILY_PLAYTIME_MINUTES);
return Math.max(0, totalAllowed - played);
}
public long getUsedPlaytime(UUID playerId) {
PlayerData data = playerDataMap.get(playerId);
if (data == null) return 0;
long played = data.getPlayedTime();
Long sessionStart = sessionStartTimes.get(playerId);
if (sessionStart != null) {
played += (System.currentTimeMillis() - sessionStart);
}
return played;
}
public Map<UUID, PlayerData> getPlayerDataMap() {
return playerDataMap;
}
public Map<UUID, Long> getSessionStartTimes() {
return sessionStartTimes;
}
public DataManager getDataManager() {
return dataManager;
}
public CombatManager getCombatManager() {
return combatManager;
}
public static long getDailyPlaytimeMinutes() {
return DAILY_PLAYTIME_MINUTES;
}
public static String getTimezone() {
return TIMEZONE;
}
private void startResetScheduler() {
new BukkitRunnable() {
@Override
public void run() {
ZonedDateTime now = ZonedDateTime.now(ZoneId.of(TIMEZONE));
ZonedDateTime nextReset = now.toLocalDate().atStartOfDay(ZoneId.of(TIMEZONE)).plusDays(1);
long delay = nextReset.toEpochSecond() * 1000 - System.currentTimeMillis();
if (delay < 0) {
delay = 0;
}
new BukkitRunnable() {
@Override
public void run() {
resetAllPlaytimes();
startResetScheduler();
}
}.runTaskLater(EventPlugin.this, delay / 50);
}
}.runTaskAsynchronously(this);
}
private void startRealTimePlaytimeChecker() {
new BukkitRunnable() {
@Override
public void run() {
for (Player player : Bukkit.getOnlinePlayers()) {
UUID playerId = player.getUniqueId();
Long sessionStart = sessionStartTimes.get(playerId);
if (sessionStart != null) {
PlayerData data = playerDataMap.get(playerId);
if (data != null) {
if (System.currentTimeMillis() % 30000 < 1000) {
long sessionTime = System.currentTimeMillis() - sessionStart;
data.addPlayedTime(sessionTime);
sessionStartTimes.put(playerId, System.currentTimeMillis());
dataManager.savePlayerDataAsync(playerDataMap);
}
}
}
if (!hasPlaytimeLeft(playerId)) {
player.kickPlayer("§c§lTIME'S UP!\n\n§7Your daily 15 minutes of playtime are over!\n§6Come back tomorrow at §e0:00 Berlin Time§6!");
stopPlaytimeTracking(playerId);
}
}
}
}.runTaskTimer(this, 20L, 20L);
}
private void startScoreboardUpdater() {
new BukkitRunnable() {
@Override
public void run() {
for (Player player : Bukkit.getOnlinePlayers()) {
UUID playerId = player.getUniqueId();
if (sessionStartTimes.containsKey(playerId)) {
updateScoreboard(player);
}
}
}
}.runTaskTimer(this, 10L, 10L);
}
private void createScoreboard(Player player) {
UUID playerId = player.getUniqueId();
Scoreboard scoreboard = Bukkit.getScoreboardManager().getNewScoreboard();
Objective objective = scoreboard.registerNewObjective("varo", "dummy", "§6§lVARO EVENT");
objective.setDisplaySlot(DisplaySlot.SIDEBAR);
playerScoreboards.put(playerId, scoreboard);
player.setScoreboard(scoreboard);
updateScoreboard(player);
}
public void updateScoreboard(Player player) {
UUID playerId = player.getUniqueId();
Scoreboard scoreboard = playerScoreboards.get(playerId);
if (scoreboard == null) return;
Objective objective = scoreboard.getObjective("varo");
if (objective == null) return;
for (String entry : scoreboard.getEntries()) {
scoreboard.resetScores(entry);
}
long used = getUsedPlaytime(playerId);
long total = TimeUnit.MINUTES.toMillis(DAILY_PLAYTIME_MINUTES);
boolean inCombat = combatManager.isInCombat(player);
long combatTime = combatManager.getRemainingCombatTime(player);
objective.getScore("§7").setScore(9);
if (inCombat) {
objective.getScore("§c⚔ In Combat:").setScore(8);
objective.getScore("§7" + (combatTime / 1000) + "s remaining").setScore(7);
objective.getScore("§7 ").setScore(6);
} else {
objective.getScore("§a✓ Not in Combat").setScore(8);
objective.getScore("§7 ").setScore(7);
objective.getScore("§7 ").setScore(6);
}
objective.getScore("§7 ").setScore(5);
objective.getScore("§f📊 Used Today:").setScore(4);
objective.getScore("§7" + TimeUtils.formatTimeShort(used) + "§8/§715:00").setScore(3);
objective.getScore("§7 ").setScore(2);
objective.getScore("§f🔄 Resets At:").setScore(1);
objective.getScore("§60:00 Berlin Time").setScore(0);
}
public void removeScoreboard(UUID playerId) {
Scoreboard scoreboard = playerScoreboards.remove(playerId);
if (scoreboard != null) {
Player player = Bukkit.getPlayer(playerId);
if (player != null && player.isOnline()) {
player.setScoreboard(Bukkit.getScoreboardManager().getMainScoreboard());
}
}
}
private void resetAllPlaytimes() {
for (PlayerData data : playerDataMap.values()) {
data.resetPlaytime();
}
dataManager.savePlayerData(playerDataMap);
for (Player player : Bukkit.getOnlinePlayers()) {
player.sendMessage("§6§lVARO §8» §aDaily reset! You now have 15 minutes of playtime!");
if (sessionStartTimes.containsKey(player.getUniqueId())) {
updateScoreboard(player);
}
}
getLogger().info("Daily playtime reset completed!");
}
}
@@ -0,0 +1,158 @@
package de.winniepat.eventPlugin;
import de.winniepat.eventPlugin.util.TimeUtils;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
public class VaroCommand implements CommandExecutor, TabCompleter {
private final EventPlugin plugin;
public VaroCommand(EventPlugin plugin) {
this.plugin = plugin;
}
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (args.length == 0) {
defaultCommand(sender);
return true;
}
switch (args[0].toLowerCase()) {
case "time":
case "remaining":
handleTimeCommand(sender);
break;
case "combat":
handleCombatCommand(sender);
break;
case "commands":
sendCommands(sender);
break;
case "info":
default:
defaultCommand(sender);
break;
}
return true;
}
private void handleTimeCommand(CommandSender sender) {
if (!(sender instanceof Player)) {
sender.sendMessage(ChatColor.RED + "This command can only be used by players!");
return;
}
Player player = (Player) sender;
UUID playerId = player.getUniqueId();
long remaining = plugin.getRemainingPlaytime(playerId);
long used = plugin.getUsedPlaytime(playerId);
long total = TimeUnit.MINUTES.toMillis(EventPlugin.getDailyPlaytimeMinutes());
boolean inCombat = plugin.getCombatManager().isInCombat(player);
long combatTime = plugin.getCombatManager().getRemainingCombatTime(player);
player.sendMessage(" ");
player.sendMessage(ChatColor.GOLD + "§6§lVARO EVENT");
player.sendMessage(ChatColor.YELLOW + "⏰ Time Left: " + ChatColor.WHITE + TimeUtils.formatTimeShort(remaining));
player.sendMessage(ChatColor.YELLOW + "📊 Used Today: " + ChatColor.WHITE + TimeUtils.formatTimeShort(used) + ChatColor.GRAY + "/15:00");
if (inCombat) {
player.sendMessage(ChatColor.YELLOW + "⚔ Combat Status: " + ChatColor.RED + "IN COMBAT");
player.sendMessage(ChatColor.YELLOW + "⏳ Combat Ends: " + ChatColor.WHITE + (combatTime / 1000) + " seconds");
} else {
player.sendMessage(ChatColor.YELLOW + "⚔ Combat Status: " + ChatColor.GREEN + "SAFE");
}
if (remaining > 0) {
long resetIn = TimeUtils.getMillisUntilReset(EventPlugin.getTimezone());
player.sendMessage(ChatColor.YELLOW + "🔄 Reset In: " + ChatColor.WHITE + TimeUtils.formatTimeUntilReset(resetIn));
}
player.sendMessage(" ");
}
private void handleCombatCommand(CommandSender sender) {
if (!(sender instanceof Player)) {
sender.sendMessage(ChatColor.RED + "This command can only be used by players!");
return;
}
Player player = (Player) sender;
boolean inCombat = plugin.getCombatManager().isInCombat(player);
long combatTime = plugin.getCombatManager().getRemainingCombatTime(player);
player.sendMessage(" ");
if (inCombat) {
player.sendMessage(ChatColor.RED + "§c§lCOMBAT STATUS");
player.sendMessage(ChatColor.RED + "You are in combat for " + (combatTime / 1000) + " more seconds!");
player.sendMessage(ChatColor.RED + "Logging out will result in death and inventory drop!");
} else {
player.sendMessage(ChatColor.GREEN + "§a§lCOMBAT STATUS");
player.sendMessage(ChatColor.GREEN + "You are not in combat.");
player.sendMessage(ChatColor.GREEN + "You can safely log out.");
}
player.sendMessage(" ");
}
private void defaultCommand(CommandSender sender) {
sender.sendMessage(" ");
sender.sendMessage(ChatColor.GOLD + "§6§lVARO EVENT");
sender.sendMessage(ChatColor.YELLOW + "Limited Playtime " + ChatColor.WHITE + " - You have " + EventPlugin.getDailyPlaytimeMinutes() + " minutes Playtime Every Day");
sender.sendMessage(ChatColor.YELLOW + "Combatlog " + ChatColor.WHITE + "- Logout in Combat = Death");
sender.sendMessage(ChatColor.YELLOW + "Time Reset " + ChatColor.WHITE + "- Playtimes Reset at 0:00 Berlin Time");
sender.sendMessage(ChatColor.RED + "Death " + ChatColor.WHITE + " Your death means disqualification");
sender.sendMessage(" ");
}
private void sendCommands(CommandSender sender) {
sender.sendMessage(" ");
sender.sendMessage(ChatColor.GOLD + "§6§lVARO COMMANDS");
sender.sendMessage(ChatColor.YELLOW + "/varo time" + ChatColor.WHITE + " - Check your remaining playtime");
sender.sendMessage(ChatColor.YELLOW + "/varo combat" + ChatColor.WHITE + " - Check your combat status");
sender.sendMessage(ChatColor.YELLOW + "/varo commands" + ChatColor.WHITE + " - Shows you this text");
sender.sendMessage(ChatColor.YELLOW + "/varo info" + ChatColor.WHITE + " - Show Event infos");
sender.sendMessage(" ");
}
@Override
public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {
if (args.length == 1) {
List<String> completions = new ArrayList<>();
completions.add("time");
completions.add("combat");
completions.add("commands");
completions.add("info");
return completions.stream()
.filter(s -> s.toLowerCase().startsWith(args[0].toLowerCase()))
.toList();
}
if (args.length == 2 && args[0].equalsIgnoreCase("reset") && sender.hasPermission("varo.admin")) {
return Bukkit.getOnlinePlayers().stream()
.map(Player::getName)
.filter(name -> name.toLowerCase().startsWith(args[1].toLowerCase()))
.toList();
}
return java.util.List.of();
}
}
@@ -0,0 +1,156 @@
package de.winniepat.eventPlugin.manager;
import de.winniepat.eventPlugin.EventPlugin;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.scheduler.BukkitRunnable;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
public class CombatManager {
private final EventPlugin plugin;
private final Map<UUID, Long> combatTaggedPlayers;
private final Map<UUID, BukkitRunnable> combatTasks;
private final long COMBAT_DURATION = 10000;
public CombatManager(EventPlugin plugin) {
this.plugin = plugin;
this.combatTaggedPlayers = new HashMap<>();
this.combatTasks = new HashMap<>();
}
public void tagPlayer(Player player) {
UUID playerId = player.getUniqueId();
long combatEndTime = System.currentTimeMillis() + COMBAT_DURATION;
combatTaggedPlayers.put(playerId, combatEndTime);
if (combatTasks.containsKey(playerId)) {
combatTasks.get(playerId).cancel();
}
BukkitRunnable combatTask = new BukkitRunnable() {
@Override
public void run() {
if (combatTaggedPlayers.containsKey(playerId)) {
long remaining = combatTaggedPlayers.get(playerId) - System.currentTimeMillis();
if (remaining <= 0) {
removeCombatTag(playerId);
if (player.isOnline()) {
player.sendActionBar("§aYou are no longer in combat");
}
} else {
updateActionBar(player, remaining);
}
}
}
};
combatTask.runTaskTimer(plugin, 0L, 5L);
combatTasks.put(playerId, combatTask);
player.sendActionBar("§c§lCOMBAT! §7Do not log out for 10 seconds!");
player.sendMessage("§c§lCOMBAT! §7You are now in combat. Logging out will result in death!");
}
public boolean isInCombat(Player player) {
UUID playerId = player.getUniqueId();
if (!combatTaggedPlayers.containsKey(playerId)) {
return false;
}
long combatEndTime = combatTaggedPlayers.get(playerId);
if (System.currentTimeMillis() >= combatEndTime) {
removeCombatTag(playerId);
return false;
}
return true;
}
public long getRemainingCombatTime(Player player) {
UUID playerId = player.getUniqueId();
if (!combatTaggedPlayers.containsKey(playerId)) {
return 0;
}
long remaining = combatTaggedPlayers.get(playerId) - System.currentTimeMillis();
return Math.max(0, remaining);
}
public void handleCombatLog(Player player) {
if (isInCombat(player)) {
player.setHealth(0);
String deathMessage = "§c§lCOMBAT LOGGER! §7" + player.getName() + " logged out during combat!";
Bukkit.broadcastMessage(deathMessage);
plugin.getLogger().warning("Player " + player.getName() + " combat logged and was killed.");
}
}
private void updateActionBar(Player player, long remainingTime) {
if (!player.isOnline()) return;
long seconds = remainingTime / 1000;
long milliseconds = remainingTime % 1000;
int progressBars = 20;
float progress = (float) remainingTime / COMBAT_DURATION;
int filledBars = (int) (progress * progressBars);
int emptyBars = progressBars - filledBars;
StringBuilder progressBar = new StringBuilder("§c");
for (int i = 0; i < filledBars; i++) {
progressBar.append("|");
}
progressBar.append("§7");
for (int i = 0; i < emptyBars; i++) {
progressBar.append("|");
}
String timeColor = "§a";
if (seconds <= 3) timeColor = "§c§l";
else if (seconds <= 7) timeColor = "§e";
String actionBar = String.format(
"§c§lCOMBAT §8| %s%d.%01d§7s §8| %s",
timeColor, seconds, milliseconds / 100, progressBar.toString()
);
player.sendActionBar(actionBar);
}
private void removeCombatTag(UUID playerId) {
combatTaggedPlayers.remove(playerId);
if (combatTasks.containsKey(playerId)) {
combatTasks.get(playerId).cancel();
combatTasks.remove(playerId);
}
}
public void cleanup() {
for (BukkitRunnable task : combatTasks.values()) {
task.cancel();
}
combatTaggedPlayers.clear();
combatTasks.clear();
}
public void onPlayerDeath(Player player) {
removeCombatTag(player.getUniqueId());
}
public void onEntityDamage(EntityDamageByEntityEvent event) {
if (event.getEntity() instanceof Player && event.getDamager() instanceof Player) {
Player damaged = (Player) event.getEntity();
Player damager = (Player) event.getDamager();
tagPlayer(damaged);
tagPlayer(damager);
}
}
}
@@ -0,0 +1,65 @@
package de.winniepat.eventPlugin.manager;
import de.winniepat.eventPlugin.EventPlugin;
import de.winniepat.eventPlugin.player.PlayerData;
import org.bukkit.configuration.file.FileConfiguration;
import java.util.Map;
import java.util.UUID;
public class DataManager {
private final EventPlugin plugin;
public DataManager(EventPlugin plugin) {
this.plugin = plugin;
plugin.saveDefaultConfig();
}
public void loadPlayerData(Map<UUID, PlayerData> playerDataMap) {
FileConfiguration config = plugin.getConfig();
if (config.contains("playerData")) {
for (String key : config.getConfigurationSection("playerData").getKeys(false)) {
try {
UUID uuid = UUID.fromString(key);
long playedTime = config.getLong("playerData." + key + ".playedTime");
long lastPlayDate = config.getLong("playerData." + key + ".lastPlayDate");
playerDataMap.put(uuid, new PlayerData(playedTime, lastPlayDate));
} catch (IllegalArgumentException e) {
plugin.getLogger().warning("Invalid UUID in config: " + key);
}
}
}
}
public void savePlayerData(Map<UUID, PlayerData> playerDataMap) {
FileConfiguration config = plugin.getConfig();
config.set("playerData", null);
for (Map.Entry<UUID, PlayerData> entry : playerDataMap.entrySet()) {
String path = "playerData." + entry.getKey().toString();
config.set(path + ".playedTime", entry.getValue().getPlayedTime());
config.set(path + ".lastPlayDate", entry.getValue().getLastPlayDate());
}
plugin.saveConfig();
}
public void savePlayerDataAsync(Map<UUID, PlayerData> playerDataMap) {
plugin.getServer().getScheduler().runTaskAsynchronously(plugin, () -> {
savePlayerData(playerDataMap);
});
}
public void emergencySave(Map<UUID, PlayerData> playerDataMap, Map<UUID, Long> sessionStartTimes) {
for (Map.Entry<UUID, Long> entry : sessionStartTimes.entrySet()) {
PlayerData data = playerDataMap.get(entry.getKey());
if (data != null) {
long sessionTime = System.currentTimeMillis() - entry.getValue();
data.addPlayedTime(sessionTime);
}
}
savePlayerData(playerDataMap);
}
}
@@ -0,0 +1,42 @@
package de.winniepat.eventPlugin.player;
public class PlayerData {
private long playedTime;
private long lastPlayDate;
public PlayerData() {
this.playedTime = 0;
this.lastPlayDate = System.currentTimeMillis();
}
public PlayerData(long playedTime, long lastPlayDate) {
this.playedTime = playedTime;
this.lastPlayDate = lastPlayDate;
}
public long getPlayedTime() {
return playedTime;
}
public long getLastPlayDate() {
return lastPlayDate;
}
public void addPlayedTime(long timeMillis) {
this.playedTime += timeMillis;
this.lastPlayDate = System.currentTimeMillis();
}
public void resetPlaytime() {
this.playedTime = 0;
this.lastPlayDate = System.currentTimeMillis();
}
public void setPlayedTime(long playedTime) {
this.playedTime = playedTime;
}
public void setLastPlayDate(long lastPlayDate) {
this.lastPlayDate = lastPlayDate;
}
}
@@ -0,0 +1,60 @@
package de.winniepat.eventPlugin.player;
import de.winniepat.eventPlugin.EventPlugin;
import de.winniepat.eventPlugin.util.TimeUtils;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import java.util.UUID;
public class PlayerListener implements Listener {
private final EventPlugin plugin;
public PlayerListener(EventPlugin plugin) {
this.plugin = plugin;
}
@EventHandler
public void onPlayerJoin(PlayerJoinEvent event) {
Player player = event.getPlayer();
UUID playerId = player.getUniqueId();
if (!plugin.hasPlaytimeLeft(playerId)) {
player.kickPlayer("§c§lTIME'S UP!\n\n§7Your daily 15 minutes of playtime are over!\n§6Come back tomorrow at §e0:00 Berlin Time§6!");
return;
}
plugin.startPlaytimeTracking(playerId);
long remaining = plugin.getRemainingPlaytime(playerId);
player.sendMessage("§6§lVARO §8» §7Welcome to the §6Varo Event§7!");
player.sendMessage("§a§lVARO §8» §7Check the scoreboard for your remaining time!");
player.sendMessage("§a§lVARO §8» §7You have §e" + TimeUtils.formatTimeShort(remaining) + "§7 of playtime left today!");
}
@EventHandler
public void onPlayerQuit(PlayerQuitEvent event) {
plugin.stopPlaytimeTracking(event.getPlayer().getUniqueId());
}
@EventHandler
public void onEntityDamage(EntityDamageByEntityEvent event) {
plugin.getCombatManager().onEntityDamage(event);
}
@EventHandler
public void onPlayerDeath(PlayerDeathEvent event) {
Player player = event.getEntity();
plugin.getCombatManager().onPlayerDeath(player);
if (event.getDeathMessage() != null && event.getDeathMessage().contains("combat")) {
event.setDeathMessage("§c§lCOMBAT LOG! §7" + player.getName() + " logged out during combat!");
}
}
}
@@ -0,0 +1,36 @@
package de.winniepat.eventPlugin.util;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.concurrent.TimeUnit;
public class TimeUtils {
public static boolean isSameDay(long timestamp, String timezone) {
ZonedDateTime now = ZonedDateTime.now(ZoneId.of(timezone));
ZonedDateTime lastPlay = ZonedDateTime.ofInstant(
java.time.Instant.ofEpochMilli(timestamp), ZoneId.of(timezone));
return now.toLocalDate().equals(lastPlay.toLocalDate());
}
public static String formatTimeShort(long millis) {
long minutes = TimeUnit.MILLISECONDS.toMinutes(millis);
long seconds = TimeUnit.MILLISECONDS.toSeconds(millis) -
TimeUnit.MINUTES.toSeconds(minutes);
return String.format("%02d:%02d", minutes, seconds);
}
public static long getMillisUntilReset(String timezone) {
ZonedDateTime now = ZonedDateTime.now(ZoneId.of(timezone));
ZonedDateTime nextReset = now.toLocalDate().atStartOfDay(ZoneId.of(timezone)).plusDays(1);
return nextReset.toEpochSecond() * 1000 - System.currentTimeMillis();
}
public static String formatTimeUntilReset(long millis) {
long hours = TimeUnit.MILLISECONDS.toHours(millis);
long minutes = TimeUnit.MILLISECONDS.toMinutes(millis) -
TimeUnit.HOURS.toMinutes(hours);
return String.format("%d hours and %d minutes", hours, minutes);
}
}
View File
+19
View File
@@ -0,0 +1,19 @@
name: EventPlugin
version: '1.1'
main: de.winniepat.eventPlugin.EventPlugin
api-version: '1.21'
authors: [ WinniePatGG ]
website: https://winniepat.de
commands:
varo:
description: Varo event commands
usage: /varo <time|combat|commands|info>
permissions:
varo.player:
description: Basic varo player permissions
default: true
varo.admin:
description: Admin permissions for varo
default: op