Skip to content

Instantly share code, notes, and snippets.

@aikar
Created June 13, 2014 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aikar/830d26a74a6794f2c67b to your computer and use it in GitHub Desktop.
Save aikar/830d26a74a6794f2c67b to your computer and use it in GitHub Desktop.
package com.empireminecraft.systems;
import com.empireminecraft.config.EmpireConfig;
import com.empireminecraft.config.meta.EmpireMetaKey;
import com.empireminecraft.data.EmpireUser;
import com.empireminecraft.data.items.PromoItems;
import com.empireminecraft.data.items.VotingItems;
import com.empireminecraft.systems.currency.Rupees;
import com.empireminecraft.features.items.CustomItem;
import com.empireminecraft.systems.db.DbRow;
import com.empireminecraft.systems.db.DbStatement;
import com.empireminecraft.util.TaskChain;
import com.empireminecraft.util.Util;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
import java.util.ArrayList;
import java.util.List;
import static com.empireminecraft.features.Mail.sendSystemMail;
public class Voting {
public static void creditVote(final String player, final String service) {
if (!EmpireUser.validateUsername(player)) {
Util.log("[vote] Could not validate user name " + player);
return;
}
if (service == null) {
Util.logWarning("[vote] Player " + player + " voted with unknown service");
return;
}
TaskChain.newChain().add(new TaskChain.GenericTask() {
@Override
protected void run() {
new VotingRewards(player, service);
}
}).execute();
}
static class VotingRewards {
Long userId;
Long voteBonus;
Long lastVote;
Long voteMax;
Long voteMissed;
Long yesterday;
Long midnight;
Long timestamp;
int voteRupees;
String player;
String service;
VotingRewards(String name, String service) {
player = name;
this.service = service;
try (DbStatement stm = new DbStatement()) {
stm.startTransaction();
stm.query("SELECT " +
"lastvote, votebonus,voteitembonus, " +
"user_id, votemax,votelastmiss " +
"FROM user WHERE name = ? FOR UPDATE");
stm.execute(player);
DbRow rs = stm.getNextRow();
if (rs == null) {
Util.log("[vote] Could not find user '" + player + "' for '" + service + "'");
return;
}
userId = rs.get("user_id");
voteBonus = rs.get("votebonus");
lastVote = rs.get("lastvote");
voteMax = rs.get("votemax");
voteMissed = rs.get("votelastmiss");
voteRupees = EmpireConfig.get().getInt("vote-rewards." + Util.simplifyString(service), 100);
timestamp = System.currentTimeMillis() / 1000;
final EmpireUser user = EmpireUser.getUser(player);
if (user == null) {
return;
}
player = user.getName();
boolean newVoteBonus = false;
if (timestamp - lastVote < (60*60*36)) {
Long lastBonus = user.getMeta(EmpireMetaKey.VOTE_LAST_BONUS).getLong();
if (lastBonus == null || timestamp - lastBonus > (60*60*16)) {
voteRupees += 100;
voteRupees += Math.min(voteBonus++ * 10, 500);
newVoteBonus = true;
processRupeeBonus();
processItemBonus();
processTokenBonus();
user.setMeta(EmpireMetaKey.VOTE_LAST_BONUS, timestamp);
} else {
user.setMeta(EmpireMetaKey.VOTE_LAST_BONUS, lastBonus - (60*90));
}
} else if (lastVote < timestamp - (60 * 60 * 24 * 3)) { // 3 day window before losing streak
long daysMissed = (long) Math.floor((timestamp - lastVote) / (60 * 60 * 24));
voteBonus = Math.max(0, voteBonus - daysMissed);
voteMissed = timestamp;
user.setMeta(EmpireMetaKey.VOTE_LAST_BONUS, timestamp);
}
lastVote = timestamp;
stm.query("UPDATE user SET votes = votes + 1, "
+ " lastvote = ?, votebonus = ?, votemax = ?, votelastmiss = ? WHERE user_id = ?");
stm.executeUpdate(
lastVote,
voteBonus,
Math.max(voteBonus, voteMax),
voteMissed,
userId);
stm.commit();
Rupees.credit(userId, voteRupees, 31, service + " - day bonus: " + voteBonus);
Util.notifyPlayer(player, "&aYou successfully voted on&f " + service + " &aand earned &f" + voteRupees + "&a rupees!");
if (user.currentServer != null) {
CommandQueue.queueServerCommand(user.currentServer, "updatevote " + user.name + " " + lastVote + " " + voteBonus);
}
if (newVoteBonus) {
Util.notifyPlayer(player, "&aYour vote bonus is now &f" + voteBonus + "&a! Keep up the good work!");
}
Util.log("[vote] '" + player + "' voted on '" + service + "' and earned: " + voteRupees +
" rupees with mod:" + voteBonus);
} catch (Exception e) {
Util.printException("[vote] FAILED for '" + player + "' on '" + service + "'", e);
}
}
private void processTokenBonus() {
int tokens = 0;
/*if (shouldGetEvery(2, "token2")) {
tokens += 50;
}
if (shouldGetEvery(5, "token5")) {
tokens += 100;
}
if (shouldGetEvery(10, "token10")) {
tokens += 500;
}
if (shouldGetEvery(30, "token30")) {
tokens += 2000;
}
if (shouldGetEvery(50, "token50")) {
tokens += 5000;
}
if (shouldGetEvery(100, "token2")) {
tokens += 15000;
}*/
}
private void processRupeeBonus() {
/*
DO NOT add any other logic after shouldGet* - do it BEFORE.
If one of the shouldGetItem returns true, it must deliver item.
*/
if (shouldGetEvery(5, "rupee5")) {
voteRupees += 300;
}
if (shouldGetEvery(15, "rupee15")) {
voteRupees += 1000;
}
if (shouldGetEvery(30, "rupee30")) {
voteRupees += 4000;
}
if (shouldGetEvery(45, "rupee45")) {
voteRupees += 7500;
}
if (shouldGetEvery(50, "rupee50")) {
voteRupees += 25000;
}
if (shouldGetEvery(100, "rupee100")) {
voteRupees += 40000;
}
}
private void processItemBonus() {
List<ItemStack> rewards = new ArrayList<>();
/*
DO NOT add any other logic after shouldGet* - do it BEFORE.
If one of the shouldGetItem returns true, it must deliver item.
*/
if (shouldGetEvery(2, "diamond")) {
rewards.add(CustomItem.newItem(Material.DIAMOND)
.qtyRange(1, Math.max(1, (int) Math.min(5, voteBonus / 5))).getDrop());
}
if (shouldGetEvery(3, "emerald")) {
rewards.add(CustomItem.newItem(Material.EMERALD)
.qtyRange(1, Math.max(1, (int) Math.min(5, voteBonus / 5))).getDrop());
}
if (shouldGetEvery(20, "vaultVoucher")) {
rewards.add(PromoItems.VAULT_VOUCHER);
}
if (shouldGetEvery(50, "stableVoucher")) {
rewards.add(PromoItems.STABLE_VOUCHER);
}
if (shouldGetAt(20, "votersBoots")) {
rewards.add(VotingItems.makeVotingItem(player, VotingItems.VOTERS_BOOTS));
}
if (shouldGetAt(30, "votersHead")) {
rewards.add(VotingItems.makeVotingItem(player, VotingItems.VOTERS_HEAD));
}
if (shouldGetAt(40, "votersLegs")) {
rewards.add(VotingItems.makeVotingItem(player, VotingItems.VOTERS_LEGS));
}
if (shouldGetAt(60, "votersChest")) {
rewards.add(VotingItems.makeVotingItem(player, VotingItems.VOTERS_CHEST));
}
if (shouldGetAt(100, "tyCertificate")) {
rewards.add(VotingItems.makeVotingThankYou(player));
}
if (!rewards.isEmpty()) {
sendSystemMail(player, "Vote Bonus " + voteBonus + " Reward",
rewards.toArray(new ItemStack[rewards.size()]));
}
}
private boolean shouldGetEvery(int i, String key) {
if (shouldGetAt(i, key)) {
return true;
} else if ((voteBonus % i == 0) && !hasMetaKey(key + voteBonus)) {
setMetaKey(key + voteBonus);
return true;
}
return false;
}
private boolean shouldGetAt(int i, String key) {
if (voteBonus >= i && !hasMetaKey(key + i)) {
setMetaKey(key + i);
return true;
}
return false;
}
private void setMetaKey(String key) {
EmpireMetaKey metaKey = new EmpireMetaKey("votereward." + key, 0);
EmpireUser.getUser(player).setMeta(metaKey, "1");
}
private boolean hasMetaKey(String key) {
EmpireMetaKey metaKey = new EmpireMetaKey("votereward." + key, 0);
return EmpireUser.getUser(player).getMeta(metaKey).getString() != null;
}
}
}
package com.empireminecraft.data.items;
import com.empireminecraft.features.items.CustomItem;
import com.empireminecraft.features.items.CustomItems;
import com.empireminecraft.features.items.UsableCustomItem;
import com.empireminecraft.util.ItemUtil;
import org.bukkit.Material;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
public class VotingItems {
private static final UsableCustomItem VOTING_THANK_YOU = new UsableCustomItem("VotingThankYou", Material.PAPER) {
@Override
public ItemStack onUse(Player player, ItemStack item) {
return null;
}
};
public static final CustomItem VOTERS_CHEST = new CustomItem(Material.LEATHER_CHESTPLATE) {{
ItemUtil.setName(this, "&fVoters Chest");
addUnsafeEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 3);
addUnsafeEnchantment(Enchantment.THORNS, 1);
CustomItems.makeWhiteLeather(this);
}};
public static final CustomItem VOTERS_LEGS = new CustomItem(Material.LEATHER_LEGGINGS) {{
ItemUtil.setName(this, "&fVoters Legs");
addUnsafeEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 2);
CustomItems.makeWhiteLeather(this);
}};
public static final CustomItem VOTERS_HEAD = new CustomItem(Material.LEATHER_HELMET) {{
ItemUtil.setName(this, "&fVoters Helmet");
addUnsafeEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 1);
addUnsafeEnchantment(Enchantment.WATER_WORKER, 5);
addUnsafeEnchantment(Enchantment.OXYGEN, 3);
CustomItems.makeWhiteLeather(this);
}};
public static final CustomItem VOTERS_BOOTS = new CustomItem(Material.LEATHER_BOOTS) {{
ItemUtil.setName(this, "&fVoters Boots");
addUnsafeEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 1);
addUnsafeEnchantment(Enchantment.PROTECTION_FALL, 5);
CustomItems.makeWhiteLeather(this);
}};
public static ItemStack makeVotingItem(String name, ItemStack item) {
item = item.clone();
ItemUtil.buildLore(item)
.setName("&r&f" + name + "'s " + ItemUtil.getName(item))
.add(0, "&6&l&nVoting Reward")
.makeFinal().makeShiny().makeSoulbound().makeUnbreakable().save();
return item;
}
public static ItemStack makeVotingThankYou(String name) {
ItemStack item = VOTING_THANK_YOU.clone();
ItemUtil.buildLore(item)
.setName("&5Thank You to " + name + " from &6Empire Minecraft")
.empty()
.add("&eThis is a certificate of thanks from the")
.add("&6Empire Minecraft &eStaff team for your continued voting")
.add("&eefforts on the Empire. Your vote helps us tremendously.")
.empty()
.add("&eShow this certificate in an item frame with pride!")
.empty()
.add("&eThank You, &6Empire Minecraft")
.makeSoulbound().makeFinal().makeShiny().save();
return item;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment