Skip to content

Commit

Permalink
Merge remote-tracking branch 'refs/remotes/origin/dev'
Browse files Browse the repository at this point in the history
  • Loading branch information
nsporillo committed Sep 8, 2018
2 parents a4e910d + cef1909 commit 11ce28d
Show file tree
Hide file tree
Showing 31 changed files with 575 additions and 182 deletions.
1 change: 1 addition & 0 deletions src/main/java/net/porillo/GlobalWarming.java
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ public void onDisable() {
}

private void registerCommands() {
commandManager.enableUnstableAPI("help");
commandManager.getCommandContexts().registerIssuerOnlyContext(GPlayer.class, c -> tableManager.getPlayerTable().getPlayers().get(c.getPlayer().getUniqueId()));

this.commandManager.registerCommand(new AdminCommands());
Expand Down
64 changes: 41 additions & 23 deletions src/main/java/net/porillo/commands/AdminCommands.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,39 +2,57 @@

import co.aikar.commands.BaseCommand;
import co.aikar.commands.annotation.*;
import net.porillo.database.queue.AsyncDBQueue;
import net.porillo.effect.EffectEngine;
import net.porillo.objects.GPlayer;
import org.bukkit.ChatColor;

@CommandAlias("globalwarming|gw")
public class AdminCommands extends BaseCommand {

@Subcommand("debug effect")
@CommandPermission("globalwarming.admin.debug.effect")
public class EffectCommands extends BaseCommand {

@Subcommand("sealevel")
@Syntax("[level]")
@Description("Force execute a sealevel effect")
public void onSeaLevel(GPlayer gPlayer, String[] args) {
if (args.length < 2) {
int seaLevel = 62;

if (args.length == 1) {
try {
seaLevel = Integer.parseInt(args[0]);
} catch (NumberFormatException e) {
gPlayer.sendMsg(ChatColor.RED + "Invalid SeaLevel");
return;
}
}
@Subcommand("debug")
@CommandPermission("globalwarming.admin.debug")
public class DebugCommands extends BaseCommand {

@Subcommand("database|db")
@Description("Toggles database console logging")
public void onDatabaseDebug(GPlayer gPlayer, String[] args) {
boolean value = AsyncDBQueue.getInstance().isDebug();
AsyncDBQueue.getInstance().setDebug(!value);

EffectEngine.getInstance().testSeaLevelRise(gPlayer.getPlayer().getLocation().getChunk(), seaLevel);
gPlayer.sendMsg(ChatColor.GREEN + String.format("Applying sea level rise from y:%d to chunk", seaLevel));
if (!value) {
gPlayer.sendMsg(ChatColor.GREEN + "Database console logging = " + ChatColor.YELLOW + "true.");
} else {
gPlayer.sendMsg(ChatColor.RED + "Invalid Args");
gPlayer.sendMsg(ChatColor.GREEN + "Database console logging = " + ChatColor.GRAY + "false.");
}
}
}

@Subcommand("effect")
@CommandPermission("globalwarming.admin.debug.effect")
public class EffectCommands extends BaseCommand {

@Subcommand("sealevel")
@Syntax("[level]")
@Description("Force execute Sea Level effect")
public void onSeaLevel(GPlayer gPlayer, String[] args) {
if (args.length < 2) {
int seaLevel = 62;

if (args.length == 1) {
try {
seaLevel = Integer.parseInt(args[0]);
} catch (NumberFormatException e) {
gPlayer.sendMsg(ChatColor.RED + "Invalid SeaLevel");
return;
}
}

EffectEngine.getInstance().testSeaLevelRise(gPlayer.getPlayer().getLocation().getChunk(), seaLevel);
gPlayer.sendMsg(ChatColor.GREEN + String.format("Applying sea level rise from y:%d to chunk", seaLevel));
} else {
gPlayer.sendMsg(ChatColor.RED + "Invalid Args");
}
}
}
}
}
137 changes: 128 additions & 9 deletions src/main/java/net/porillo/commands/GeneralCommands.java
Original file line number Diff line number Diff line change
@@ -1,36 +1,150 @@
package net.porillo.commands;

import co.aikar.commands.BaseCommand;
import co.aikar.commands.CommandHelp;
import co.aikar.commands.annotation.*;
import net.porillo.GlobalWarming;
import net.porillo.database.api.select.GeneralSelection;
import net.porillo.database.api.select.SelectionResult;
import net.porillo.database.queue.AsyncDBQueue;
import net.porillo.database.tables.OffsetTable;
import net.porillo.engine.ClimateEngine;
import net.porillo.engine.models.CarbonIndexModel;
import net.porillo.objects.GPlayer;
import net.porillo.objects.OffsetBounty;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import static org.bukkit.ChatColor.*;

@CommandAlias("globalwarming|gw")
public class GeneralCommands extends BaseCommand {

private Map<UUID, Long> lastTopped = new HashMap<>();
private static final UUID untrackedUUID = UUID.fromString("1-1-1-1-1");
private static final ChatColor[] topHeader = {GOLD, AQUA, LIGHT_PURPLE, AQUA, GOLD, AQUA, LIGHT_PURPLE, AQUA, GOLD,
AQUA, LIGHT_PURPLE, AQUA, GOLD};

@Subcommand("score")
@Description("Get your carbon score")
@CommandPermission("globalwarming.score")
public void onScore(GPlayer gPlayer) {
Player player = Bukkit.getPlayer(gPlayer.getUuid());
player.sendMessage(ChatColor.LIGHT_PURPLE + "Your current carbon footprint is " + formatScore(gPlayer.getCarbonScore()));
player.sendMessage(ChatColor.LIGHT_PURPLE + "Your goal is to keep your score as close to zero as possible!");
String worldName = player.getWorld().getName();
int score = gPlayer.getCarbonScore();

if (ClimateEngine.getInstance().hasClimateEngine(worldName)) {
double index = ClimateEngine.getInstance().getClimateEngine(worldName).getCarbonIndexModel().getCarbonIndex(score);
player.sendMessage(LIGHT_PURPLE + "Your carbon footprint index is " + formatIndex(index));
player.sendMessage(LIGHT_PURPLE + "Your current carbon footprint is " + formatScore(gPlayer.getCarbonScore()));
player.sendMessage(LIGHT_PURPLE + "Your goal is to keep your index above 5");
} else {
player.sendMessage(LIGHT_PURPLE + "Your current overall carbon footprint is " + formatScore(gPlayer.getCarbonScore()));
player.sendMessage(LIGHT_PURPLE + "Your goal is to keep your index above 5");
}
}

@Subcommand("top")
@Description("Display the top ten players")
@CommandPermission("globalwarming.top")
public void onTop(GPlayer gPlayer) {
// Prevent players from spamming /gw top (which syncs the database)
if (lastTopped.containsKey(gPlayer.getUuid())) {
Long last = lastTopped.get(gPlayer.getUuid());
long diff = System.currentTimeMillis() - last;

if (diff < 3000) {
gPlayer.sendMsg(RED + "Please wait " + YELLOW + (3000 - diff) / 1000 + RED + " seconds to view top again.");
} else {
lastTopped.remove(gPlayer.getUuid());
onTop(gPlayer);
}
} else {
lastTopped.put(gPlayer.getUuid(), System.currentTimeMillis());

Player player = Bukkit.getPlayer(gPlayer.getUuid());
String worldName = player.getWorld().getName();

if (ClimateEngine.getInstance().hasClimateEngine(worldName)) {
CarbonIndexModel indexModel = ClimateEngine.getInstance().getClimateEngine(worldName).getCarbonIndexModel();
final String sql = "SELECT uuid,carbonScore FROM players ORDER BY carbonScore ASC LIMIT 10;";

GeneralSelection selection = new GeneralSelection("players", sql) {
@Override
public void onResultArrival(SelectionResult result) throws SQLException {
if (this.getUuid().equals(result.getUuid())) {
ResultSet resultSet = result.getResultSet();
String header = "%s+%s------ %splayer%s ------%s+%s-- %sindex%s --%s+%s-- %sscore%s --%s+";
String footer = "%s+%s------------------%s+%s-----------%s+%s-----------%s+";
gPlayer.sendMsg(String.format(header, topHeader));

String row = DARK_PURPLE + "%d " + WHITE + "%s " + GOLD + "+ %s " + GOLD + "+ %s " + GOLD + "+";
int i = 1;
while (resultSet.next()) {
UUID uuid = UUID.fromString(resultSet.getString(1));
int score = resultSet.getInt(2);
double index = indexModel.getCarbonIndex(score);
String playerName;

if (uuid.equals(untrackedUUID)) {
playerName = "Untracked";
} else {
playerName = Bukkit.getOfflinePlayer(uuid).getName();
}

int pad = i == 10 ? 22 : 23;
gPlayer.sendMsg(String.format(row, i++, fixed(playerName, pad),
fixed(formatIndex(index), 13),
fixed(formatScore(score), 12)));
}

gPlayer.sendMsg(String.format(footer, GOLD, AQUA, GOLD, AQUA, GOLD, AQUA, GOLD));
}
}
};
AsyncDBQueue.getInstance().executeGeneralSelection(selection);
} else {
gPlayer.sendMsg(RED + "This world does not have GlobalWarming enabled.");
}
}
}

public static String fixed(String text, int length) {
return String.format("%-" + length + "." + length + "s", text);
}

private String formatIndex(double index) {
if (index < 3) {
return RED + String.format("%1.4f", index);
} else if (index < 5) {
return YELLOW + String.format("%1.4f", index);
} else if (index > 5) {
return GREEN + String.format("%1.4f", index);
} else if (index > 7) {
return DARK_AQUA + String.format("%1.4f", index);
} else if (index > 9) {
return DARK_GREEN + String.format("%1.4f", index);
} else {
return GRAY + String.format("%1.4f", index);
}
}

// TODO: Make configurable
// TODO: Add more colors
private String formatScore(int score) {
if (score <= 0) {
return ChatColor.GREEN + String.valueOf(score);
return GREEN + String.valueOf(score);
} else if (score <= 500) {
return ChatColor.YELLOW + String.valueOf(score);
return YELLOW + String.valueOf(score);
} else {
return ChatColor.RED + String.valueOf(score);
return RED + String.valueOf(score);
}
}

Expand All @@ -39,16 +153,16 @@ private String formatScore(int score) {
public class BountyCommand extends BaseCommand {

@Subcommand("offset")
@Syntax("[log] [reward]")
@Description("Set tree-planting bounties to reduce carbon footprint")
@Syntax("[log] [reward]")
@CommandPermission("globalwarming.bounty.offset")
public void onBountyOffset(GPlayer gPlayer, String[] args) {
// Validate input
Integer logTarget;
Integer reward;

if (args.length != 2) {
gPlayer.sendMsg(ChatColor.RED + "Must specify 2 args");
gPlayer.sendMsg(RED + "Must specify 2 args");
}
try {
logTarget = Integer.parseInt(args[0]);
Expand All @@ -58,7 +172,7 @@ public void onBountyOffset(GPlayer gPlayer, String[] args) {
throw new NumberFormatException();
}
} catch (NumberFormatException nfe) {
gPlayer.sendMsg(ChatColor.RED + "Error: <trees> and <reward> must be positive integers");
gPlayer.sendMsg(RED + "Error: <trees> and <reward> must be positive integers");
return;
}

Expand All @@ -73,13 +187,14 @@ public void onBountyOffset(GPlayer gPlayer, String[] args) {
// TODO: Add configurable player max concurrent bounties to prevent bounty hoarding
@Subcommand("list")
@Description("Show all current bounties")
@Syntax("")
@CommandPermission("globalwarming.bounty.list")
public void onBounty(GPlayer gPlayer) {
OffsetTable offsetTable = GlobalWarming.getInstance().getTableManager().getOffsetTable();
Player player = gPlayer.getPlayer();

int numBounties = offsetTable.getOffsetList().size();
gPlayer.sendMsg(ChatColor.GREEN + "Showing " + numBounties + " Tree Planting Bounties");
gPlayer.sendMsg(GREEN + "Showing " + numBounties + " Tree Planting Bounties");

// TODO: Paginate if necessary
for (OffsetBounty bounty : offsetTable.getOffsetList()) {
Expand All @@ -91,4 +206,8 @@ public void onBounty(GPlayer gPlayer) {

}

@HelpCommand
public void onHelp(GPlayer gPlayer, CommandHelp help) {
help.showHelp();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package net.porillo.database.api.select;

public abstract class GeneralSelection extends Selection implements SelectionListener {

public GeneralSelection(String tableName, String sql) {
super(tableName, sql);
}
}
8 changes: 8 additions & 0 deletions src/main/java/net/porillo/database/api/select/Selection.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,21 @@
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.UUID;

@Data
@AllArgsConstructor
public class Selection {

private String tableName;
private String sql;
private UUID uuid;

public Selection(String tableName, String sql) {
this.tableName = tableName;
this.sql = sql;
this.uuid = UUID.randomUUID();
}

public ResultSet makeSelection(Connection connection) throws SQLException {
return connection.createStatement().executeQuery(sql);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import lombok.NoArgsConstructor;

import java.sql.ResultSet;
import java.util.UUID;

@Data
@NoArgsConstructor
Expand All @@ -13,4 +14,5 @@ public class SelectionResult {

private String tableName;
private ResultSet resultSet;
private UUID uuid;
}
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public String getSQL() {
public PreparedStatement prepareStatement(Connection connection) throws SQLException {
PreparedStatement preparedStatement = connection.prepareStatement(getSQL());
preparedStatement.setInt(1, furnace.getUniqueID());
preparedStatement.setInt(2, furnace.getOwner().getUniqueId());
preparedStatement.setInt(2, furnace.getOwnerID());
preparedStatement.setString(3, furnace.getLocation().getWorld().getName());
preparedStatement.setInt(4, furnace.getLocation().getBlockX());
preparedStatement.setInt(5, furnace.getLocation().getBlockY());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public String getSQL() {
public PreparedStatement prepareStatement(Connection connection) throws SQLException {
PreparedStatement preparedStatement = connection.prepareStatement(getSQL());
preparedStatement.setInt(1, tree.getUniqueID());
preparedStatement.setInt(2, tree.getOwner().getUniqueId());
preparedStatement.setInt(2, tree.getOwnerID());
preparedStatement.setString(3, tree.getLocation().getWorld().getName());
preparedStatement.setInt(4, tree.getLocation().getBlockX());
preparedStatement.setInt(5, tree.getLocation().getBlockY());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ public WorldInsertQuery(GWorld world) {

@Override
public String getSQL() {
return "INSERT INTO worlds (uniqueID, worldName, firstSeen, carbonValue, seaLevel, size)" +
return "INSERT IGNORE INTO worlds (uniqueID, worldName, firstSeen, carbonValue, seaLevel, size)" +
" VALUES (?,?,?,?,?,?)";
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ public TreeUpdateQuery(Tree tree) {

@Override
public String getSQL() {
return "UPDATE trees SET isSapling = ?, size = ? WHERE uniqueId = ?";
return "UPDATE trees SET sapling = ?, size = ? WHERE uniqueId = ?";
}

@Override
Expand Down

0 comments on commit 11ce28d

Please sign in to comment.