Formatting

Signed-off-by: Grafe <flingelfrank@hotmail.com>
This commit is contained in:
Grafe 2013-05-03 16:08:05 +02:00
parent 3bae71872e
commit 873b54f532
11 changed files with 800 additions and 843 deletions

View File

@ -13,13 +13,13 @@ import org.bukkit.configuration.ConfigurationSection;
import com.dre.brewery.BIngredients;
public class BCauldron {
public static CopyOnWriteArrayList<BCauldron> bcauldrons=new CopyOnWriteArrayList<BCauldron>();
public static CopyOnWriteArrayList<BCauldron> bcauldrons = new CopyOnWriteArrayList<BCauldron>();
private BIngredients ingredients;
private Block block;
private int state;
public BCauldron(Block block,Material ingredient){
public BCauldron(Block block, Material ingredient) {
this.block = block;
this.state = 1;
this.ingredients = new BIngredients();
@ -27,68 +27,66 @@ public class BCauldron {
bcauldrons.add(this);
}
//loading from file
public BCauldron(Block block,BIngredients ingredients,int state){
// loading from file
public BCauldron(Block block, BIngredients ingredients, int state) {
this.block = block;
this.state = state;
this.ingredients = ingredients;
bcauldrons.add(this);
}
public void onUpdate(){
//Check if fire still alive
if(block.getRelative(BlockFace.DOWN).getType() == Material.FIRE ||
block.getRelative(BlockFace.DOWN).getType() == Material.STATIONARY_LAVA ||
block.getRelative(BlockFace.DOWN).getType() == Material.LAVA){
//add a minute to cooking time
public void onUpdate() {
// Check if fire still alive
if (block.getRelative(BlockFace.DOWN).getType() == Material.FIRE || block.getRelative(BlockFace.DOWN).getType() == Material.STATIONARY_LAVA
|| block.getRelative(BlockFace.DOWN).getType() == Material.LAVA) {
// add a minute to cooking time
state++;
}
}
//add an ingredient to the cauldron
public void add(Material ingredient){
// add an ingredient to the cauldron
public void add(Material ingredient) {
ingredients.add(ingredient);
block.getWorld().playEffect(block.getLocation(),Effect.EXTINGUISH,0);
if(state > 1){
block.getWorld().playEffect(block.getLocation(), Effect.EXTINGUISH, 0);
if (state > 1) {
state--;
}
}
//get cauldron from block and add given ingredient
public static boolean ingredientAdd(Block block,Material ingredient){
//if not empty
if(block.getData() != 0){
for(BCauldron bcauldron:bcauldrons){
if(bcauldron.block.equals(block)){
// get cauldron from block and add given ingredient
public static boolean ingredientAdd(Block block, Material ingredient) {
// if not empty
if (block.getData() != 0) {
for (BCauldron bcauldron : bcauldrons) {
if (bcauldron.block.equals(block)) {
bcauldron.add(ingredient);
return true;
}
}
new BCauldron(block,ingredient);
new BCauldron(block, ingredient);
return true;
}
return false;
}
//fills players bottle with cooked brew
public static boolean fill(Player player,Block block){
for(BCauldron bcauldron:bcauldrons){
if(bcauldron.block.equals(block)){
// fills players bottle with cooked brew
public static boolean fill(Player player, Block block) {
for (BCauldron bcauldron : bcauldrons) {
if (bcauldron.block.equals(block)) {
ItemStack potion = bcauldron.ingredients.cook(bcauldron.state);
if(potion != null){
//Bukkit Bug, inventory not updating while in event so this will delay the give
//but could also just use deprecated updateInventory()
giveItem(player,potion);
//player.getInventory().addItem(potion);
//player.getInventory().updateInventory();
if(block.getData() > 3){
block.setData((byte)3);
if (potion != null) {
// Bukkit Bug, inventory not updating while in event so this
// will delay the give
// but could also just use deprecated updateInventory()
giveItem(player, potion);
// player.getInventory().addItem(potion);
// player.getInventory().updateInventory();
if (block.getData() > 3) {
block.setData((byte) 3);
}
block.setData((byte)(block.getData() - 1));
block.setData((byte) (block.getData() - 1));
if(block.getData() == 0){
if (block.getData() == 0) {
bcauldrons.remove(bcauldron);
}
return true;
@ -98,36 +96,37 @@ public class BCauldron {
return false;
}
//reset to normal cauldron
public static void remove(Block block){
for(BCauldron bcauldron:bcauldrons){
if(bcauldron.block.equals(block)){
// reset to normal cauldron
public static void remove(Block block) {
for (BCauldron bcauldron : bcauldrons) {
if (bcauldron.block.equals(block)) {
bcauldrons.remove(bcauldron);
}
}
}
public static void save(ConfigurationSection config){
public static void save(ConfigurationSection config) {
int id = 0;
for(BCauldron cauldron:bcauldrons){
//cauldrons are randomly listed
ConfigurationSection section = config.createSection(""+id);
section.set("block",cauldron.block.getWorld().getName()+"/"+cauldron.block.getX()+"/"+cauldron.block.getY()+"/"+cauldron.block.getZ());
if(cauldron.state != 1){
section.set("state",cauldron.state);
for (BCauldron cauldron : bcauldrons) {
// cauldrons are randomly listed
ConfigurationSection section = config.createSection("" + id);
section.set("block", cauldron.block.getWorld().getName() + "/" + cauldron.block.getX() + "/" + cauldron.block.getY() + "/" + cauldron.block.getZ());
if (cauldron.state != 1) {
section.set("state", cauldron.state);
}
cauldron.ingredients.save(section.createSection("ingredients"));
id++;
}
}
//bukkit bug not updating the inventory while executing event, have to schedule the give
public static void giveItem(final Player player,final ItemStack item){
// bukkit bug not updating the inventory while executing event, have to
// schedule the give
public static void giveItem(final Player player, final ItemStack item) {
P.p.getServer().getScheduler().runTaskLater(P.p, new Runnable() {
public void run() {
player.getInventory().addItem(item);
}
},1L);
}, 1L);
}
}

View File

@ -13,71 +13,70 @@ import org.bukkit.inventory.meta.PotionMeta;
import com.dre.brewery.BRecipe;
import com.dre.brewery.Brew;
public class BIngredients {
public static ArrayList<Material> possibleIngredients=new ArrayList<Material>();
public static ArrayList<BRecipe> recipes=new ArrayList<BRecipe>();
public static Map<Material,String> cookedNames=new HashMap<Material,String>();
public static ArrayList<Material> possibleIngredients = new ArrayList<Material>();
public static ArrayList<BRecipe> recipes = new ArrayList<BRecipe>();
public static Map<Material, String> cookedNames = new HashMap<Material, String>();
private Map<Material,Integer> ingredients=new HashMap<Material,Integer>();
private Map<Material, Integer> ingredients = new HashMap<Material, Integer>();
private int cookedTime;
//Represents ingredients in Cauldron, Brew
//Init a new BIngredients
public BIngredients(){
// Represents ingredients in Cauldron, Brew
// Init a new BIngredients
public BIngredients() {
}
//Init a copy of BIngredients with existing values
public BIngredients(Map<Material,Integer> ingredients,int cookedTime){
// Init a copy of BIngredients with existing values
public BIngredients(Map<Material, Integer> ingredients, int cookedTime) {
this.ingredients.putAll(ingredients);
this.cookedTime = cookedTime;
}
//Add an ingredient to this
public void add(Material ingredient){
if(ingredients.containsKey(ingredient)){
// Add an ingredient to this
public void add(Material ingredient) {
if (ingredients.containsKey(ingredient)) {
int newAmount = ingredients.get(ingredient) + 1;
ingredients.put(ingredient,newAmount);
ingredients.put(ingredient, newAmount);
} else {
this.ingredients.put(ingredient,1);
this.ingredients.put(ingredient, 1);
}
}
//returns an Potion item with cooked ingredients
public ItemStack cook(int state){
// returns an Potion item with cooked ingredients
public ItemStack cook(int state) {
ItemStack potion = new ItemStack(Material.POTION);
PotionMeta potionMeta = (PotionMeta) potion.getItemMeta();
//cookedTime is always time in minutes, state may differ with number of ticks
// cookedTime is always time in minutes, state may differ with number of
// ticks
cookedTime = state;
String cookedName = null;
BRecipe cookRecipe = getCookRecipe();
int uid = Brew.generateUID();
if(cookRecipe != null){
//Potion is best with cooking only, can still be destilled, etc.
int quality =(int) Math.round((getIngredientQuality(cookRecipe) + getCookingQuality(cookRecipe)) / 2.0);
P.p.log("cooked potion has Quality: "+quality);
new Brew(uid,quality,cookRecipe.getAlcohol(),new BIngredients(ingredients,cookedTime));
if (cookRecipe != null) {
// Potion is best with cooking only, can still be destilled, etc.
int quality = (int) Math.round((getIngredientQuality(cookRecipe) + getCookingQuality(cookRecipe)) / 2.0);
P.p.log("cooked potion has Quality: " + quality);
new Brew(uid, quality, cookRecipe.getAlcohol(), new BIngredients(ingredients, cookedTime));
cookedName = cookRecipe.getName(quality);
potion.setDurability(Brew.PotionColor.valueOf(cookRecipe.getColor()).getColorId(false));
} else {
//new base potion
new Brew(uid,new BIngredients(ingredients,cookedTime));
// new base potion
new Brew(uid, new BIngredients(ingredients, cookedTime));
if(state == 0){//TESTING sonst 1
if (state == 0) {// TESTING sonst 1
cookedName = "Schlammiger Sud";
potion.setDurability(Brew.PotionColor.BLUE.getColorId(false));
} else {
for(Material ingredient:ingredients.keySet()){
if(cookedNames.containsKey(ingredient)){
//if more than half of the ingredients is of one kind
if(ingredients.get(ingredient) > (getIngredientsCount() / 2)){
for (Material ingredient : ingredients.keySet()) {
if (cookedNames.containsKey(ingredient)) {
// if more than half of the ingredients is of one kind
if (ingredients.get(ingredient) > (getIngredientsCount() / 2)) {
cookedName = cookedNames.get(ingredient);
potion.setDurability(Brew.PotionColor.CYAN.getColorId(true));
}
@ -85,200 +84,202 @@ public class BIngredients {
}
}
}
if(cookedName == null){
//if no name could be found
if (cookedName == null) {
// if no name could be found
cookedName = "Undefinierbarer Sud";
potion.setDurability(Brew.PotionColor.CYAN.getColorId(true));
}
potionMeta.setDisplayName(cookedName);
//This effect stores the UID in its Duration
potionMeta.addCustomEffect((PotionEffectType.REGENERATION).createEffect((uid * 4),0),true);
// This effect stores the UID in its Duration
potionMeta.addCustomEffect((PotionEffectType.REGENERATION).createEffect((uid * 4), 0), true);
potion.setItemMeta(potionMeta);
return potion;
}
//returns amount of ingredients
private int getIngredientsCount(){
// returns amount of ingredients
private int getIngredientsCount() {
int count = 0;
for(int value:ingredients.values()){
for (int value : ingredients.values()) {
count += value;
}
return count;
}
//best recipe for current state of potion, STILL not always returns the correct one...
public BRecipe getBestRecipe(byte wood,float time){
// best recipe for current state of potion, STILL not always returns the
// correct one...
public BRecipe getBestRecipe(byte wood, float time) {
float quality = 0;
int ingredientQuality = 0;
int cookingQuality = 0;
int woodQuality = 0;
int ageQuality = 0;
BRecipe bestRecipe = null;
for(BRecipe recipe:recipes){
for (BRecipe recipe : recipes) {
ingredientQuality = getIngredientQuality(recipe);
cookingQuality = getCookingQuality(recipe);
if(ingredientQuality > -1){
P.p.log("Ingredient Quality: "+ingredientQuality+" Cooking Quality: "+cookingQuality+" Wood Quality: "+getWoodQuality(recipe,wood)+" age Quality: "+getAgeQuality(recipe,time)+" for "+recipe.getName(5));
if(recipe.needsToAge()){
//needs riping in barrel
ageQuality = getAgeQuality(recipe,time);
woodQuality = getWoodQuality(recipe,wood);
if (ingredientQuality > -1) {
P.p.log("Ingredient Quality: " + ingredientQuality + " Cooking Quality: " + cookingQuality + " Wood Quality: " + getWoodQuality(recipe, wood) + " age Quality: "
+ getAgeQuality(recipe, time) + " for " + recipe.getName(5));
if (recipe.needsToAge()) {
// needs riping in barrel
ageQuality = getAgeQuality(recipe, time);
woodQuality = getWoodQuality(recipe, wood);
//is this recipe better than the previous best?
if((((float)ingredientQuality + cookingQuality + woodQuality + ageQuality) / 4) > quality){
quality = ((float)ingredientQuality + cookingQuality + woodQuality + ageQuality) / 4;
// is this recipe better than the previous best?
if ((((float) ingredientQuality + cookingQuality + woodQuality + ageQuality) / 4) > quality) {
quality = ((float) ingredientQuality + cookingQuality + woodQuality + ageQuality) / 4;
bestRecipe = recipe;
}
} else {
//calculate quality without age and barrel
if((((float)ingredientQuality + cookingQuality) / 2) > quality){
quality = ((float)ingredientQuality + cookingQuality) / 2;
// calculate quality without age and barrel
if ((((float) ingredientQuality + cookingQuality) / 2) > quality) {
quality = ((float) ingredientQuality + cookingQuality) / 2;
bestRecipe = recipe;
}
}
}
}
if(bestRecipe != null){
P.p.log("best recipe: "+bestRecipe.getName(5)+" has Quality= "+quality);
if (bestRecipe != null) {
P.p.log("best recipe: " + bestRecipe.getName(5) + " has Quality= " + quality);
}
return bestRecipe;
}
//returns recipe that is cooking only and matches the ingredients and cooking time
public BRecipe getCookRecipe(){
BRecipe bestRecipe = getBestRecipe((byte)0,0);
// returns recipe that is cooking only and matches the ingredients and
// cooking time
public BRecipe getCookRecipe() {
BRecipe bestRecipe = getBestRecipe((byte) 0, 0);
//Check if best recipe is cooking only
if(bestRecipe != null){
if(bestRecipe.isCookingOnly()){
// Check if best recipe is cooking only
if (bestRecipe != null) {
if (bestRecipe.isCookingOnly()) {
return bestRecipe;
}
}
return null;
}
//returns the currently best matching recipe for distilling for the ingredients and cooking time
public BRecipe getdistillRecipe(){
BRecipe bestRecipe = getBestRecipe((byte)0,0);
// returns the currently best matching recipe for distilling for the
// ingredients and cooking time
public BRecipe getdistillRecipe() {
BRecipe bestRecipe = getBestRecipe((byte) 0, 0);
//Check if best recipe needs to be destilled
if(bestRecipe != null){
if(bestRecipe.getDistillRuns() != 0){
// Check if best recipe needs to be destilled
if (bestRecipe != null) {
if (bestRecipe.getDistillRuns() != 0) {
return bestRecipe;
}
}
return null;
}
//returns currently best matching recipe for ingredients, cooking- and ageingtime
public BRecipe getAgeRecipe(byte wood,float time){
BRecipe bestRecipe = getBestRecipe(wood,time);
// returns currently best matching recipe for ingredients, cooking- and
// ageingtime
public BRecipe getAgeRecipe(byte wood, float time) {
BRecipe bestRecipe = getBestRecipe(wood, time);
if(bestRecipe != null){
if(bestRecipe.needsToAge()){
if (bestRecipe != null) {
if (bestRecipe.needsToAge()) {
return bestRecipe;
}
}
return null;
}
//returns the quality of the ingredients conditioning given recipe, -1 if no recipe is near them
public int getIngredientQuality(BRecipe recipe){
// returns the quality of the ingredients conditioning given recipe, -1 if
// no recipe is near them
public int getIngredientQuality(BRecipe recipe) {
float quality = 10;
int count = 0;
int badStuff = 0;
if(recipe.isMissingIngredients(ingredients)){
//when ingredients are not complete
if (recipe.isMissingIngredients(ingredients)) {
// when ingredients are not complete
return -1;
}
for(Material ingredient:ingredients.keySet()){
for (Material ingredient : ingredients.keySet()) {
count = ingredients.get(ingredient);
if(recipe.amountOf(ingredient) == 0){
//this ingredient doesnt belong into the recipe
if(count > (getIngredientsCount() / 2)){
//when more than half of the ingredients dont fit into the recipe
if (recipe.amountOf(ingredient) == 0) {
// this ingredient doesnt belong into the recipe
if (count > (getIngredientsCount() / 2)) {
// when more than half of the ingredients dont fit into the
// recipe
return -1;
}
badStuff++;
if(badStuff < ingredients.size()){
//when there are other ingredients
if (badStuff < ingredients.size()) {
// when there are other ingredients
quality -= count * 2;
continue;
} else {
//ingredients dont fit at all
// ingredients dont fit at all
return -1;
}
}
//calculate the quality
// calculate the quality
quality -= (((float) Math.abs(count - recipe.amountOf(ingredient)) / recipe.allowedCountDiff(recipe.amountOf(ingredient))) * 10.0);
}
/* if(quality != 0){
quality /= ingredients.size();
}*/
if(quality >= 0){
/*
* if(quality != 0){ quality /= ingredients.size(); }
*/
if (quality >= 0) {
return Math.round(quality);
}
return -1;
}
//returns the quality regarding the cooking-time conditioning given Recipe
public int getCookingQuality(BRecipe recipe){
// returns the quality regarding the cooking-time conditioning given Recipe
public int getCookingQuality(BRecipe recipe) {
int quality = 10 - (int) Math.round(((float) Math.abs(cookedTime - recipe.getCookingTime()) / recipe.allowedTimeDiff(recipe.getCookingTime())) * 10.0);
if(quality > 0){
if (quality > 0) {
return quality;
}
return 0;
}
//returns the quality regarding the barrel wood conditioning given Recipe
public int getWoodQuality(BRecipe recipe,byte wood){
if(recipe.getWood() == 0x8){
//type of wood doesnt matter
// returns the quality regarding the barrel wood conditioning given Recipe
public int getWoodQuality(BRecipe recipe, byte wood) {
if (recipe.getWood() == 0x8) {
// type of wood doesnt matter
return 10;
}
int quality = 10 - (int) Math.round(recipe.getWoodDiff(wood) * recipe.getDifficulty());
if(quality > 0){
if (quality > 0) {
return quality;
}
return 0;
}
//returns the quality regarding the ageing time conditioning given Recipe
public int getAgeQuality(BRecipe recipe,float time){
int quality = 10 - (int) Math.round( Math.abs(time - recipe.getAge()) * ((float)recipe.getDifficulty() / 2) );
// returns the quality regarding the ageing time conditioning given Recipe
public int getAgeQuality(BRecipe recipe, float time) {
int quality = 10 - (int) Math.round(Math.abs(time - recipe.getAge()) * ((float) recipe.getDifficulty() / 2));
if(quality > 0){
if (quality > 0) {
return quality;
}
return 0;
}
//saves data into ingredient section of Brew/BCauldron
public void save(ConfigurationSection config){
if(cookedTime != 0){
// saves data into ingredient section of Brew/BCauldron
public void save(ConfigurationSection config) {
if (cookedTime != 0) {
config.set("cookedTime", cookedTime);
}
//convert the ingredient Material to id
Map<Integer,Integer> mats = new HashMap<Integer,Integer>();
for(Material mat:ingredients.keySet()){
mats.put(mat.getId(),ingredients.get(mat));
// convert the ingredient Material to id
Map<Integer, Integer> mats = new HashMap<Integer, Integer>();
for (Material mat : ingredients.keySet()) {
mats.put(mat.getId(), ingredients.get(mat));
}
//list all Material ids with their amount
// list all Material ids with their amount
ConfigurationSection matSection = config.createSection("mats");
for(int id:mats.keySet()){
matSection.set(""+id,mats.get(id));
for (int id : mats.keySet()) {
matSection.set("" + id, mats.get(id));
}
}
}

View File

@ -12,84 +12,87 @@ import org.bukkit.configuration.ConfigurationSection;
import com.dre.brewery.Brew;
public class BPlayer {
public static Map<String,BPlayer> players=new HashMap<String,BPlayer>();//Players name and BPlayer
public static Map<String, BPlayer> players = new HashMap<String, BPlayer>();// Players
// name
// and
// BPlayer
private int quality = 0;// = quality of drunkeness * drunkeness
private int drunkeness = 0;// = amount of drunkeness
private Vector push = new Vector(0,0,0);
private Vector push = new Vector(0, 0, 0);
private int time = 20;
public BPlayer(){
public BPlayer() {
}
//reading from file
public BPlayer(String name,int quality,int drunkeness){
// reading from file
public BPlayer(String name, int quality, int drunkeness) {
this.quality = quality;
this.drunkeness = drunkeness;
players.put(name,this);
players.put(name, this);
}
public static BPlayer get(String name){
if(!players.isEmpty()){
if(players.containsKey(name)){
public static BPlayer get(String name) {
if (!players.isEmpty()) {
if (players.containsKey(name)) {
return players.get(name);
}
}
return null;
}
//returns true if drinking was successful
public static boolean drink(int uid,String name){
// returns true if drinking was successful
public static boolean drink(int uid, String name) {
Brew brew = Brew.get(uid);
if(brew != null){
if (brew != null) {
BPlayer bPlayer = get(name);
if(bPlayer == null){
if (bPlayer == null) {
bPlayer = new BPlayer();
players.put(name,bPlayer);
players.put(name, bPlayer);
}
bPlayer.drunkeness += brew.getAlcohol();
bPlayer.quality += brew.getQuality() * brew.getAlcohol();
P.p.log(name+" ist nun "+bPlayer.drunkeness+"% betrunken, mit einer Qualität von "+bPlayer.getQuality());
P.p.log(name + " ist nun " + bPlayer.drunkeness + "% betrunken, mit einer Qualität von " + bPlayer.getQuality());
return true;
}
return false;
}
//push the player around if he moves
public static void playerMove(PlayerMoveEvent event){
// push the player around if he moves
public static void playerMove(PlayerMoveEvent event) {
BPlayer bPlayer = get(event.getPlayer().getName());
if(bPlayer != null){
if (bPlayer != null) {
bPlayer.move(event);
}
}
//player is drunk
public void move(PlayerMoveEvent event){
//has player more alc than 10
if(drunkeness >= 10){
if(drunkeness <= 100){
if(time > 1){
// player is drunk
public void move(PlayerMoveEvent event) {
// has player more alc than 10
if (drunkeness >= 10) {
if (drunkeness <= 100) {
if (time > 1) {
time--;
} else {
//Is he moving
if(event.getFrom().getX() != event.getTo().getX() || event.getFrom().getZ() != event.getTo().getZ()){
// Is he moving
if (event.getFrom().getX() != event.getTo().getX() || event.getFrom().getZ() != event.getTo().getZ()) {
Player player = event.getPlayer();
Entity entity = (Entity) player;
//not in midair
if(entity.isOnGround()){
// not in midair
if (entity.isOnGround()) {
time--;
if(time == 0){
//push him only to the side? or any direction like now
if (time == 0) {
// push him only to the side? or any direction
// like now
push.setX(Math.random() - 0.5);
push.setZ(Math.random() - 0.5);
player.setVelocity(push);
} else if (time < 0 && time > -10){
//push him some more in the same direction
} else if (time < 0 && time > -10) {
// push him some more in the same direction
player.setVelocity(push);
} else {
//when more alc, push him more often
time = (int)(Math.random() * (201.0 - (drunkeness * 2)));
// when more alc, push him more often
time = (int) (Math.random() * (201.0 - (drunkeness * 2)));
}
}
}
@ -98,22 +101,22 @@ public class BPlayer {
}
}
//decreasing drunkeness over time
public static void onUpdate(){
if(!players.isEmpty()){
for(BPlayer bplayer:players.values()){
// decreasing drunkeness over time
public static void onUpdate() {
if (!players.isEmpty()) {
for (BPlayer bplayer : players.values()) {
bplayer.drunkeness -= 2;
if(bplayer.drunkeness <= 0){
if (bplayer.drunkeness <= 0) {
players.remove(bplayer);
}
}
}
}
//save all data
public static void save(ConfigurationSection config){
if(!players.isEmpty()){
for(String name:players.keySet()){
// save all data
public static void save(ConfigurationSection config) {
if (!players.isEmpty()) {
for (String name : players.keySet()) {
ConfigurationSection section = config.createSection(name);
section.set("quality", players.get(name).quality);
section.set("drunk", players.get(name).drunkeness);
@ -121,15 +124,13 @@ public class BPlayer {
}
}
//getter
public int getDrunkeness(){
// getter
public int getDrunkeness() {
return drunkeness;
}
public int getQuality(){
public int getQuality() {
return Math.round(quality / drunkeness);
}
}

View File

@ -7,134 +7,133 @@ import java.util.HashMap;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.Material;
public class BRecipe {
private String[] name;
private Map<Material,Integer> ingredients = new HashMap<Material,Integer>();//material and amount
private int cookingTime;//time to cook in cauldron
private int distillruns;//runs through the brewer
private int wood;//type of wood the barrel has to consist of
private int age;//time in minecraft days for the potions to age in barrels
private String color;//color of the destilled/finished potion
private int difficulty;//difficulty to brew the potion, how exact the instruction has to be followed
private int alcohol;//Vol% of alcohol in perfect potion
private Map<Material, Integer> ingredients = new HashMap<Material, Integer>();// material
// and
// amount
private int cookingTime;// time to cook in cauldron
private int distillruns;// runs through the brewer
private int wood;// type of wood the barrel has to consist of
private int age;// time in minecraft days for the potions to age in barrels
private String color;// color of the destilled/finished potion
private int difficulty;// difficulty to brew the potion, how exact the
// instruction has to be followed
private int alcohol;// Vol% of alcohol in perfect potion
public BRecipe(ConfigurationSection configSectionRecipes,String recipeId){
String[] name = configSectionRecipes.getString(recipeId+".name").split("/");
if(name.length > 2){
public BRecipe(ConfigurationSection configSectionRecipes, String recipeId) {
String[] name = configSectionRecipes.getString(recipeId + ".name").split("/");
if (name.length > 2) {
this.name = name;
} else {
this.name = new String[1];
this.name[0] = name[0];
}
List<String> ingredientsList = configSectionRecipes.getStringList(recipeId+".ingredients");
for(String item:ingredientsList){
List<String> ingredientsList = configSectionRecipes.getStringList(recipeId + ".ingredients");
for (String item : ingredientsList) {
String[] ingredParts = item.split("/");
ingredParts[0] = ingredParts[0].toUpperCase();
this.ingredients.put(Material.getMaterial(ingredParts[0]),P.p.parseInt(ingredParts[1]));
this.ingredients.put(Material.getMaterial(ingredParts[0]), P.p.parseInt(ingredParts[1]));
}
this.cookingTime = configSectionRecipes.getInt(recipeId+".cookingtime");
this.distillruns = configSectionRecipes.getInt(recipeId+".distillruns");
this.wood = configSectionRecipes.getInt(recipeId+".wood");
this.age = configSectionRecipes.getInt(recipeId+".age");
this.color = configSectionRecipes.getString(recipeId+".color");
this.difficulty = configSectionRecipes.getInt(recipeId+".difficulty");
this.alcohol = configSectionRecipes.getInt(recipeId+".alcohol");
this.cookingTime = configSectionRecipes.getInt(recipeId + ".cookingtime");
this.distillruns = configSectionRecipes.getInt(recipeId + ".distillruns");
this.wood = configSectionRecipes.getInt(recipeId + ".wood");
this.age = configSectionRecipes.getInt(recipeId + ".age");
this.color = configSectionRecipes.getString(recipeId + ".color");
this.difficulty = configSectionRecipes.getInt(recipeId + ".difficulty");
this.alcohol = configSectionRecipes.getInt(recipeId + ".alcohol");
}
// allowed deviation to the recipes count of ingredients at the given
// difficulty
public int allowedCountDiff(int count) {
int allowedCountDiff = Math.round((float) ((11.0 - difficulty) * (count / 10.0)));
//allowed deviation to the recipes count of ingredients at the given difficulty
public int allowedCountDiff(int count){
int allowedCountDiff = Math.round((float)((11.0 - difficulty) * (count / 10.0)));
if(allowedCountDiff == 0){
if (allowedCountDiff == 0) {
return 1;
}
return allowedCountDiff;
}
//allowed deviation to the recipes cooking-time at the given difficulty
public int allowedTimeDiff(int time){
int allowedTimeDiff = Math.round((float)((11.0 - difficulty) * (time / 10.0)));
// allowed deviation to the recipes cooking-time at the given difficulty
public int allowedTimeDiff(int time) {
int allowedTimeDiff = Math.round((float) ((11.0 - difficulty) * (time / 10.0)));
while(allowedTimeDiff >= time){
while (allowedTimeDiff >= time) {
allowedTimeDiff -= 1;
}
if(allowedTimeDiff == 0){
if (allowedTimeDiff == 0) {
return 1;
}
return allowedTimeDiff;
}
//difference between given and recipe-wanted woodtype
public float getWoodDiff(byte wood){
// difference between given and recipe-wanted woodtype
public float getWoodDiff(byte wood) {
int woodType = 0;
if(wood == 0x0){
if (wood == 0x0) {
woodType = 2;
}else if(wood == 0x1){
} else if (wood == 0x1) {
woodType = 4;
} else if(wood == 0x2){
} else if (wood == 0x2) {
woodType = 1;
} else if(wood == 0x3){
} else if (wood == 0x3) {
woodType = 3;
}
return Math.abs(woodType - wood);
}
public boolean isCookingOnly(){
if(age == 0 && distillruns == 0){
public boolean isCookingOnly() {
if (age == 0 && distillruns == 0) {
return true;
}
return false;
}
public boolean needsDistilling(){
if(distillruns == 0){
public boolean needsDistilling() {
if (distillruns == 0) {
return true;
}
return false;
}
public boolean needsToAge(){
if(age == 0){
public boolean needsToAge() {
if (age == 0) {
return false;
}
return true;
}
//true if given map misses an ingredient
public boolean isMissingIngredients(Map<Material,Integer> map){
if(map.size() < ingredients.size()){
// true if given map misses an ingredient
public boolean isMissingIngredients(Map<Material, Integer> map) {
if (map.size() < ingredients.size()) {
return true;
}
for(Material ingredient:ingredients.keySet()){
if(!map.containsKey(ingredient)){
for (Material ingredient : ingredients.keySet()) {
if (!map.containsKey(ingredient)) {
return true;
}
}
return false;
}
// Getter
//Getter
//how many of a specific ingredient in the recipe
public int amountOf(Material material){
if(ingredients.containsKey(material)){
// how many of a specific ingredient in the recipe
public int amountOf(Material material) {
if (ingredients.containsKey(material)) {
return ingredients.get(material);
}
return 0;
}
//name that fits the quality
public String getName(int quality){
if(name.length > 2){
if(quality <= 3){
// name that fits the quality
public String getName(int quality) {
if (name.length > 2) {
if (quality <= 3) {
return name[0];
} else if(quality <= 7){
} else if (quality <= 7) {
return name[1];
} else {
return name[2];
@ -144,43 +143,42 @@ public class BRecipe {
}
}
public int getCookingTime(){
public int getCookingTime() {
return cookingTime;
}
public int getDistillRuns(){
public int getDistillRuns() {
return distillruns;
}
public String getColor(){
public String getColor() {
return color.toUpperCase();
}
//get the woodtype in blockData-byte
public byte getWood(){
if(wood == 1){
// get the woodtype in blockData-byte
public byte getWood() {
if (wood == 1) {
return 0x2;
} else if(wood == 2){
} else if (wood == 2) {
return 0x0;
} else if(wood == 3){
} else if (wood == 3) {
return 0x3;
} else if(wood == 4){
} else if (wood == 4) {
return 0x1;
}
return 0x8;
}
public float getAge(){
public float getAge() {
return (float) age;
}
public int getDifficulty(){
public int getDifficulty() {
return difficulty;
}
public int getAlcohol(){
public int getAlcohol() {
return alcohol;
}
}

View File

@ -11,38 +11,39 @@ import org.bukkit.configuration.ConfigurationSection;
public class Barrel {
public static CopyOnWriteArrayList<Barrel> barrels = new CopyOnWriteArrayList<Barrel>();
public static CopyOnWriteArrayList<Barrel> barrels = new CopyOnWriteArrayList<Barrel>();
//private CopyOnWriteArrayList<Brew> brews = new CopyOnWriteArrayList<Brew>();
private Block spigot;
private Inventory inventory;
private float time;
// private CopyOnWriteArrayList<Brew> brews = new
// CopyOnWriteArrayList<Brew>();
private Block spigot;
private Inventory inventory;
private float time;
public Barrel(Block spigot){
public Barrel(Block spigot) {
this.spigot = spigot;
}
//load from file
public Barrel(Block spigot,Map<String,Object> items,float time){
// load from file
public Barrel(Block spigot, Map<String, Object> items, float time) {
this.spigot = spigot;
if(isLarge()){
if (isLarge()) {
this.inventory = org.bukkit.Bukkit.createInventory(null, 27, "Fass");
} else {
this.inventory = org.bukkit.Bukkit.createInventory(null, 9, "Fass");
}
for(String slot:items.keySet()){
if(items.get(slot) instanceof ItemStack){
this.inventory.setItem(P.p.parseInt(slot), (ItemStack)items.get(slot));
for (String slot : items.keySet()) {
if (items.get(slot) instanceof ItemStack) {
this.inventory.setItem(P.p.parseInt(slot), (ItemStack) items.get(slot));
}
}
this.time = time;
barrels.add(this);
}
//load from file (without inventory)
public Barrel(Block spigot,float time){
// load from file (without inventory)
public Barrel(Block spigot, float time) {
this.spigot = spigot;
if(isLarge()){
if (isLarge()) {
this.inventory = org.bukkit.Bukkit.createInventory(null, 27, "Fass");
} else {
this.inventory = org.bukkit.Bukkit.createInventory(null, 9, "Fass");
@ -51,38 +52,38 @@ private float time;
barrels.add(this);
}
public static void onUpdate(){
public static void onUpdate() {
Block broken;
for(Barrel barrel:barrels){
for (Barrel barrel : barrels) {
broken = getBrokenBlock(barrel.spigot);
//remove the barrel if it was destroyed
if(broken != null){
// remove the barrel if it was destroyed
if (broken != null) {
barrel.remove(broken);
} else {
//Minecraft day is 20 min, so add 1/20 to the time every minute
barrel.time += 1.0/20.0;
// Minecraft day is 20 min, so add 1/20 to the time every minute
barrel.time += 1.0 / 20.0;
}
}
}
//player opens the barrel
public void open(Player player){
if(inventory == null){
if(isLarge()){
// player opens the barrel
public void open(Player player) {
if (inventory == null) {
if (isLarge()) {
inventory = org.bukkit.Bukkit.createInventory(null, 27, "Fass");
} else {
inventory = org.bukkit.Bukkit.createInventory(null, 9, "Fass");
}
} else {
//if nobody has the inventory opened
if(inventory.getViewers().isEmpty()){
//if inventory contains potions
if(inventory.contains(373)){
for(ItemStack item:inventory.getContents()){
if(item != null){
if(item.getTypeId() == 373){
if(item.hasItemMeta()){
Brew.age(item,time,getWood());
// if nobody has the inventory opened
if (inventory.getViewers().isEmpty()) {
// if inventory contains potions
if (inventory.contains(373)) {
for (ItemStack item : inventory.getContents()) {
if (item != null) {
if (item.getTypeId() == 373) {
if (item.hasItemMeta()) {
Brew.age(item, time, getWood());
}
}
}
@ -90,27 +91,27 @@ private float time;
}
}
}
//reset barreltime, potions have new age
// reset barreltime, potions have new age
time = 0;
player.openInventory(inventory);
}
public static Barrel get(Block spigot){
//convert spigot if neccessary
public static Barrel get(Block spigot) {
// convert spigot if neccessary
spigot = getSpigotOfSign(spigot);
for(Barrel barrel:barrels){
if(barrel.spigot.equals(spigot)){
for (Barrel barrel : barrels) {
if (barrel.spigot.equals(spigot)) {
return barrel;
}
}
return null;
}
//creates a new Barrel out of a sign
public static boolean create(Block spigot){
// creates a new Barrel out of a sign
public static boolean create(Block spigot) {
spigot = getSpigotOfSign(spigot);
if(getBrokenBlock(spigot) == null){
if(get(spigot) == null){
if (getBrokenBlock(spigot) == null) {
if (get(spigot) == null) {
barrels.add(new Barrel(spigot));
return true;
}
@ -118,18 +119,18 @@ private float time;
return false;
}
//removes a barrel, throwing included potions to the ground
public void remove(Block broken){
if(inventory != null){
// removes a barrel, throwing included potions to the ground
public void remove(Block broken) {
if (inventory != null) {
ItemStack[] items = inventory.getContents();
for(ItemStack item:items){
if(item != null){
if(item.getTypeId() == 373){
//Brew before throwing
Brew.age(item,time,getWood());
for (ItemStack item : items) {
if (item != null) {
if (item.getTypeId() == 373) {
// Brew before throwing
Brew.age(item, time, getWood());
}
//"broken" is the block that destroyed, throw them there!
if(broken != null){
// "broken" is the block that destroyed, throw them there!
if (broken != null) {
broken.getLocation().getWorld().dropItem(broken.getLocation(), item);
} else {
spigot.getLocation().getWorld().dropItem(spigot.getLocation(), item);
@ -140,33 +141,34 @@ private float time;
barrels.remove(this);
}
//Saves all data
public static void save(ConfigurationSection config){
// Saves all data
public static void save(ConfigurationSection config) {
int id = 0;
for(Barrel barrel:barrels){
//barrels are listed randomly
ConfigurationSection idConfig = config.createSection(""+id);
for (Barrel barrel : barrels) {
// barrels are listed randomly
ConfigurationSection idConfig = config.createSection("" + id);
//block: worldname/x/y/z
idConfig.set("spigot",barrel.spigot.getWorld().getName()+"/"+barrel.spigot.getX()+"/"+barrel.spigot.getY()+"/"+barrel.spigot.getZ());
if(barrel.time != 0){
// block: worldname/x/y/z
idConfig.set("spigot", barrel.spigot.getWorld().getName() + "/" + barrel.spigot.getX() + "/" + barrel.spigot.getY() + "/" + barrel.spigot.getZ());
if (barrel.time != 0) {
idConfig.set("time", barrel.time);
}
//not saving the inventory if there is none, or it is empty
if(barrel.inventory != null){
// not saving the inventory if there is none, or it is empty
if (barrel.inventory != null) {
int slot = 0;
ItemStack item = null;
ConfigurationSection invConfig = null;
while(slot < barrel.inventory.getSize()){
while (slot < barrel.inventory.getSize()) {
item = barrel.inventory.getItem(slot);
if(item != null){
if(invConfig == null){
//create section only when items in inventory
if (item != null) {
if (invConfig == null) {
// create section only when items in inventory
invConfig = idConfig.createSection("inv");
}
//ItemStacks are configurationSerializeable, makes them really easy to save
invConfig.set(slot+"",item);
// ItemStacks are configurationSerializeable, makes them
// really easy to save
invConfig.set(slot + "", item);
}
slot++;
@ -177,32 +179,32 @@ private float time;
}
}
//direction of the barrel from the spigot
public static int getDirection(Block spigot){
int direction = 0;//1=x+ 2=x- 3=z+ 4=z-
int typeId = spigot.getRelative(0,0,1).getTypeId();
if(typeId == 5 || typeId == 53 || typeId == 134 || typeId == 135 || typeId == 136){
// direction of the barrel from the spigot
public static int getDirection(Block spigot) {
int direction = 0;// 1=x+ 2=x- 3=z+ 4=z-
int typeId = spigot.getRelative(0, 0, 1).getTypeId();
if (typeId == 5 || typeId == 53 || typeId == 134 || typeId == 135 || typeId == 136) {
direction = 3;
}
typeId = spigot.getRelative(0,0,-1).getTypeId();
if(typeId == 5 || typeId == 53 || typeId == 134 || typeId == 135 || typeId == 136){
if(direction == 0){
typeId = spigot.getRelative(0, 0, -1).getTypeId();
if (typeId == 5 || typeId == 53 || typeId == 134 || typeId == 135 || typeId == 136) {
if (direction == 0) {
direction = 4;
} else {
return 0;
}
}
typeId = spigot.getRelative(1,0,0).getTypeId();
if(typeId == 5 || typeId == 53 || typeId == 134 || typeId == 135 || typeId == 136){
if(direction == 0){
typeId = spigot.getRelative(1, 0, 0).getTypeId();
if (typeId == 5 || typeId == 53 || typeId == 134 || typeId == 135 || typeId == 136) {
if (direction == 0) {
direction = 1;
} else {
return 0;
}
}
typeId = spigot.getRelative(-1,0,0).getTypeId();
if(typeId == 5 || typeId == 53 || typeId == 134 || typeId == 135 || typeId == 136){
if(direction == 0){
typeId = spigot.getRelative(-1, 0, 0).getTypeId();
if (typeId == 5 || typeId == 53 || typeId == 134 || typeId == 135 || typeId == 136) {
if (direction == 0) {
direction = 2;
} else {
return 0;
@ -211,84 +213,84 @@ private float time;
return direction;
}
//is this a Large barrel?
public boolean isLarge(){
if(spigot.getTypeId() == 63 || spigot.getTypeId() == 68){
// is this a Large barrel?
public boolean isLarge() {
if (spigot.getTypeId() == 63 || spigot.getTypeId() == 68) {
return false;
}
return true;
}
//true for small barrels
public static boolean isSign(Block spigot){
if(spigot.getTypeId() == 63 || spigot.getTypeId() == 68){
// true for small barrels
public static boolean isSign(Block spigot) {
if (spigot.getTypeId() == 63 || spigot.getTypeId() == 68) {
return true;
}
return false;
}
//woodtype of the block the spigot is attached to
public byte getWood(){
int direction = getDirection(this.spigot);//1=x+ 2=x- 3=z+ 4=z-
// woodtype of the block the spigot is attached to
public byte getWood() {
int direction = getDirection(this.spigot);// 1=x+ 2=x- 3=z+ 4=z-
Block wood = null;
if(direction == 0){
if (direction == 0) {
return 0;
} else if (direction == 1){
wood = this.spigot.getRelative(1,0,0);
} else if (direction == 2){
wood = this.spigot.getRelative(-1,0,0);
} else if (direction == 3){
wood = this.spigot.getRelative(0,0,1);
} else if (direction == 1) {
wood = this.spigot.getRelative(1, 0, 0);
} else if (direction == 2) {
wood = this.spigot.getRelative(-1, 0, 0);
} else if (direction == 3) {
wood = this.spigot.getRelative(0, 0, 1);
} else {
wood = this.spigot.getRelative(0,0,-1);
wood = this.spigot.getRelative(0, 0, -1);
}
if(wood.getTypeId() == 5){
if (wood.getTypeId() == 5) {
return wood.getData();
}
if(wood.getTypeId() == 53){
if (wood.getTypeId() == 53) {
return 0x0;
}
if(wood.getTypeId() == 134){
if (wood.getTypeId() == 134) {
return 0x1;
}
if(wood.getTypeId() == 135){
if (wood.getTypeId() == 135) {
return 0x2;
}
if(wood.getTypeId() == 136){
if (wood.getTypeId() == 136) {
return 0x3;
}
return 0;
}
//returns the fence above/below a block, itself if there is none
public static Block getSpigotOfSign(Block block){
// returns the fence above/below a block, itself if there is none
public static Block getSpigotOfSign(Block block) {
int y = -2;
while(y <= 1){
//Fence and Netherfence
if(block.getRelative(0,y,0).getTypeId() == 85 ||
block.getRelative(0,y,0).getTypeId() == 113){
return (block.getRelative(0,y,0));
while (y <= 1) {
// Fence and Netherfence
if (block.getRelative(0, y, 0).getTypeId() == 85 || block.getRelative(0, y, 0).getTypeId() == 113) {
return (block.getRelative(0, y, 0));
}
y++;
}
return block;
}
//returns null if Barrel is correctly placed; the block that is missing when not
//the barrel needs to be formed correctly
public static Block getBrokenBlock(Block spigot){
// returns null if Barrel is correctly placed; the block that is missing
// when not
// the barrel needs to be formed correctly
public static Block getBrokenBlock(Block spigot) {
spigot = getSpigotOfSign(spigot);
if(isSign(spigot)){
if (isSign(spigot)) {
return checkSBarrel(spigot);
} else {
return checkLBarrel(spigot);
}
}
public static Block checkSBarrel(Block spigot){
int direction = getDirection(spigot);//1=x+ 2=x- 3=z+ 4=z-
if(direction == 0){
public static Block checkSBarrel(Block spigot) {
int direction = getDirection(spigot);// 1=x+ 2=x- 3=z+ 4=z-
if (direction == 0) {
return spigot;
}
int startX = 0;
@ -296,17 +298,17 @@ private float time;
int endX;
int endZ;
if (direction == 1){
if (direction == 1) {
startX = 1;
endX = startX + 1;
startZ = -1;
endZ = 0;
} else if (direction == 2){
} else if (direction == 2) {
startX = -2;
endX = startX + 1;
startZ = 0;
endZ = 1;
} else if (direction == 3){
} else if (direction == 3) {
startX = 0;
endX = 1;
startZ = 1;
@ -322,23 +324,23 @@ private float time;
int x = startX;
int y = 0;
int z = startZ;
//P.p.log("startX="+startX+" startZ="+startZ+" endX="+endX+" endZ="+endZ+" direction="+direction);
while(y <= 1){
while(x <= endX){
while(z <= endZ){
typeId = spigot.getRelative(x,y,z).getTypeId();
// P.p.log("startX="+startX+" startZ="+startZ+" endX="+endX+" endZ="+endZ+" direction="+direction);
while (y <= 1) {
while (x <= endX) {
while (z <= endZ) {
typeId = spigot.getRelative(x, y, z).getTypeId();
if(typeId == 53 || typeId == 134 || typeId == 135 || typeId == 136){
if(y == 0){
//stairs have to be upside down
if(spigot.getRelative(x,y,z).getData() < 4){
return spigot.getRelative(x,y,z);
if (typeId == 53 || typeId == 134 || typeId == 135 || typeId == 136) {
if (y == 0) {
// stairs have to be upside down
if (spigot.getRelative(x, y, z).getData() < 4) {
return spigot.getRelative(x, y, z);
}
}
z++;
continue;
} else {
return spigot.getRelative(x,y,z);
return spigot.getRelative(x, y, z);
}
}
z = startZ;
@ -352,9 +354,9 @@ private float time;
}
public static Block checkLBarrel(Block spigot){
int direction = getDirection(spigot);//1=x+ 2=x- 3=z+ 4=z-
if(direction == 0){
public static Block checkLBarrel(Block spigot) {
int direction = getDirection(spigot);// 1=x+ 2=x- 3=z+ 4=z-
if (direction == 0) {
return spigot;
}
int startX = 0;
@ -362,17 +364,17 @@ private float time;
int endX;
int endZ;
if (direction == 1){
if (direction == 1) {
startX = 1;
endX = startX + 3;
startZ = -1;
endZ = 1;
} else if (direction == 2){
} else if (direction == 2) {
startX = -4;
endX = startX + 3;
startZ = -1;
endZ = 1;
} else if (direction == 3){
} else if (direction == 3) {
startX = -1;
endX = 1;
startZ = 1;
@ -388,42 +390,42 @@ private float time;
int x = startX;
int y = 0;
int z = startZ;
//P.p.log("startX="+startX+" startZ="+startZ+" endX="+endX+" endZ="+endZ+" direction="+direction);
while(y <= 2){
while(x <= endX){
while(z <= endZ){
typeId = spigot.getRelative(x,y,z).getTypeId();
//spigot.getRelative(x,y,z).setTypeId(1);
if(direction == 1 || direction == 2){
if(y == 1 && z == 0){
if(x == -2 || x == -3 || x == 2 || x == 3){
// P.p.log("startX="+startX+" startZ="+startZ+" endX="+endX+" endZ="+endZ+" direction="+direction);
while (y <= 2) {
while (x <= endX) {
while (z <= endZ) {
typeId = spigot.getRelative(x, y, z).getTypeId();
// spigot.getRelative(x,y,z).setTypeId(1);
if (direction == 1 || direction == 2) {
if (y == 1 && z == 0) {
if (x == -2 || x == -3 || x == 2 || x == 3) {
z++;
continue;
} else if (x == -1 || x == -4 || x == 1 || x == 4){
if(typeId != 0){
} else if (x == -1 || x == -4 || x == 1 || x == 4) {
if (typeId != 0) {
z++;
continue;
}
}
}
} else {
if(y == 1 && x == 0){
if(z == -2 || z == -3 || z == 2 || z == 3){
if (y == 1 && x == 0) {
if (z == -2 || z == -3 || z == 2 || z == 3) {
z++;
continue;
} else if (z == -1 || z == -4 || z == 1 || z == 4){
if(typeId != 0){
} else if (z == -1 || z == -4 || z == 1 || z == 4) {
if (typeId != 0) {
z++;
continue;
}
}
}
}
if(typeId == 5 || typeId == 53 || typeId == 134 || typeId == 135 || typeId == 136){
if (typeId == 5 || typeId == 53 || typeId == 134 || typeId == 135 || typeId == 136) {
z++;
continue;
} else {
return spigot.getRelative(x,y,z);
return spigot.getRelative(x, y, z);
}
}
z = startZ;

View File

@ -15,9 +15,9 @@ import com.dre.brewery.BIngredients;
public class Brew {
public static Map<Integer,Brew> potions=new HashMap<Integer,Brew>();
public static Map<Integer, Brew> potions = new HashMap<Integer, Brew>();
//represents the liquid in the brewed Potions
// represents the liquid in the brewed Potions
private BIngredients ingredients;
private int quality;
@ -25,35 +25,35 @@ public class Brew {
private float ageTime;
private int alcohol;
public Brew(int uid,BIngredients ingredients){
public Brew(int uid, BIngredients ingredients) {
this.ingredients = ingredients;
potions.put(uid,this);
potions.put(uid, this);
}
//quality already set
public Brew(int uid,int quality,int alcohol,BIngredients ingredients){
// quality already set
public Brew(int uid, int quality, int alcohol, BIngredients ingredients) {
this.ingredients = ingredients;
this.quality = quality;
this.alcohol = calcAlcohol(alcohol);
potions.put(uid,this);
potions.put(uid, this);
}
//loading from file
public Brew(int uid,BIngredients ingredients,int quality,int distillRuns,float ageTime,int alcohol){
// loading from file
public Brew(int uid, BIngredients ingredients, int quality, int distillRuns, float ageTime, int alcohol) {
this.ingredients = ingredients;
this.quality = quality;
this.distillRuns = distillRuns;
this.ageTime = ageTime;
this.alcohol = alcohol;
potions.put(uid,this);
potions.put(uid, this);
}
//returns a Brew by its UID
public static Brew get(int uid){
if(uid < -1){
if(!potions.containsKey(uid)){
P.p.errorLog("Database failure! unable to find UID "+uid+" of a custom Potion!");
return null;//throw some exception?
// returns a Brew by its UID
public static Brew get(int uid) {
if (uid < -1) {
if (!potions.containsKey(uid)) {
P.p.errorLog("Database failure! unable to find UID " + uid + " of a custom Potion!");
return null;// throw some exception?
}
} else {
return null;
@ -61,32 +61,29 @@ public class Brew {
return potions.get(uid);
}
//returns a Brew by PotionMeta
public static Brew get(PotionMeta meta){
// returns a Brew by PotionMeta
public static Brew get(PotionMeta meta) {
return get(getUID(meta));
}
//returns a Brew by ItemStack
/*public static Brew get(ItemStack item){
if(item.getTypeId() == 373){
PotionMeta potionMeta = (PotionMeta) item.getItemMeta();
return get(potionMeta);
}
return null;
}*/
// returns a Brew by ItemStack
/*
* public static Brew get(ItemStack item){ if(item.getTypeId() == 373){
* PotionMeta potionMeta = (PotionMeta) item.getItemMeta(); return
* get(potionMeta); } return null; }
*/
//returns UID of custom Potion item
public static int getUID(ItemStack item){
// returns UID of custom Potion item
public static int getUID(ItemStack item) {
return getUID((PotionMeta) item.getItemMeta());
}
//returns UID of custom Potion meta
public static int getUID(PotionMeta potionMeta){
if(potionMeta.hasCustomEffect(PotionEffectType.REGENERATION)){
for(PotionEffect effect:potionMeta.getCustomEffects()){
if(effect.getType().equals(PotionEffectType.REGENERATION)){
if(effect.getDuration() < -1){
// returns UID of custom Potion meta
public static int getUID(PotionMeta potionMeta) {
if (potionMeta.hasCustomEffect(PotionEffectType.REGENERATION)) {
for (PotionEffect effect : potionMeta.getCustomEffects()) {
if (effect.getType().equals(PotionEffectType.REGENERATION)) {
if (effect.getDuration() < -1) {
return effect.getDuration();
}
}
@ -95,94 +92,87 @@ public class Brew {
return 0;
}
//remove potion from map (drinking, despawning, should be more!)
public static void remove(ItemStack item){
// remove potion from map (drinking, despawning, should be more!)
public static void remove(ItemStack item) {
potions.remove(getUID(item));
}
//generate an UID
public static int generateUID(){
// generate an UID
public static int generateUID() {
int uid = -2;
while(potions.containsKey(uid)){
while (potions.containsKey(uid)) {
uid -= 1;
}
return uid;
}
//calculate alcohol from recipe
public int calcAlcohol(int alc){
if(distillRuns == 0){
// calculate alcohol from recipe
public int calcAlcohol(int alc) {
if (distillRuns == 0) {
distillRuns = 1;
}
alc /= distillRuns;
alc *= distillRuns * ((float)quality / 10.0);
alc *= distillRuns * ((float) quality / 10.0);
return alc;
}
//calculating quality
public int calcQuality(BRecipe recipe,byte wood){
//calculate quality from all of the factors
float quality =(
// calculating quality
public int calcQuality(BRecipe recipe, byte wood) {
// calculate quality from all of the factors
float quality = (
ingredients.getIngredientQuality(recipe) +
ingredients.getCookingQuality(recipe) +
ingredients.getWoodQuality(recipe,wood) +
ingredients.getAgeQuality(recipe,ageTime));
ingredients.getIngredientQuality(recipe) + ingredients.getCookingQuality(recipe) + ingredients.getWoodQuality(recipe, wood) + ingredients.getAgeQuality(recipe, ageTime));
quality /= 4;
return (int)Math.round(quality);
return (int) Math.round(quality);
}
public int getQuality(){
public int getQuality() {
return quality;
}
//return prev calculated alcohol
public int getAlcohol(){
// return prev calculated alcohol
public int getAlcohol() {
return alcohol;
}
// Distilling section ---------------
//Distilling section ---------------
//distill all custom potions in the brewer
public static void distillAll(BrewerInventory inv,Integer[] contents){
// distill all custom potions in the brewer
public static void distillAll(BrewerInventory inv, Integer[] contents) {
int slot = 0;
while (slot < 3){
if(contents[slot] == 1){
distillSlot(inv,slot);
while (slot < 3) {
if (contents[slot] == 1) {
distillSlot(inv, slot);
}
slot++;
}
}
//distill custom potion in given slot
public static void distillSlot(BrewerInventory inv,int slot){
// distill custom potion in given slot
public static void distillSlot(BrewerInventory inv, int slot) {
ItemStack slotItem = inv.getItem(slot);
PotionMeta potionMeta = (PotionMeta) slotItem.getItemMeta();
Brew brew = get(potionMeta);
BRecipe recipe = brew.ingredients.getdistillRecipe();
if(recipe != null){
brew.quality = brew.calcQuality(recipe,(byte)0);
P.p.log("destilled "+recipe.getName(5)+" has Quality: "+brew.quality);
if (recipe != null) {
brew.quality = brew.calcQuality(recipe, (byte) 0);
P.p.log("destilled " + recipe.getName(5) + " has Quality: " + brew.quality);
brew.distillRuns += 1;
//distillRuns will have an effect on the amount of alcohol, not the quality
if(brew.distillRuns > 1){
// distillRuns will have an effect on the amount of alcohol, not the
// quality
if (brew.distillRuns > 1) {
ArrayList<String> lore = new ArrayList<String>();
lore.add(brew.distillRuns+" fach Destilliert");
lore.add(brew.distillRuns + " fach Destilliert");
potionMeta.setLore(lore);
}
brew.alcohol = brew.calcAlcohol(recipe.getAlcohol());
potionMeta.setDisplayName(recipe.getName(brew.quality));
//if the potion should be further distillable
if(recipe.getDistillRuns() > 1){
// if the potion should be further distillable
if (recipe.getDistillRuns() > 1) {
slotItem.setDurability(PotionColor.valueOf(recipe.getColor()).getColorId(true));
} else {
slotItem.setDurability(PotionColor.valueOf(recipe.getColor()).getColorId(false));
@ -195,26 +185,22 @@ public class Brew {
slotItem.setItemMeta(potionMeta);
}
// Ageing Section ------------------
//Ageing Section ------------------
public static void age(ItemStack item,float time,byte wood){
public static void age(ItemStack item, float time, byte wood) {
PotionMeta potionMeta = (PotionMeta) item.getItemMeta();
Brew brew = get(potionMeta);
if(brew != null){
if (brew != null) {
brew.ageTime += time;
//if younger than half a day, it shouldnt get aged form
if(brew.ageTime > 0.5){
BRecipe recipe = brew.ingredients.getAgeRecipe(wood,brew.ageTime);
if(recipe != null){
if(!recipe.needsDistilling() || brew.distillRuns > 0){
// if younger than half a day, it shouldnt get aged form
if (brew.ageTime > 0.5) {
BRecipe recipe = brew.ingredients.getAgeRecipe(wood, brew.ageTime);
if (recipe != null) {
if (!recipe.needsDistilling() || brew.distillRuns > 0) {
brew.quality = brew.calcQuality(recipe,wood);
brew.quality = brew.calcQuality(recipe, wood);
brew.alcohol = brew.calcAlcohol(recipe.getAlcohol());
P.p.log("Final "+recipe.getName(5)+" has Quality: "+brew.quality);
P.p.log("Final " + recipe.getName(5) + " has Quality: " + brew.quality);
potionMeta.setDisplayName(recipe.getName(brew.quality));
item.setDurability(PotionColor.valueOf(recipe.getColor()).getColorId(false));
@ -225,45 +211,31 @@ public class Brew {
}
}
//Saves all data
public static void save(ConfigurationSection config){
for(int uid:potions.keySet()){
ConfigurationSection idConfig = config.createSection(""+uid);
// Saves all data
public static void save(ConfigurationSection config) {
for (int uid : potions.keySet()) {
ConfigurationSection idConfig = config.createSection("" + uid);
Brew brew = potions.get(uid);
//not saving unneccessary data
if(brew.quality != 0){
// not saving unneccessary data
if (brew.quality != 0) {
idConfig.set("quality", brew.quality);
}
if(brew.distillRuns != 0){
if (brew.distillRuns != 0) {
idConfig.set("distillRuns", brew.distillRuns);
}
if(brew.ageTime != 0){
if (brew.ageTime != 0) {
idConfig.set("ageTime", brew.ageTime);
}
if(brew.alcohol != 0){
if (brew.alcohol != 0) {
idConfig.set("alcohol", brew.alcohol);
}
//save the ingredients
// save the ingredients
brew.ingredients.save(idConfig.createSection("ingredients"));
}
}
public static enum PotionColor{
PINK(1),
CYAN(2),
ORANGE(3),
GREEN(4),
BRIGHT_RED(5),
BLUE(6),
BLACK(8),
RED(9),
GREY(10),
WATER(11),
DARK_RED(12),
BRIGHT_GREY(14);
public static enum PotionColor {
PINK(1), CYAN(2), ORANGE(3), GREEN(4), BRIGHT_RED(5), BLUE(6), BLACK(8), RED(9), GREY(10), WATER(11), DARK_RED(12), BRIGHT_GREY(14);
private final int colorId;
@ -271,15 +243,14 @@ public class Brew {
this.colorId = colorId;
}
//gets the Damage Value, that sets a color on the potion
//offset +32 is not accepted by brewer, so not further destillable
public short getColorId(boolean destillable){
if(destillable){
// gets the Damage Value, that sets a color on the potion
// offset +32 is not accepted by brewer, so not further destillable
public short getColorId(boolean destillable) {
if (destillable) {
return (short) (colorId + 64);
}
return (short) (colorId + 32);
}
}
}

View File

@ -20,205 +20,196 @@ import org.bukkit.ChatColor;
import org.bukkit.Material;
import java.io.IOException;
public class P extends JavaPlugin{
public class P extends JavaPlugin {
public static P p;
public static int lastBackup = 0;
//Listeners
// Listeners
public BlockListener blockListener;
public PlayerListener playerListener;
public EntityListener entityListener;
@Override
public void onEnable(){
public void onEnable() {
p = this;
readConfig();
readData();
//Listeners
// Listeners
blockListener = new BlockListener();
playerListener = new PlayerListener();
entityListener = new EntityListener();
p.getServer().getPluginManager().registerEvents(blockListener, p);
p.getServer().getPluginManager().registerEvents(playerListener, p);
p.getServer().getPluginManager().registerEvents(entityListener, p);
p.getServer().getScheduler().runTaskTimer(p, new BreweryRunnable(), 1200, 1200);
this.log(this.getDescription().getName()+" enabled!");
this.log(this.getDescription().getName() + " enabled!");
}
@Override
public void onDisable(){
public void onDisable() {
//Disable listeners
// Disable listeners
HandlerList.unregisterAll(p);
//Stop shedulers
// Stop shedulers
p.getServer().getScheduler().cancelTasks(this);
saveData();
this.log(this.getDescription().getName()+" disabled!");
this.log(this.getDescription().getName() + " disabled!");
}
public void msg(CommandSender sender,String msg){
sender.sendMessage(ChatColor.DARK_GREEN+"[Brewery] "+ChatColor.WHITE+msg);
public void msg(CommandSender sender, String msg) {
sender.sendMessage(ChatColor.DARK_GREEN + "[Brewery] " + ChatColor.WHITE + msg);
}
public void log(String msg){
public void log(String msg) {
this.msg(Bukkit.getConsoleSender(), msg);
}
public void errorLog(String msg){
Bukkit.getConsoleSender().sendMessage(ChatColor.DARK_GREEN+"[Brewery] "+ChatColor.DARK_RED+"ERROR: "+ChatColor.RED+msg);
public void errorLog(String msg) {
Bukkit.getConsoleSender().sendMessage(ChatColor.DARK_GREEN + "[Brewery] " + ChatColor.DARK_RED + "ERROR: " + ChatColor.RED + msg);
}
public void readConfig() {
public void readConfig(){
File file=new File(p.getDataFolder(), "config.yml");
if(!file.exists()){
File file = new File(p.getDataFolder(), "config.yml");
if (!file.exists()) {
saveDefaultConfig();
}
FileConfiguration config = getConfig();
//loading recipes
// loading recipes
ConfigurationSection configSection = config.getConfigurationSection("recipes");
if(configSection != null){
for(String recipeId:configSection.getKeys(false)){
BIngredients.recipes.add(new BRecipe(configSection,recipeId));
if (configSection != null) {
for (String recipeId : configSection.getKeys(false)) {
BIngredients.recipes.add(new BRecipe(configSection, recipeId));
}
}
//loading cooked names and possible ingredients
// loading cooked names and possible ingredients
configSection = config.getConfigurationSection("cooked");
if(configSection != null){
for(String ingredient:configSection.getKeys(false)){
BIngredients.cookedNames.put(Material.getMaterial(ingredient.toUpperCase()),(configSection.getString(ingredient)));
if (configSection != null) {
for (String ingredient : configSection.getKeys(false)) {
BIngredients.cookedNames.put(Material.getMaterial(ingredient.toUpperCase()), (configSection.getString(ingredient)));
BIngredients.possibleIngredients.add(Material.getMaterial(ingredient.toUpperCase()));
}
}
//telling Words the path, it will load it when needed
// telling Words the path, it will load it when needed
Words.config = config;
}
//load all Data
public void readData(){
File file=new File(p.getDataFolder(), "data.yml");
if(file.exists()){
// load all Data
public void readData() {
File file = new File(p.getDataFolder(), "data.yml");
if (file.exists()) {
FileConfiguration data = YamlConfiguration.loadConfiguration(file);
//loading Brew
// loading Brew
ConfigurationSection section = data.getConfigurationSection("Brew");
if(section != null){
//All sections have the UID as name
for(String uid:section.getKeys(false)) {
new Brew(
parseInt(uid), loadIngredients(section.getConfigurationSection(uid+".ingredients")),
section.getInt(uid+".quality",0), section.getInt(uid+".distillRuns",0), (float)section.getDouble(uid+".ageTime",0.0), section.getInt(uid+".alcohol",0));
if (section != null) {
// All sections have the UID as name
for (String uid : section.getKeys(false)) {
new Brew(parseInt(uid), loadIngredients(section.getConfigurationSection(uid + ".ingredients")), section.getInt(uid + ".quality", 0), section.getInt(uid + ".distillRuns", 0),
(float) section.getDouble(uid + ".ageTime", 0.0), section.getInt(uid + ".alcohol", 0));
}
}
//loading BCauldron
// loading BCauldron
section = data.getConfigurationSection("BCauldron");
if(section != null){
for(String cauldron:section.getKeys(false)) {
//block is splitted into worldname/x/y/z
String block = section.getString(cauldron+".block");
if(block != null){
if (section != null) {
for (String cauldron : section.getKeys(false)) {
// block is splitted into worldname/x/y/z
String block = section.getString(cauldron + ".block");
if (block != null) {
String[] splitted = block.split("/");
if(splitted.length == 4){
new BCauldron(
getServer().getWorld(splitted[0]).getBlockAt(parseInt(splitted[1]),parseInt(splitted[2]),parseInt(splitted[3])),
loadIngredients(section.getConfigurationSection(cauldron+".ingredients")), section.getInt(cauldron+".state",1));
if (splitted.length == 4) {
new BCauldron(getServer().getWorld(splitted[0]).getBlockAt(parseInt(splitted[1]), parseInt(splitted[2]), parseInt(splitted[3])),
loadIngredients(section.getConfigurationSection(cauldron + ".ingredients")), section.getInt(cauldron + ".state", 1));
} else {
errorLog("Incomplete Block-Data in data.yml: "+section.getCurrentPath()+"."+cauldron);
errorLog("Incomplete Block-Data in data.yml: " + section.getCurrentPath() + "." + cauldron);
}
} else {
errorLog("Missing Block-Data in data.yml: "+section.getCurrentPath()+"."+cauldron);
errorLog("Missing Block-Data in data.yml: " + section.getCurrentPath() + "." + cauldron);
}
}
}
//loading Barrel
// loading Barrel
section = data.getConfigurationSection("Barrel");
if(section != null){
for(String barrel:section.getKeys(false)) {
//block spigot is splitted into worldname/x/y/z
String spigot = section.getString(barrel+".spigot");
if(spigot != null){
if (section != null) {
for (String barrel : section.getKeys(false)) {
// block spigot is splitted into worldname/x/y/z
String spigot = section.getString(barrel + ".spigot");
if (spigot != null) {
String[] splitted = spigot.split("/");
if(splitted.length == 4){
//load itemStacks from invSection
ConfigurationSection invSection = section.getConfigurationSection(barrel+".inv");
if(invSection != null){
//Map<String,ItemStack> inventory = section.getValues(barrel+"inv");
new Barrel(
getServer().getWorld(splitted[0]).getBlockAt(parseInt(splitted[1]),parseInt(splitted[2]),parseInt(splitted[3])),
invSection.getValues(true), (float)section.getDouble(barrel+".time",0.0));
if (splitted.length == 4) {
// load itemStacks from invSection
ConfigurationSection invSection = section.getConfigurationSection(barrel + ".inv");
if (invSection != null) {
// Map<String,ItemStack> inventory =
// section.getValues(barrel+"inv");
new Barrel(getServer().getWorld(splitted[0]).getBlockAt(parseInt(splitted[1]), parseInt(splitted[2]), parseInt(splitted[3])), invSection.getValues(true),
(float) section.getDouble(barrel + ".time", 0.0));
} else {
//errorLog("Inventory of "+section.getCurrentPath()+"."+barrel+" in data.yml is missing");
//Barrel has no inventory
new Barrel(
getServer().getWorld(splitted[0]).getBlockAt(parseInt(splitted[1]),parseInt(splitted[2]),parseInt(splitted[3])),
(float)section.getDouble(barrel+".time",0.0));
// errorLog("Inventory of "+section.getCurrentPath()+"."+barrel+" in data.yml is missing");
// Barrel has no inventory
new Barrel(getServer().getWorld(splitted[0]).getBlockAt(parseInt(splitted[1]), parseInt(splitted[2]), parseInt(splitted[3])), (float) section.getDouble(barrel
+ ".time", 0.0));
}
} else {
errorLog("Incomplete Block-Data in data.yml: "+section.getCurrentPath()+"."+barrel);
errorLog("Incomplete Block-Data in data.yml: " + section.getCurrentPath() + "." + barrel);
}
} else {
errorLog("Missing Block-Data in data.yml: "+section.getCurrentPath()+"."+barrel);
errorLog("Missing Block-Data in data.yml: " + section.getCurrentPath() + "." + barrel);
}
}
}
//loading BPlayer
// loading BPlayer
section = data.getConfigurationSection("Player");
if(section != null){
//keys have players name
for(String name:section.getKeys(false)) {
new BPlayer(name, section.getInt(name+".quality"), section.getInt(name+".drunk"));
if (section != null) {
// keys have players name
for (String name : section.getKeys(false)) {
new BPlayer(name, section.getInt(name + ".quality"), section.getInt(name + ".drunk"));
}
}
} else {
errorLog("No data.yml found, will create new one!");
}
}
//loads BIngredients from ingredient section
public BIngredients loadIngredients(ConfigurationSection config){
if(config != null){
// loads BIngredients from ingredient section
public BIngredients loadIngredients(ConfigurationSection config) {
if (config != null) {
ConfigurationSection matSection = config.getConfigurationSection("mats");
if(matSection != null){
//matSection has all the materials + amount in Integer form
Map<Material,Integer> ingredients = new HashMap<Material,Integer>();
for(String ingredient:matSection.getKeys(false)){
//convert to Material
if (matSection != null) {
// matSection has all the materials + amount in Integer form
Map<Material, Integer> ingredients = new HashMap<Material, Integer>();
for (String ingredient : matSection.getKeys(false)) {
// convert to Material
ingredients.put(Material.getMaterial(parseInt(ingredient)), matSection.getInt(ingredient));
}
return new BIngredients(ingredients, config.getInt("cookedTime",0));
return new BIngredients(ingredients, config.getInt("cookedTime", 0));
}
}
errorLog("Ingredient section not found or incomplete in data.yml");
return new BIngredients();
}
//save all Data
public void saveData(){
// save all Data
public void saveData() {
File datafile = new File(p.getDataFolder(), "data.yml");
if(datafile.exists()){
if(lastBackup > 10){
if (datafile.exists()) {
if (lastBackup > 10) {
datafile.renameTo(new File(p.getDataFolder(), "dataBackup.yml"));
} else {
lastBackup++;
@ -227,18 +218,18 @@ public class P extends JavaPlugin{
FileConfiguration configFile = new YamlConfiguration();
if(!Brew.potions.isEmpty()){
if (!Brew.potions.isEmpty()) {
Brew.save(configFile.createSection("Brew"));
}
if(!BCauldron.bcauldrons.isEmpty()){
if (!BCauldron.bcauldrons.isEmpty()) {
BCauldron.save(configFile.createSection("BCauldron"));
}
if(!Barrel.barrels.isEmpty()){
if (!Barrel.barrels.isEmpty()) {
Barrel.save(configFile.createSection("Barrel"));
}
if(!BPlayer.players.isEmpty()){
if (!BPlayer.players.isEmpty()) {
BPlayer.save(configFile.createSection("Player"));
}
@ -249,13 +240,11 @@ public class P extends JavaPlugin{
}
}
public int parseInt(String string){
public int parseInt(String string) {
return NumberUtils.toInt(string, 0);
}
public class BreweryRunnable implements Runnable {
public class BreweryRunnable implements Runnable {
public BreweryRunnable() {
}
@ -263,13 +252,13 @@ public class P extends JavaPlugin{
@Override
public void run() {
p.log("Update");
for(BCauldron cauldron:BCauldron.bcauldrons){
cauldron.onUpdate();//runs every min to update cooking time
for (BCauldron cauldron : BCauldron.bcauldrons) {
cauldron.onUpdate();// runs every min to update cooking time
}
Barrel.onUpdate();//runs every min to check and update ageing time
BPlayer.onUpdate();//updates players drunkeness
Barrel.onUpdate();// runs every min to check and update ageing time
BPlayer.onUpdate();// updates players drunkeness
saveData();//save all data
saveData();// save all data
}
}

View File

@ -10,7 +10,7 @@ import com.dre.brewery.BPlayer;
public class Words {
//represends Words and letters, that are replaced in drunk players messages
// represends Words and letters, that are replaced in drunk players messages
public static ArrayList<Words> words = new ArrayList<Words>();
public static FileConfiguration config;
@ -22,54 +22,54 @@ public class Words {
private int alcohol = 1;
private int percentage = 100;
public Words(Map<?,?> part){
for(Map.Entry<?,?> wordPart : part.entrySet()){
public Words(Map<?, ?> part) {
for (Map.Entry<?, ?> wordPart : part.entrySet()) {
String key = (String) wordPart.getKey();
if(wordPart.getValue() instanceof String){
if (wordPart.getValue() instanceof String) {
if(key.equalsIgnoreCase("replace")){
if (key.equalsIgnoreCase("replace")) {
this.from = (String) wordPart.getValue();
} else if (key.equalsIgnoreCase("to")){
} else if (key.equalsIgnoreCase("to")) {
this.to = (String) wordPart.getValue();
} else if (key.equalsIgnoreCase("pre")){
} else if (key.equalsIgnoreCase("pre")) {
String fullPre = (String) wordPart.getValue();
this.pre = fullPre.split(",");
}
} else if (wordPart.getValue() instanceof Boolean){
} else if (wordPart.getValue() instanceof Boolean) {
if(key.equalsIgnoreCase("match")){
if (key.equalsIgnoreCase("match")) {
this.match = (Boolean) wordPart.getValue();
}
} else if (wordPart.getValue() instanceof Integer){
} else if (wordPart.getValue() instanceof Integer) {
if(key.equalsIgnoreCase("alcohol")){
if (key.equalsIgnoreCase("alcohol")) {
this.alcohol = (Integer) wordPart.getValue();
} else if (key.equalsIgnoreCase("percentage")){
} else if (key.equalsIgnoreCase("percentage")) {
this.percentage = (Integer) wordPart.getValue();
}
}
}
if(this.from != null && this.to != null){
if (this.from != null && this.to != null) {
words.add(this);
}
}
//Distort players words when he talks
public static void playerChat(AsyncPlayerChatEvent event){
// Distort players words when he talks
public static void playerChat(AsyncPlayerChatEvent event) {
BPlayer bPlayer = BPlayer.get(event.getPlayer().getName());
if(bPlayer != null){
if(words.isEmpty()){
//load when first drunk player talks
if (bPlayer != null) {
if (words.isEmpty()) {
// load when first drunk player talks
load();
}
if(!words.isEmpty()){
if (!words.isEmpty()) {
String message = event.getMessage();
for(Words w:words){
if(w.alcohol <= bPlayer.getDrunkeness()){
for (Words w : words) {
if (w.alcohol <= bPlayer.getDrunkeness()) {
message = distort(message, w.from, w.to, w.pre, w.match, w.percentage);
}
}
@ -78,94 +78,96 @@ public class Words {
}
}
//replace "percent"% of "from" -> "to" in "words", when the string before each "from" "match"es "pre"
//Not yet ignoring case :(
public static String distort(String words, String from, String to, String[] pre, boolean match, int percent){
if(from.equalsIgnoreCase("-end")){
// replace "percent"% of "from" -> "to" in "words", when the string before
// each "from" "match"es "pre"
// Not yet ignoring case :(
public static String distort(String words, String from, String to, String[] pre, boolean match, int percent) {
if (from.equalsIgnoreCase("-end")) {
from = words;
to = words+to;
} else if (from.equalsIgnoreCase("-start")){
to = words + to;
} else if (from.equalsIgnoreCase("-start")) {
from = words;
to = to+words;
}else if (from.equalsIgnoreCase("-space")){
to = to + words;
} else if (from.equalsIgnoreCase("-space")) {
from = " ";
}else if (from.equalsIgnoreCase("-random")){
//inserts "to" on a random position in "words"
} else if (from.equalsIgnoreCase("-random")) {
// inserts "to" on a random position in "words"
int charIndex = (int) (Math.random() * (words.length() - 1));
if(charIndex > words.length() / 2){
if (charIndex > words.length() / 2) {
from = words.substring(charIndex);
to = to+from;
to = to + from;
} else {
from = words.substring(0,charIndex);
to = from+to;
from = words.substring(0, charIndex);
to = from + to;
}
}
if (words.contains(from)){
//some characters (*,?) disturb split() which then throws PatternSyntaxException
try{
if(pre == null && percent == 100){
//All occurences of "from" need to be replaced
return words.replaceAll(from,to);
if (words.contains(from)) {
// some characters (*,?) disturb split() which then throws
// PatternSyntaxException
try {
if (pre == null && percent == 100) {
// All occurences of "from" need to be replaced
return words.replaceAll(from, to);
}
String newWords = "";
if(words.endsWith(from)){
//add space to end to recognize last occurence of "from"
words = words+" ";
if (words.endsWith(from)) {
// add space to end to recognize last occurence of "from"
words = words + " ";
}
//remove all "from" and split "words" there
// remove all "from" and split "words" there
String[] splitted = words.split(from);
int index = 0;
String part = null;
//if there are occurences of "from"
if(splitted.length > 1){
//- 1 because dont add "to" to the end of last part
while(index < splitted.length - 1){
// if there are occurences of "from"
if (splitted.length > 1) {
// - 1 because dont add "to" to the end of last part
while (index < splitted.length - 1) {
part = splitted[index];
//add current part of "words" to the output
newWords = newWords+part;
//check if the part ends with correct string
if(doesPreMatch(part, pre, match) && Math.random() * 100.0 <= percent){
//add replacement
newWords = newWords+to;
// add current part of "words" to the output
newWords = newWords + part;
// check if the part ends with correct string
if (doesPreMatch(part, pre, match) && Math.random() * 100.0 <= percent) {
// add replacement
newWords = newWords + to;
} else {
//add original
newWords = newWords+from;
// add original
newWords = newWords + from;
}
index++;
}
//add the last part to finish the sentence
// add the last part to finish the sentence
part = splitted[index];
if(part.equals(" ")){
//dont add the space to the end
if (part.equals(" ")) {
// dont add the space to the end
return newWords;
} else {
return newWords + part;
}
}
} catch (java.util.regex.PatternSyntaxException e) {
//e.printStackTrace();
// e.printStackTrace();
return words;
}
}
return words;
}
public static boolean doesPreMatch(String part,String[] pre,boolean match){
public static boolean doesPreMatch(String part, String[] pre, boolean match) {
boolean isBefore = !match;
if(pre != null){
for(String pr:pre){
if(match == true){
//if one is correct, it is enough
if(part.endsWith(pr) == match){
if (pre != null) {
for (String pr : pre) {
if (match == true) {
// if one is correct, it is enough
if (part.endsWith(pr) == match) {
isBefore = true;
break;
}
} else {
//if one is wrong, its over
if(part.endsWith(pr) != match){
// if one is wrong, its over
if (part.endsWith(pr) != match) {
isBefore = false;
break;
}
@ -177,14 +179,13 @@ public class Words {
return isBefore;
}
//load from config file
public static void load(){
if(config != null){
for(Map<?,?> map:config.getMapList("words")){
// load from config file
public static void load() {
if (config != null) {
for (Map<?, ?> map : config.getMapList("words")) {
new Words(map);
}
}
}
}

View File

@ -13,43 +13,42 @@ import com.dre.brewery.BCauldron;
import com.dre.brewery.Barrel;
import com.dre.brewery.P;
public class BlockListener implements Listener{
public class BlockListener implements Listener {
@EventHandler(priority = EventPriority.NORMAL)
public void onSignChange(SignChangeEvent event){
public void onSignChange(SignChangeEvent event) {
String[] lines = event.getLines();
if(lines[0].equalsIgnoreCase("Fass")){
if(Barrel.create(event.getBlock())){
P.p.msg(event.getPlayer(),"Fass erfolgreich erstellt");
if (lines[0].equalsIgnoreCase("Fass")) {
if (Barrel.create(event.getBlock())) {
P.p.msg(event.getPlayer(), "Fass erfolgreich erstellt");
}
}
}
@EventHandler(priority = EventPriority.HIGH)
public void onBlockBreak(BlockBreakEvent event){
Block block=event.getBlock();
//remove cauldron
if(block.getType() == Material.CAULDRON){
if(block.getRelative(BlockFace.DOWN).getType() == Material.FIRE ||
block.getRelative(BlockFace.DOWN).getType() == Material.STATIONARY_LAVA ||
block.getRelative(BlockFace.DOWN).getType() == Material.LAVA){
if(block.getData() != 0){
//will only remove when existing
public void onBlockBreak(BlockBreakEvent event) {
Block block = event.getBlock();
// remove cauldron
if (block.getType() == Material.CAULDRON) {
if (block.getRelative(BlockFace.DOWN).getType() == Material.FIRE || block.getRelative(BlockFace.DOWN).getType() == Material.STATIONARY_LAVA
|| block.getRelative(BlockFace.DOWN).getType() == Material.LAVA) {
if (block.getData() != 0) {
// will only remove when existing
BCauldron.remove(block);
}
}
//remove barrel and throw potions on the ground
} else if (block.getType() == Material.FENCE || block.getType() == Material.NETHER_FENCE){
// remove barrel and throw potions on the ground
} else if (block.getType() == Material.FENCE || block.getType() == Material.NETHER_FENCE) {
Barrel barrel = Barrel.get(block);
if(barrel != null){
if (barrel != null) {
barrel.remove(null);
}
//remove small Barrels
} else if (block.getType() == Material.SIGN || block.getType() == Material.WALL_SIGN){
// remove small Barrels
} else if (block.getType() == Material.SIGN || block.getType() == Material.WALL_SIGN) {
Barrel barrel = Barrel.get(block);
if(barrel != null){
if(!barrel.isLarge()){
if (barrel != null) {
if (!barrel.isLarge()) {
barrel.remove(null);
}
}

View File

@ -9,13 +9,13 @@ import org.bukkit.inventory.ItemStack;
import com.dre.brewery.Brew;
public class EntityListener implements Listener{
public class EntityListener implements Listener {
//Remove the Potion from Brew when it despawns
// Remove the Potion from Brew when it despawns
@EventHandler(priority = EventPriority.NORMAL)
public void onItemDespawn(ItemDespawnEvent event){
public void onItemDespawn(ItemDespawnEvent event) {
ItemStack item = event.getEntity().getItemStack();
if(item.getTypeId() == 373){
if (item.getTypeId() == 373) {
Brew.remove(item);
}
}

View File

@ -23,61 +23,60 @@ import com.dre.brewery.Barrel;
import com.dre.brewery.BPlayer;
import com.dre.brewery.Words;
public class PlayerListener implements Listener{
public class PlayerListener implements Listener {
@EventHandler(priority = EventPriority.HIGH)
public void onPlayerInteract(PlayerInteractEvent event){
public void onPlayerInteract(PlayerInteractEvent event) {
Block clickedBlock = event.getClickedBlock();
if(clickedBlock!=null){
if(event.getAction() == Action.RIGHT_CLICK_BLOCK){
if(clickedBlock.getType() == Material.CAULDRON){
if(clickedBlock.getRelative(BlockFace.DOWN).getType() == Material.FIRE ||
clickedBlock.getRelative(BlockFace.DOWN).getType() == Material.STATIONARY_LAVA ||
clickedBlock.getRelative(BlockFace.DOWN).getType() == Material.LAVA){
if (clickedBlock != null) {
if (event.getAction() == Action.RIGHT_CLICK_BLOCK) {
if (clickedBlock.getType() == Material.CAULDRON) {
if (clickedBlock.getRelative(BlockFace.DOWN).getType() == Material.FIRE || clickedBlock.getRelative(BlockFace.DOWN).getType() == Material.STATIONARY_LAVA
|| clickedBlock.getRelative(BlockFace.DOWN).getType() == Material.LAVA) {
Material materialInHand = event.getMaterial();
Player player = event.getPlayer();
ItemStack item = event.getItem();
//add ingredient to cauldron that meet the previous contitions
if(BIngredients.possibleIngredients.contains(materialInHand)){
if(BCauldron.ingredientAdd(clickedBlock,materialInHand)){
if(item.getAmount() > 1){
item.setAmount(item.getAmount() -1);
// add ingredient to cauldron that meet the previous
// contitions
if (BIngredients.possibleIngredients.contains(materialInHand)) {
if (BCauldron.ingredientAdd(clickedBlock, materialInHand)) {
if (item.getAmount() > 1) {
item.setAmount(item.getAmount() - 1);
} else {
player.setItemInHand(new ItemStack(0));
}
}
//fill a glass bottle with potion
} else if(materialInHand == Material.GLASS_BOTTLE){
if(BCauldron.fill(player,clickedBlock)){
// fill a glass bottle with potion
} else if (materialInHand == Material.GLASS_BOTTLE) {
if (BCauldron.fill(player, clickedBlock)) {
event.setCancelled(true);
if(item.getAmount() > 1){
item.setAmount(item.getAmount() -1);
if (item.getAmount() > 1) {
item.setAmount(item.getAmount() - 1);
} else {
player.setItemInHand(new ItemStack(0));
}
}
//reset cauldron when refilling to prevent unlimited source of potions
} else if(materialInHand == Material.WATER_BUCKET){
if(clickedBlock.getData() != 0){
if(clickedBlock.getData() < 3){
//will only remove when existing
// reset cauldron when refilling to prevent
// unlimited source of potions
} else if (materialInHand == Material.WATER_BUCKET) {
if (clickedBlock.getData() != 0) {
if (clickedBlock.getData() < 3) {
// will only remove when existing
BCauldron.remove(clickedBlock);
}
}
}
}
//access a barrel
} else if (clickedBlock.getType() == Material.FENCE ||
clickedBlock.getType() == Material.NETHER_FENCE ||
clickedBlock.getType() == Material.SIGN ||
clickedBlock.getType() == Material.WALL_SIGN){
// access a barrel
} else if (clickedBlock.getType() == Material.FENCE || clickedBlock.getType() == Material.NETHER_FENCE || clickedBlock.getType() == Material.SIGN
|| clickedBlock.getType() == Material.WALL_SIGN) {
Barrel barrel = Barrel.get(clickedBlock);
if(barrel != null){
if (barrel != null) {
event.setCancelled(true);
Block broken = Barrel.getBrokenBlock(clickedBlock);
//barrel is built correctly
if(broken == null){
// barrel is built correctly
if (broken == null) {
barrel.open(event.getPlayer());
} else {
barrel.remove(broken);
@ -89,48 +88,45 @@ public class PlayerListener implements Listener{
}
@EventHandler(priority = EventPriority.HIGH)
public void onBrew(BrewEvent event){
public void onBrew(BrewEvent event) {
int slot = 0;
BrewerInventory inv = event.getContents();
ItemStack item;
boolean custom = false;
Integer[] contents = new Integer[3];
while(slot < 3){
while (slot < 3) {
item = inv.getItem(slot);
contents[slot] = 0;
if(item != null){
if(item.getType() == Material.POTION){
if(item.hasItemMeta()){
if(Brew.potions.containsKey(Brew.getUID(item))){
//has custom potion in "slot"
if (item != null) {
if (item.getType() == Material.POTION) {
if (item.hasItemMeta()) {
if (Brew.potions.containsKey(Brew.getUID(item))) {
// has custom potion in "slot"
contents[slot] = 1;
custom = true;
}
}
}
}
slot++;
slot++;
}
if(custom){
if (custom) {
event.setCancelled(true);
Brew.distillAll(inv,contents);
Brew.distillAll(inv, contents);
}
}
//player drinks a custom potion
// player drinks a custom potion
@EventHandler(priority = EventPriority.NORMAL)
public void onPlayerItemConsume(PlayerItemConsumeEvent event){
public void onPlayerItemConsume(PlayerItemConsumeEvent event) {
ItemStack item = event.getItem();
if(item != null){
if(item.getType() == Material.POTION){
if(item.hasItemMeta()){
if(BPlayer.drink(Brew.getUID(item),event.getPlayer().getName())){
if(event.getPlayer().getGameMode() != org.bukkit.GameMode.CREATIVE){
if (item != null) {
if (item.getType() == Material.POTION) {
if (item.hasItemMeta()) {
if (BPlayer.drink(Brew.getUID(item), event.getPlayer().getName())) {
if (event.getPlayer().getGameMode() != org.bukkit.GameMode.CREATIVE) {
Brew.remove(item);
}
}
@ -139,18 +135,18 @@ public class PlayerListener implements Listener{
}
}
//player walks while drunk, push him around!
// player walks while drunk, push him around!
@EventHandler(priority = EventPriority.LOW)
public void onPlayerMove(PlayerMoveEvent event){
if(BPlayer.players.containsKey(event.getPlayer().getName())){
public void onPlayerMove(PlayerMoveEvent event) {
if (BPlayer.players.containsKey(event.getPlayer().getName())) {
BPlayer.playerMove(event);
}
}
//player talks while drunk, but he cant speak very well
// player talks while drunk, but he cant speak very well
@EventHandler(priority = EventPriority.NORMAL)
public void onPlayerChat(AsyncPlayerChatEvent event){
if(BPlayer.players.containsKey(event.getPlayer().getName())){
public void onPlayerChat(AsyncPlayerChatEvent event) {
if (BPlayer.players.containsKey(event.getPlayer().getName())) {
Words.playerChat(event);
}
}