Skip to content

Commit

Permalink
add functions
Browse files Browse the repository at this point in the history
  • Loading branch information
angushushu committed Nov 11, 2023
1 parent 41678c9 commit 3ce732f
Show file tree
Hide file tree
Showing 13 changed files with 120 additions and 41 deletions.
91 changes: 64 additions & 27 deletions src/main/java/org/cubexmc/ecobalancer/EcoBalancer.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,27 +3,33 @@
import net.milkbowl.vault.chat.Chat;
import net.milkbowl.vault.economy.Economy;
import net.milkbowl.vault.permission.Permission;

import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.plugin.java.JavaPlugin;
import org.cubexmc.ecobalancer.commands.CheckAllCommand;
import org.cubexmc.ecobalancer.commands.CheckPlayerCommand;
import org.cubexmc.ecobalancer.commands.HelpCommand;

import java.util.UUID;
import java.util.Calendar;
import java.util.*;

import java.io.File;
import java.io.IOException;
import java.util.logging.FileHandler;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;

public final class EcoBalancer extends JavaPlugin {

private static Economy econ = null;
private static Permission perms = null;
private static Chat chat = null;
private boolean deductBasedOnTime;
private int inactiveDaysToDeduct;
private double deductionPercentage;
private TreeMap<Integer, Double> taxBrackets = new TreeMap<>();
private int inactiveDaysToClear;
private Logger fileLogger = Logger.getLogger("EcoBalancerFileLogger");
private FileHandler fileHandler;

@Override
public void onEnable() {
Expand All @@ -40,10 +46,28 @@ public void onEnable() {
int minute = Integer.parseInt(checkTime.split(":")[1]);
scheduleCheckAll(hourOfDay, minute);
// deduction setting
deductBasedOnTime = getConfig().getBoolean("deduct-based-on-time", false);
inactiveDaysToDeduct = getConfig().getInt("inactive-days-to-deduct", 50);
deductionPercentage = getConfig().getDouble("deduction-percentage", 1);
List<Map<?, ?>> rawTaxBrackets = getConfig().getMapList("tax-brackets");

for (Map<?, ?> bracket : rawTaxBrackets) {
Integer threshold = bracket.get("threshold") == null ? Integer.MAX_VALUE : (Integer) bracket.get("threshold");
Double rate = (Double) bracket.get("rate");
taxBrackets.put(threshold, rate);
}

inactiveDaysToClear = getConfig().getInt("inactive-days-to-clear", 500);

try {
FileHandler fileHandler = new FileHandler(getDataFolder() + File.separator + "EcoBalancer.log", true);
fileHandler.setFormatter(new SimpleFormatter());
fileLogger.addHandler(fileHandler);
fileLogger.setUseParentHandlers(false); // 不将日志转发到父处理器,即不在控制台输出
} catch (IOException e) {
getLogger().severe("Could not setup file logger for EcoBalancer");
e.printStackTrace();
}

getCommand("help").setExecutor(new HelpCommand());
getCommand("checkall").setExecutor(new CheckAllCommand(this));
getCommand("checkplayer").setExecutor(new CheckPlayerCommand(this));
Expand All @@ -53,6 +77,7 @@ public void onEnable() {
@Override
public void onDisable() {
// Plugin shutdown logic
fileHandler.close();
getLogger().info("EcoBalancer disabled.");
}

Expand All @@ -78,26 +103,44 @@ public static Economy getEconomy() {
public void checkBalance(long currentTime, OfflinePlayer player, boolean print) {
UUID playerId = player.getUniqueId();
long lastPlayed = player.getLastPlayed();
long daysOffline = (currentTime - lastPlayed) / (1000 * 60 * 60 * 24);
double balance = econ.hasAccount(player) ? econ.getBalance(player) : 0;
Double deductionRate = 0.0;

// 计算玩家离线天数
long daysOffline = (currentTime - lastPlayed) / (1000 * 60 * 60 * 24);
if (balance < 0) {
econ.depositPlayer(player, -1*balance);
} else {
if (daysOffline > inactiveDaysToClear) {
// 清除超过500天未上线的玩家
econ.withdrawPlayer(player, balance);
} else if (daysOffline > inactiveDaysToDeduct) {
// 对于超过50天未上线的玩家,扣除其1%的余额
double deduction = balance * deductionPercentage;
econ.withdrawPlayer(player, deduction);
Map.Entry<Integer, Double> entry = taxBrackets.higherEntry((int) balance);
if (entry != null) {
deductionRate = entry.getValue();
}
// If no bracket is found (which should not happen because we use Integer.MAX_VALUE for the highest bracket), use a default rate
if (deductionRate == null) {
deductionRate = 0.0; // defaultRate should be defined somewhere in your class
}

if (deductBasedOnTime) {
// 计算玩家离线天数
if (balance < 0) {
econ.depositPlayer(player, -1 * balance);
fileLogger.info("[Negative Bal] Depositing " + (-1 * balance) + " to " + player.getName() + " to bring balance to 0.");
} else {
if (daysOffline > inactiveDaysToClear) {
// 清除超过500天未上线的玩家
econ.withdrawPlayer(player, balance);
fileLogger.info("[>500] Depositing " + (-1 * balance) + " to " + player.getName() + " to bring balance to 0.");
} else if (daysOffline > inactiveDaysToDeduct) {
// 对于超过50天未上线的玩家,按税率扣除
double deduction = balance * deductionRate;
econ.withdrawPlayer(player, deduction);
fileLogger.info("[<500] Withdrawing " + deduction + " from " + player.getName() + " for inactivity.");
}
}
} else {
double deduction = balance * deductionRate;
econ.withdrawPlayer(player, deduction);
fileLogger.info("Withdrawing " + deduction + " from " + player.getName() + " for inactivity.");
}
if (print) {
getLogger().info("Player: " + player.getName() + ", UUID: " + playerId
+ ", Last Played: " + lastPlayed + ", Balance: " + balance
+ ", Days Offline: " + daysOffline);
+ ", Offline: " + daysOffline + ", Balance: " + balance);
}
}

Expand All @@ -121,19 +164,13 @@ private void scheduleCheckAll(int hour, int minute) {

long millisUntilOneAM = oneAM.getTimeInMillis() - now.getTimeInMillis();
long ticksUntilOneAM = millisUntilOneAM / 50; // 每个tick代表50毫秒
// 注意:你需要编写代码来正确计算这个值

Bukkit.getScheduler().scheduleSyncRepeatingTask(this, new Runnable() {
@Override
public void run() {
int cnt = 0;
boolean print = false;
long currentTime = System.currentTimeMillis();
for (OfflinePlayer player : Bukkit.getOfflinePlayers()) {
if (cnt < 10) {
print = true;
}
checkBalance(currentTime, player, print);
checkBalance(currentTime, player, false);
}
}
}, ticksUntilOneAM, oneDayTicks);
Expand Down
41 changes: 31 additions & 10 deletions src/main/java/org/cubexmc/ecobalancer/commands/CheckAllCommand.java
Original file line number Diff line number Diff line change
Expand Up @@ -29,23 +29,44 @@ public boolean onCommand(CommandSender sender, Command command, String s, String
}
if (args.length == 0) {
player.sendMessage(ChatColor.GREEN + "CHECKING ALL!");
checkAll();
checkAll(sender);
}
}

return true;
}

public void checkAll() {
int cnt = 0;
boolean print = false;
Economy economy = EcoBalancer.getEconomy();
long currentTime = System.currentTimeMillis();
for (OfflinePlayer player : Bukkit.getOfflinePlayers()) {
if (cnt < 10) {
print = true;
public void checkAll(CommandSender sender) {
final long currentTime = System.currentTimeMillis();
final OfflinePlayer[] players = Bukkit.getOfflinePlayers();
final int batchSize = 100; // Number of players to process at once
final int delay = 10; // Delay in ticks between batches (20 ticks = 1 second)

class BatchRunnable implements Runnable {
private int index = 0;

@Override
public void run() {
int start = index;
int end = Math.min(index + batchSize, players.length);
for (int i = index; i < end; i++) {
OfflinePlayer player = players[i];
plugin.checkBalance(currentTime, player, false);
}
index += batchSize;
// Send a message to the sender after each batch
Bukkit.getScheduler().runTask(plugin, () -> sender.sendMessage(ChatColor.GREEN + "Processed " + (end - start) + " players. Total processed: " + end));
if (index < players.length) {
// Schedule next batch
Bukkit.getScheduler().runTaskLaterAsynchronously(plugin, this, delay);
} else {
// All players have been processed, notify the sender
Bukkit.getScheduler().runTask(plugin, () -> sender.sendMessage(ChatColor.GREEN + "All balances have been checked."));
}
}
plugin.checkBalance(currentTime, player, print);
}

// Start the first batch
Bukkit.getScheduler().runTaskAsynchronously(plugin, new BatchRunnable());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,10 @@ public boolean onCommand(CommandSender sender, Command command, String s, String
}

private void checkPlayer(String playerName) {
System.out.println("checkPlayer()");
long currentTime = System.currentTimeMillis();
OfflinePlayer player = Bukkit.getOfflinePlayer(playerName);
System.out.println("player == null?" + (player == null));
plugin.checkBalance(currentTime, player, true);
}
}
13 changes: 11 additions & 2 deletions src/main/resources/config.yml
Original file line number Diff line number Diff line change
@@ -1,5 +1,14 @@
check-time: "01:00" # 格式为 HH:mm
# by CubeX
check-time: "20:00" # 格式为 HH:mm
deduct-based-on-time: true
inactive-days-to-deduct: 50 # 未上线扣款开始的天数
deduction-rate: 0.01 # 扣款比例
inactive-days-to-clear: 500 # 未上线清空余额的天数
# 按阶级扣税
tax-brackets:
- threshold: 10000
rate: 0.001
- threshold: 20000
rate: 0.002
- threshold: null # No upper limit specified
rate: 0.1

Binary file modified target/EcoBalancer-1.0-SNAPSHOT.jar
Binary file not shown.
13 changes: 11 additions & 2 deletions target/classes/config.yml
Original file line number Diff line number Diff line change
@@ -1,5 +1,14 @@
check-time: "01:00" # 格式为 HH:mm
# by CubeX
check-time: "20:00" # 格式为 HH:mm
deduct-based-on-time: true
inactive-days-to-deduct: 50 # 未上线扣款开始的天数
deduction-rate: 0.01 # 扣款比例
inactive-days-to-clear: 500 # 未上线清空余额的天数
# 按阶级扣税
tax-brackets:
- threshold: 10000
rate: 0.001
- threshold: 20000
rate: 0.002
- threshold: null # No upper limit specified
rate: 0.1

Binary file modified target/classes/org/cubexmc/ecobalancer/EcoBalancer$1.class
Binary file not shown.
Binary file modified target/classes/org/cubexmc/ecobalancer/EcoBalancer.class
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@ org\cubexmc\ecobalancer\EcoBalancer.class
org\cubexmc\ecobalancer\commands\CheckPlayerCommand.class
org\cubexmc\ecobalancer\commands\CheckAllCommand.class
org\cubexmc\ecobalancer\EcoBalancer$1.class
org\cubexmc\ecobalancer\commands\CheckAllCommand$1BatchRunnable.class
Binary file modified target/original-EcoBalancer-1.0-SNAPSHOT.jar
Binary file not shown.

0 comments on commit 3ce732f

Please sign in to comment.