Skip to content

Commit

Permalink
Now rewards factory can execute a list of commands
Browse files Browse the repository at this point in the history
  • Loading branch information
Despical committed Jun 23, 2023
1 parent fca790c commit 93ebad7
Show file tree
Hide file tree
Showing 10 changed files with 163 additions and 151 deletions.
2 changes: 1 addition & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

<groupId>me.despical</groupId>
<artifactId>one-in-the-chamber</artifactId>
<version>2.3.8</version>
<version>2.3.9</version>
<name>One In The Chamber</name>

<properties>
Expand Down
4 changes: 2 additions & 2 deletions src/main/java/me/despical/oitc/ConfigPreferences.java
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,8 @@ public enum Option {
BLOCK_COMMANDS, BOSS_BAR_ENABLED, BUNGEE_ENABLED(false), CHAT_FORMAT_ENABLED, DATABASE_ENABLED(false),
DISABLE_FALL_DAMAGE(false), DISABLE_LEAVE_COMMAND(false), DISABLE_SEPARATE_CHAT(false),
ENABLE_SHORT_COMMANDS, IGNORE_WARNING_MESSAGES(false), INVENTORY_MANAGER_ENABLED, NAME_TAGS_HIDDEN,
REWARDS_ENABLED(false), SEND_SETUP_TIPS, SIGNS_BLOCK_STATES_ENABLED, UPDATE_NOTIFIER_ENABLED,
REGEN_ENABLED(false), LEVEL_COUNTDOWN_ENABLED(false), DISABLE_SPECTATING_ON_BUNGEE(false);
SEND_SETUP_TIPS, SIGNS_BLOCK_STATES_ENABLED, UPDATE_NOTIFIER_ENABLED, REGEN_ENABLED(false),
LEVEL_COUNTDOWN_ENABLED(false), DISABLE_SPECTATING_ON_BUNGEE(false);

final String path;
final boolean def;
Expand Down
5 changes: 3 additions & 2 deletions src/main/java/me/despical/oitc/Main.java
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,6 @@ public class Main extends JavaPlugin {

@Override
public void onEnable() {
setupFiles();
initializeClasses();
checkUpdate();

Expand Down Expand Up @@ -109,6 +108,8 @@ public void onDisable() {
}

private void initializeClasses() {
setupFiles();

configPreferences = new ConfigPreferences(this);
chatManager = new ChatManager(this);
languageManager = new LanguageManager(this);
Expand Down Expand Up @@ -158,7 +159,7 @@ private void checkUpdate() {
if (result.requiresUpdate()) {
getLogger().info("Found a new version available: v" + result.getNewestVersion());
getLogger().info("Download it SpigotMC:");
getLogger().info("https://www.spigotmc.org/resources/one-in-the-chamber.81185/");
getLogger().info("https://spigotmc.org/resources/81185");
}
});
}
Expand Down
4 changes: 2 additions & 2 deletions src/main/java/me/despical/oitc/arena/ArenaManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -281,14 +281,14 @@ public static void stopGame(boolean quickStop, Arena arena) {

Titles.sendTitle(player, chatManager.message("in_game.messages.game_end_messages.titles.win"), chatManager.message("in_game.messages.game_end_messages.subtitles.win").replace("%winner%", topPlayerName));

plugin.getRewardsFactory().performReward(player, Reward.RewardType.WIN);
plugin.getRewardsFactory().performReward(user, Reward.RewardType.WIN);
} else {
Titles.sendTitle(player, chatManager.message("in_game.messages.game_end_messages.titles.lose"), chatManager.message("in_game.messages.game_end_messages.subtitles.lose").replace("%winner%", topPlayerName));

if (!user.isSpectator()) {
user.addStat(StatsStorage.StatisticType.LOSES, 1);

plugin.getRewardsFactory().performReward(player, Reward.RewardType.LOSE);
plugin.getRewardsFactory().performReward(user, Reward.RewardType.LOSE);
}
}

Expand Down
6 changes: 3 additions & 3 deletions src/main/java/me/despical/oitc/events/Events.java
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ public void onJoinCheckVersion(PlayerJoinEvent event) {
final Player player = event.getPlayer();

player.sendMessage(chatManager.coloredRawMessage("&3[OITC] &bFound an update: v" + result.getNewestVersion() + " Download:"));
player.sendMessage(chatManager.coloredRawMessage("&3>> &bhttps://www.spigotmc.org/resources/one-in-the-chamber.81185/"));
player.sendMessage(chatManager.coloredRawMessage("&3>> &bhttps://spigotmc.org/resources/81185"));
}
}), 25);
}
Expand Down Expand Up @@ -301,7 +301,7 @@ public void onDamageEntity(EntityDamageByEntityEvent e) {
if (!player.getUniqueId().equals(shooter.getUniqueId())) {
e.setDamage(100.0);

plugin.getRewardsFactory().performReward(player, Reward.RewardType.DEATH);
plugin.getRewardsFactory().performReward(plugin.getUserManager().getUser(player), Reward.RewardType.DEATH);
} else {
e.setCancelled(true);
}
Expand Down Expand Up @@ -344,7 +344,7 @@ public void onDeath(PlayerDeathEvent e) {
ItemPosition.addItem(victim.getKiller(), ItemPosition.ARROW, ItemPosition.ARROW.getItem());
plugin.getServer().getScheduler().runTaskLater(plugin, () -> victim.spigot().respawn(), 5);

plugin.getRewardsFactory().performReward(victim.getKiller(), Reward.RewardType.KILL);
plugin.getRewardsFactory().performReward(victimUser, Reward.RewardType.KILL);

if (StatsStorage.getUserStats(victim.getKiller(), StatsStorage.StatisticType.LOCAL_KILLS) == plugin.getConfig().getInt("Winning-Score", 25)) {
ArenaManager.stopGame(false, arena);
Expand Down
118 changes: 69 additions & 49 deletions src/main/java/me/despical/oitc/handlers/rewards/Reward.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,10 @@

package me.despical.oitc.handlers.rewards;

import me.despical.commons.util.Strings;
import org.apache.commons.lang.StringUtils;
import org.bukkit.Bukkit;
import me.despical.oitc.Main;

import java.util.ArrayList;
import java.util.List;

/**
* @author Despical
Expand All @@ -29,75 +30,94 @@
*/
public class Reward {

private String executableCode;

private final double chance;
private final RewardType type;
private final RewardExecutor executor;
private final List<SubReward> rewards;

public Reward(RewardType type, String rawCode) {
public Reward(final Main plugin, final RewardType type, final List<String> rawCodes) {
this.type = type;
String processedCode = rawCode;
this.rewards = new ArrayList<>();

if (rawCode.contains("p:")) {
this.executor = RewardExecutor.PLAYER;
for (final String rawCode : rawCodes) {
this.rewards.add(new SubReward(plugin, rawCode));
}
}

processedCode = StringUtils.replace(processedCode, "p:", "");
} else if (rawCode.contains("script:")) {
this.executor = RewardExecutor.SCRIPT;
public List<SubReward> getRewards() {
return rewards;
}

processedCode = StringUtils.replace(processedCode, "script:", "");
} else {
this.executor = RewardExecutor.CONSOLE;
}
public RewardType getType() {
return type;
}

final static class SubReward {

private String executableCode;
private final int chance, executor;

public SubReward(final Main plugin, final String rawCode) {
String processedCode = rawCode;

if (processedCode.contains("chance(")) {
int loc = processedCode.indexOf(")");
if (rawCode.contains("p:")) {
this.executor = 2;

if (loc == -1) {
Bukkit.getConsoleSender().sendMessage(Strings.format("&cRewards configuration is broken! Make sure you don't forget using ')' character in chance condition! Command: " + rawCode));
this.chance = 101;
return;
processedCode = processedCode.replace("p:", "");
} else if (rawCode.contains("script:")) {
this.executor = 3;

processedCode = processedCode.replace("script:", "");
} else {
this.executor = 1;
}

String chanceStr = processedCode;
chanceStr = chanceStr.substring(0, loc).replaceAll("[^0-9]+", "");
processedCode = StringUtils.replace(processedCode, "chance(" + chanceStr + "):", "");
this.chance = Double.parseDouble(chanceStr);
} else {
this.chance = 100;
}
if (processedCode.contains("chance(")) {
int loc = processedCode.indexOf(")");

this.executableCode = processedCode;
}
if (loc == -1) {
plugin.getLogger().warning(String.format("Second '')'' is not found in chance condition! Command: %s", rawCode));

public RewardExecutor getExecutor() {
return executor;
}
this.chance = 101;
return;
}

public String getExecutableCode() {
return executableCode;
}
String chanceStr = processedCode;
chanceStr = chanceStr.substring(0, loc).replaceAll("[^0-9]+", "");

public double getChance() {
return chance;
}
processedCode = processedCode.replace(String.format("chance(%s):", chanceStr), "");

public RewardType getType() {
return type;
this.chance = Integer.parseInt(chanceStr);
} else {
this.chance = 100;
}

this.executableCode = processedCode;
}

public String getExecutableCode() {
return executableCode;
}

public int getExecutor() {
return executor;
}

public int getChance() {
return chance;
}
}

public enum RewardType {
KILL("kill"), DEATH("death"), END_GAME("endgame"), LOSE("lose"), WIN("win");

KILL("kill"),
DEATH("death"),
END_GAME("endgame"),
LOSE("lose"),
WIN("win");

final String path;

RewardType(String path) {
this.path = "rewards." + path;
}
}

public enum RewardExecutor {
CONSOLE, PLAYER, SCRIPT
}
}
102 changes: 43 additions & 59 deletions src/main/java/me/despical/oitc/handlers/rewards/RewardsFactory.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,17 +20,17 @@

import me.despical.commons.configuration.ConfigUtils;
import me.despical.commons.engine.ScriptEngine;
import me.despical.oitc.ConfigPreferences;
import me.despical.oitc.Main;
import me.despical.oitc.arena.Arena;
import me.despical.oitc.arena.ArenaRegistry;
import org.apache.commons.lang.StringUtils;
import me.despical.oitc.user.User;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;

/**
* @author Despical
Expand All @@ -42,78 +42,62 @@ public class RewardsFactory {
private final Main plugin;
private final Set<Reward> rewards;

public RewardsFactory(Main plugin) {
public RewardsFactory(final Main plugin) {
this.plugin = plugin;
this.rewards = new HashSet<>();

registerRewards();
}

public void performReward(Arena arena, Reward.RewardType type) {
if (rewards.isEmpty()) {
return;
}

for (Player player : arena.getPlayers()) {
performReward(player, type);
}
}

public void performReward(Player player, Reward.RewardType type) {
Arena arena = ArenaRegistry.getArena(player);
Reward reward = rewards.stream().filter(rew -> rew.getType() == type).findFirst().orElse(null);

if (reward == null) {
return;
}

if (ThreadLocalRandom.current().nextInt(0, 100) > reward.getChance()) {
return;
}

String command = formatCommandPlaceholders(reward.getExecutableCode(), arena, player);

switch (reward.getExecutor()) {
case CONSOLE:
plugin.getServer().dispatchCommand(plugin.getServer().getConsoleSender(), command);
break;
case PLAYER:
player.performCommand(command);
break;
case SCRIPT:
ScriptEngine engine = new ScriptEngine();

engine.setValue("player", player);
engine.setValue("server", plugin.getServer());
engine.setValue("arena", arena);
engine.execute(command);
break;
default:
break;
public void performReward(final User user, final Reward.RewardType type) {
final List<Reward> rewardList = rewards.stream().filter(rew -> rew.getType() == type).collect(Collectors.toList());

if (rewardList.isEmpty()) return;

for (final Reward mainRewards : rewardList) {
for (final Reward.SubReward reward : mainRewards.getRewards()){
if (ThreadLocalRandom.current().nextInt(0, 100) > reward.getChance()) continue;

final Arena arena = user.getArena();
final Player player = user.getPlayer();
final String command = formatCommandPlaceholders(reward, user);

switch (reward.getExecutor()) {
case 1:
plugin.getServer().dispatchCommand(plugin.getServer().getConsoleSender(), command);
break;
case 2:
player.performCommand(command);
break;
case 3:
final ScriptEngine engine = new ScriptEngine();
engine.setValue("player", player);
engine.setValue("server", plugin.getServer());
engine.setValue("arena", arena);
engine.execute(command);
}
}
}
}

private String formatCommandPlaceholders(String command, Arena arena, Player player) {
String formatted = command;
private String formatCommandPlaceholders(final Reward.SubReward reward, final User user) {
Arena arena = user.getArena();
String formatted = reward.getExecutableCode();

formatted = StringUtils.replace(formatted, "%arena_id%", arena.getId());
formatted = StringUtils.replace(formatted, "%map_name%", arena.getMapName());
formatted = StringUtils.replace(formatted, "%player%", player.getName());
formatted = StringUtils.replace(formatted, "%players%", Integer.toString(arena.getPlayers().size()));
formatted = formatted.replace("%arena%", arena.getId());
formatted = formatted.replace("%map_name%", arena.getMapName());
formatted = formatted.replace("%player%", user.getName());
formatted = formatted.replace("%players%", Integer.toString(arena.getPlayers().size()));
return formatted;
}

private void registerRewards() {
if (!plugin.getConfigPreferences().getOption(ConfigPreferences.Option.REWARDS_ENABLED)) {
return;
}
final FileConfiguration config = ConfigUtils.getConfig(plugin, "rewards");

FileConfiguration config = ConfigUtils.getConfig(plugin, "rewards");
if (!config.getBoolean("Rewards-Enabled")) return;

for (Reward.RewardType rewardType : Reward.RewardType.values()) {
for (String reward : config.getStringList(rewardType.path)) {
rewards.add(new Reward(rewardType, reward));
}
for (final Reward.RewardType rewardType : Reward.RewardType.values()) {
rewards.add(new Reward(plugin, rewardType, config.getStringList(rewardType.path)));
}
}
}
4 changes: 4 additions & 0 deletions src/main/java/me/despical/oitc/user/User.java
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,10 @@ public Player getPlayer() {
return player;
}

public String getName() {
return player.getName();
}

public UUID getUniqueId() {
return uuid;
}
Expand Down
Loading

0 comments on commit 93ebad7

Please sign in to comment.