Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Gamefreak rewrite update bug fixes #109

Open
wants to merge 3 commits into
base: rewrite
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
93 changes: 62 additions & 31 deletions src/main/java/com/codehusky/huskycrates/HuskyCrates.java
Original file line number Diff line number Diff line change
@@ -1,53 +1,60 @@
package com.codehusky.huskycrates;

import com.codehusky.huskycrates.command.BalanceCommand;
import com.codehusky.huskycrates.command.BlockCommand;
import com.codehusky.huskycrates.command.CommandRegister;
import com.codehusky.huskycrates.command.KeyCommand;
import com.codehusky.huskycrates.crate.listeners.CrateListeners;
import com.codehusky.huskycrates.crate.listeners.SQLUpdateListener;
import com.codehusky.huskycrates.crate.physical.EffectInstance;
import com.codehusky.huskycrates.crate.physical.PhysicalCrate;
import com.codehusky.huskycrates.crate.virtual.Crate;
import com.codehusky.huskycrates.crate.virtual.Key;
import com.codehusky.huskycrates.event.CrateInjectionEvent;
import com.codehusky.huskycrates.exception.ConfigParseError;
import com.google.inject.Inject;
import ninja.leaping.configurate.commented.CommentedConfigurationNode;
import ninja.leaping.configurate.hocon.HoconConfigurationLoader;
import ninja.leaping.configurate.loader.ConfigurationLoader;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.ConcurrentModificationException;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spongepowered.api.Sponge;
import org.spongepowered.api.config.ConfigDir;
import org.spongepowered.api.config.DefaultConfig;
import org.spongepowered.api.data.DataQuery;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.event.Listener;
import org.spongepowered.api.event.block.ChangeBlockEvent;
import org.spongepowered.api.event.cause.Cause;
import org.spongepowered.api.event.cause.EventContextKeys;
import org.spongepowered.api.event.game.GameReloadEvent;
import org.spongepowered.api.event.game.state.GamePostInitializationEvent;
import org.spongepowered.api.event.game.state.GamePreInitializationEvent;
import org.spongepowered.api.event.game.state.GameStartedServerEvent;
import org.spongepowered.api.event.game.state.GameStoppingServerEvent;
import org.spongepowered.api.item.inventory.ItemStackSnapshot;
import org.spongepowered.api.plugin.Dependency;
import org.spongepowered.api.plugin.Plugin;
import org.spongepowered.api.plugin.PluginContainer;
import org.spongepowered.api.scheduler.Task;
import org.spongepowered.api.world.Location;
import org.spongepowered.api.world.World;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.ConcurrentModificationException;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import com.codehusky.huskycrates.command.BalanceCommand;
import com.codehusky.huskycrates.command.BlockCommand;
import com.codehusky.huskycrates.command.CommandRegister;
import com.codehusky.huskycrates.command.KeyCommand;
import com.codehusky.huskycrates.crate.listeners.CrateListeners;
import com.codehusky.huskycrates.crate.listeners.SQLUpdateListener;
import com.codehusky.huskycrates.crate.physical.EffectInstance;
import com.codehusky.huskycrates.crate.physical.PhysicalCrate;
import com.codehusky.huskycrates.crate.virtual.Crate;
import com.codehusky.huskycrates.crate.virtual.Key;
import com.codehusky.huskycrates.event.CrateInjectionEvent;
import com.codehusky.huskycrates.exception.ConfigParseError;
import com.google.inject.Inject;

import ninja.leaping.configurate.commented.CommentedConfigurationNode;
import ninja.leaping.configurate.hocon.HoconConfigurationLoader;
import ninja.leaping.configurate.loader.ConfigurationLoader;


@Plugin(
Expand All @@ -57,6 +64,8 @@
description = "A Crate Plugin for Sponge!",
dependencies = {@Dependency(id="huskyui",version = "0.6.0PRE4"), @Dependency(id="placeholderapi", optional = true)})
public class HuskyCrates {
// Added blockplace event to prevent keys to be placed

//@Inject
public Logger logger;

Expand Down Expand Up @@ -148,7 +157,8 @@ public void gameInit(GamePreInitializationEvent event){
private int iterations = 0;
private long lastMessage = 0;
@Listener
public void gamePostInit(GamePreInitializationEvent event){
// pre to post, prevent hc from being loaded before worlds are loaded
public void gamePostInit(GamePostInitializationEvent event){
crateListeners = new CrateListeners();
Sponge.getEventManager().registerListeners(this,crateListeners);
}
Expand Down Expand Up @@ -421,4 +431,25 @@ public void gameShutdown(GameStoppingServerEvent event){
logger.info("HuskyCrates has shut down.");
}

/**
*
* Prevent block placement if block is a (potential) key (no accidental loss in keys by placement (lever, tripwire-hook ... ) )
* @param e
*
*/
@Listener
public void onBlockPlaced(ChangeBlockEvent.Place e) {
if (e.getSource() instanceof Player) {
ItemStackSnapshot item = e.getCause().getContext().get(EventContextKeys.USED_ITEM).orElse(null); // get item placed
if (item == null) { //check if item not null (prevent possible issues by wrong place detection)
return;
}

if (item.toContainer().get(DataQuery.of("UnsafeData", "HCKEYID")).isPresent()) { // check if item is a key
e.setCancelled(true); // cancel the block placement.
}


}
}
}
56 changes: 38 additions & 18 deletions src/main/java/com/codehusky/huskycrates/command/BalanceCommand.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,16 @@

import com.codehusky.huskycrates.HuskyCrates;
import ninja.leaping.configurate.ConfigurationNode;

import org.spongepowered.api.Sponge;
import org.spongepowered.api.command.CommandException;
import org.spongepowered.api.command.CommandResult;
import org.spongepowered.api.command.CommandSource;
import org.spongepowered.api.command.args.CommandContext;
import org.spongepowered.api.command.spec.CommandExecutor;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.entity.living.player.User;
import org.spongepowered.api.service.user.UserStorageService;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.text.format.TextColors;
import org.spongepowered.api.text.serializer.TextSerializers;
Expand All @@ -21,38 +24,53 @@
public class BalanceCommand implements CommandExecutor {
@Override
public CommandResult execute(CommandSource src, CommandContext args) throws CommandException {
/*
.arguments(GenericArguments.optionalWeak(GenericArguments.user(Text.of("player"))),
GenericArguments.optionalWeak(GenericArguments.uuid(Text.of("uuid"))),
GenericArguments.optionalWeak(GenericArguments.string(Text.of("username"))))
*/
Optional<User> user = args.getOne(Text.of("player"));
Optional<UUID> uuid = args.getOne(Text.of("uuid"));
Optional<String> username = args.getOne(Text.of("username"));

// Added bal others + fix username + change player to user
User user = (User)args.getOne(Text.of("player")).orElse(null); // default null
UUID uuid = (UUID)args.getOne(Text.of("uuid")).orElse(null); // default null
String username = (String)args.getOne(Text.of("username")).orElse(null);

UUID balanceToUse = (src instanceof Player)?((Player) src).getUniqueId():null;

if(user.isPresent()){
if(user != null){
if(!src.hasPermission("huskycrates.bal.others")){
src.sendMessage(Text.of(TextColors.RED,"You do not have permission to view the balance of others."));
return CommandResult.success();
}

src.sendMessage(HuskyCrates.balanceCommandMessages.getOtherBalanceHeader(user.get().getName()));
}else if(uuid.isPresent()){
// overwrite balance to check
balanceToUse = user.getUniqueId();
src.sendMessage(HuskyCrates.balanceCommandMessages.getOtherBalanceHeader(user.getName()));
}else if(uuid != null){
if(!src.hasPermission("huskycrates.bal.others")){
src.sendMessage(Text.of(TextColors.RED,"You do not have permission to view the balance of others."));
return CommandResult.success();
}

src.sendMessage(HuskyCrates.balanceCommandMessages.getUUIDBalanceHeader(uuid.get().toString()));
}else if(username.isPresent()){
// overwrite balance to check
balanceToUse = uuid;
src.sendMessage(HuskyCrates.balanceCommandMessages.getUUIDBalanceHeader(uuid.toString()));
}else if(username != null){
if(!src.hasPermission("huskycrates.bal.others")){
src.sendMessage(Text.of(TextColors.RED,"You do not have permission to view the balance of others."));
return CommandResult.success();
}

// Get user by (last known) username
Optional<UserStorageService> service = Sponge.getServiceManager().provide(UserStorageService.class);
if( service.get() != null&& service.isPresent() ) {
User us = service.get().get(username).isPresent()?service.get().get(username).get():null;
if(us == null) { // user does not exist
src.sendMessage(HuskyCrates.balanceCommandMessages.getUserNotExist(username));
return CommandResult.success();
}
// user does exist
src.sendMessage(HuskyCrates.balanceCommandMessages.getUUIDBalanceHeader(us.getName()));
// overwrite balance to check
balanceToUse = us.getUniqueId();
}else { // no service, so no user
src.sendMessage(HuskyCrates.balanceCommandMessages.getUserNotExist(username));
return CommandResult.success();
}

src.sendMessage(HuskyCrates.balanceCommandMessages.getUserNotExist(username.get()));
return CommandResult.success();
}else{
src.sendMessage(HuskyCrates.balanceCommandMessages.getSelfBalanceHeader());
Expand All @@ -66,8 +84,10 @@ public CommandResult execute(CommandSource src, CommandContext args) throws Comm
HashMap<String, Integer> balances = HuskyCrates.registry.getVirtualKeyBalances(balanceToUse);

for(Map.Entry<String, Integer> entry : balances.entrySet()){
String keyID = entry.getKey();
src.sendMessage(HuskyCrates.balanceCommandMessages.getBalanceRow(HuskyCrates.registry.getKey(keyID).getName(),keyID,entry.getValue()));
if(entry.getValue() > 0) { // decrease huge lists with 0 keys
String keyID = entry.getKey();
src.sendMessage(HuskyCrates.balanceCommandMessages.getBalanceRow(HuskyCrates.registry.getKey(keyID).getName(),keyID,entry.getValue()));
}
}

if(balances.size() == 0){
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,8 @@ public static void register(HuskyCrates plugin) {
.executor(new KeyCommand())
.arguments(GenericArguments.optionalWeak(GenericArguments.literal(Text.of("virtual"),"v")),
GenericArguments.firstParsing(new CrateArgument(Text.of("crate")), new KeyArgument(Text.of("key"))),
GenericArguments.optional(GenericArguments.firstParsing(GenericArguments.literal(Text.of("all"),"@a"), GenericArguments.player(Text.of("player")))),
// user to check offline players balances
GenericArguments.optional(GenericArguments.firstParsing(GenericArguments.literal(Text.of("all"),"@a"), GenericArguments.user(Text.of("player")))),
GenericArguments.optionalWeak(GenericArguments.integer(Text.of("amount"))))
.permission("huskycrates.key.base")
.build(),"k","key")
Expand All @@ -53,6 +54,7 @@ public static void register(HuskyCrates plugin) {
.build(),"o","open","use")
.child(CommandSpec.builder()
.executor(new BalanceCommand())
// change player to user for offline user
.arguments(GenericArguments.optionalWeak(GenericArguments.user(Text.of("player"))),
GenericArguments.optionalWeak(GenericArguments.uuid(Text.of("uuid"))),
GenericArguments.optionalWeak(GenericArguments.string(Text.of("username"))))
Expand Down
26 changes: 19 additions & 7 deletions src/main/java/com/codehusky/huskycrates/command/KeyCommand.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import org.spongepowered.api.command.args.CommandContext;
import org.spongepowered.api.command.spec.CommandExecutor;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.entity.living.player.User;
import org.spongepowered.api.item.inventory.transaction.InventoryTransactionResult;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.text.format.TextColors;
Expand All @@ -22,12 +23,13 @@
public class KeyCommand implements CommandExecutor {
@Override
public CommandResult execute(CommandSource src, CommandContext args) throws CommandException {
// change player to user and add "(not enough space)" to getKeyDeliveryFail when issue of not giving key is full inventory
Optional<Crate> crate = args.getOne(Text.of("crate"));
Optional<Key> key = args.getOne(Text.of("key"));
Optional<Integer> pamount = args.getOne(Text.of("amount"));
boolean isVirtual = args.getOne(Text.of("virtual")).isPresent();

Optional<Player> player = args.getOne(Text.of("player"));
User player = (User)args.getOne(Text.of("player")).orElse(null);
Optional<String> all = args.getOne(Text.of("all"));

Key workingWith = null;
Expand Down Expand Up @@ -79,23 +81,33 @@ public CommandResult execute(CommandSource src, CommandContext args) throws Comm
}
src.sendMessage(HuskyCrates.keyCommandMessages.getMassKeyDeliverySuccess(deliveredTo,amount));

}else if(player.isPresent()){ /** Deliver keys to a player **/
}else if(player!=null){ /** Deliver keys to a player **/
if(!src.hasPermission("huskycrates.key.others")){
src.sendMessage(Text.of(TextColors.RED,"You do not have permission to give others keys."));
return CommandResult.success();
}
InventoryTransactionResult result = null;

if(!isVirtual)
result = Util.getHotbarFirst(player.get().getInventory()).offer(workingWith.getKeyItemStack(amount));
result = Util.getHotbarFirst(player.getInventory()).offer(workingWith.getKeyItemStack(amount));
else
HuskyCrates.registry.addVirtualKeys(player.get().getUniqueId(),workingWith.getId(),amount);
HuskyCrates.registry.addVirtualKeys(player.getUniqueId(),workingWith.getId(),amount);

if(!isVirtual && result.getType() != InventoryTransactionResult.Type.SUCCESS){
src.sendMessage(HuskyCrates.keyCommandMessages.getKeyDeliveryFail(player.get().getName(),amount));
// on fail, check if it's full space and add not enough space if inventory full, making more clear if target has full inventory
if(player.getInventory().first().canFit(workingWith.getKeyItemStack(amount))) {
src.sendMessage(HuskyCrates.keyCommandMessages.getKeyDeliveryFail(player.getName(),amount).concat(Text.of(" (Not enough space)")));
}else {
src.sendMessage(HuskyCrates.keyCommandMessages.getKeyDeliveryFail(player.getName(),amount));

}
}else{
player.get().sendMessage(HuskyCrates.keyCommandMessages.getReceivedKey(keyName,amount));
src.sendMessage(HuskyCrates.keyCommandMessages.getKeyDeliverySuccess(player.get().getName(),amount));
if(player.isOnline() ){ // Send message if player (user) is online
player.getPlayer().get().sendMessage(HuskyCrates.keyCommandMessages.getReceivedKey(keyName,amount));
}
HuskyCrates.registry.addVirtualKeys(player.getUniqueId(),workingWith.getId(),amount);

src.sendMessage(HuskyCrates.keyCommandMessages.getKeyDeliverySuccess(player.getName(),amount));
}

}else if(src instanceof Player) { /** Deliver keys to self **/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@
import java.util.*;

public class Crate {

// change slotChanceMax to double, prevent wrong chances being displayed
private String id;
private String name;

Expand All @@ -47,7 +49,7 @@ public class Crate {

private List<Slot> slots;

private int slotChanceMax = 0;
private double slotChanceMax = 0;

private Boolean scrambleSlots;

Expand Down Expand Up @@ -260,7 +262,7 @@ public String getId() {

public int selectSlot() {
int chanceCuml = 0;
int selection = new Random().nextInt(slotChanceMax+1);
int selection = new Random().nextInt((int)Math.floor(slotChanceMax+1));
for(int i = 0; i < slots.size(); i++){
chanceCuml += slots.get(i).getChance();
if(selection <= chanceCuml){
Expand Down Expand Up @@ -479,7 +481,7 @@ public void launchPreview(Player player){
for(int j = 0; j < slots.size(); j++) {
ItemStack orig = slots.get(j).getDisplayItem().toItemStack();
List<Text> oldLore = orig.getOrElse(Keys.ITEM_LORE,new ArrayList<>());
double val = ((double)slots.get(j).getChance()/(double)slotChanceMax)*100;
double val = (slots.get(j).getChance() / slotChanceMax)*100;
BigDecimal occurance = new BigDecimal(val).setScale(2,BigDecimal.ROUND_HALF_UP);
if (previewShowsRewardCount) {
oldLore.add(Text.of(TextStyles.NONE,TextColors.GRAY,"Rewards: " + slots.get(j).getRewards().size()));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ public class SpinnerView implements Consumer<Page> {
private Config config;

public SpinnerView(Crate ucrate, Player player, Location loc){
// Added if-clause at interrupt, to prevent players from "picking" a reward by closing gui
this.crate = ucrate;
if(this.crate.isScrambled()){
this.crate = ucrate.getScrambledCrate();
Expand All @@ -56,7 +57,13 @@ public SpinnerView(Crate ucrate, Player player, Location loc){
.setInterrupt(() -> {
if(rewardGiven) return;
try {
crate.getSlot(selectedSlot).rewardPlayer(player, this.physicalLocation);
// check if player has won, otherwise give the slot of selected slot + 4 (restarts when max slots is succeeded)
// prevents player from picking their reward
if(hasWon) {
crate.getSlot(selectedSlot).rewardPlayer(player, this.physicalLocation);
}else {
crate.getSlot(selectedSlot+4 %(crate.getSlots().size()-1)).rewardPlayer(player, this.physicalLocation);
}
player.playSound(SoundTypes.ENTITY_EXPERIENCE_ORB_PICKUP, player.getLocation().getPosition(), 0.5);
}catch (Exception e){
e.printStackTrace();
Expand Down