Lets Play Quake v.1.0

This commit is contained in:
Bl4ckSkull666 2016-08-20 21:35:22 +02:00
commit 8a2636cf46
108 changed files with 17436 additions and 0 deletions

73
build.xml Normal file
View File

@ -0,0 +1,73 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- You may freely edit this file. See commented blocks below for -->
<!-- some examples of how to customize the build. -->
<!-- (If you delete it and reopen the project it will be recreated.) -->
<!-- By default, only the Clean and Build commands use this build script. -->
<!-- Commands such as Run, Debug, and Test only use this build script if -->
<!-- the Compile on Save feature is turned off for the project. -->
<!-- You can turn off the Compile on Save (or Deploy on Save) setting -->
<!-- in the project's Project Properties dialog box.-->
<project name="Quake_1.9" default="default" basedir=".">
<description>Builds, tests, and runs the project Quake_1.9.</description>
<import file="nbproject/build-impl.xml"/>
<!--
There exist several targets which are by default empty and which can be
used for execution of your tasks. These targets are usually executed
before and after some main targets. They are:
-pre-init: called before initialization of project properties
-post-init: called after initialization of project properties
-pre-compile: called before javac compilation
-post-compile: called after javac compilation
-pre-compile-single: called before javac compilation of single file
-post-compile-single: called after javac compilation of single file
-pre-compile-test: called before javac compilation of JUnit tests
-post-compile-test: called after javac compilation of JUnit tests
-pre-compile-test-single: called before javac compilation of single JUnit test
-post-compile-test-single: called after javac compilation of single JUunit test
-pre-jar: called before JAR building
-post-jar: called after JAR building
-post-clean: called after cleaning build products
(Targets beginning with '-' are not intended to be called on their own.)
Example of inserting an obfuscator after compilation could look like this:
<target name="-post-compile">
<obfuscate>
<fileset dir="${build.classes.dir}"/>
</obfuscate>
</target>
For list of available properties check the imported
nbproject/build-impl.xml file.
Another way to customize the build is by overriding existing main targets.
The targets of interest are:
-init-macrodef-javac: defines macro for javac compilation
-init-macrodef-junit: defines macro for junit execution
-init-macrodef-debug: defines macro for class debugging
-init-macrodef-java: defines macro for class execution
-do-jar: JAR building
run: execution of project
-javadoc-build: Javadoc generation
test-report: JUnit report generation
An example of overriding the target for project execution could look like this:
<target name="run" depends="Quake_1.9-impl.jar">
<exec dir="bin" executable="launcher.exe">
<arg file="${dist.jar}"/>
</exec>
</target>
Notice that the overridden target depends on the jar target and not only on
the compile target as the regular run target does. Again, for a list of available
properties which you can use, check the target you are overriding in the
nbproject/build-impl.xml file.
-->
</project>

3
manifest.mf Normal file
View File

@ -0,0 +1,3 @@
Manifest-Version: 1.0
X-COMMENT: Main-Class will be added automatically by build

1419
nbproject/build-impl.xml Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,8 @@
build.xml.data.CRC32=2936ce4c
build.xml.script.CRC32=bd6b80d1
build.xml.stylesheet.CRC32=8064a381@1.79.1.48
# This file is used by a NetBeans-based IDE to track changes in generated files such as build-impl.xml.
# Do not edit this file. You may delete it but then the IDE will never regenerate such files for you.
nbproject/build-impl.xml.data.CRC32=2936ce4c
nbproject/build-impl.xml.script.CRC32=daa86fce
nbproject/build-impl.xml.stylesheet.CRC32=05530350@1.79.1.48

View File

@ -0,0 +1,86 @@
annotation.processing.enabled=true
annotation.processing.enabled.in.editor=false
annotation.processing.processors.list=
annotation.processing.run.all.processors=true
annotation.processing.source.output=${build.generated.sources.dir}/ap-source-output
application.title=Quake_1.9
application.vendor=Bl4ckSkull666
build.classes.dir=${build.dir}/classes
build.classes.excludes=**/*.java,**/*.form
# This directory is removed when the project is cleaned:
build.dir=build
build.generated.dir=${build.dir}/generated
build.generated.sources.dir=${build.dir}/generated-sources
# Only compile against the classpath explicitly listed here:
build.sysclasspath=ignore
build.test.classes.dir=${build.dir}/test/classes
build.test.results.dir=${build.dir}/test/results
# Uncomment to specify the preferred debugger connection transport:
#debug.transport=dt_socket
debug.classpath=\
${run.classpath}
debug.test.classpath=\
${run.test.classpath}
# Files in build.classes.dir which should be excluded from distribution jar
dist.archive.excludes=
# This directory is removed when the project is cleaned:
dist.dir=dist
dist.jar=${dist.dir}/Quake_1.9.jar
dist.javadoc.dir=${dist.dir}/javadoc
endorsed.classpath=
excludes=
file.reference.spigot-1.10.2.jar=D:\\AMC-Server.de\\JARs\\spigot-1.10.2.jar
file.reference.Vault_v.1.5.6.jar=../../AMC-Server.de/JARs/Vault_v.1.5.6.jar
file.reference.WorldEdit_v6.1.3.jar=D:\\AMC-Server.de\\JARs\\WorldEdit_v6.1.3.jar
file.reference.WorldEdit_v6.1.jar=../../AMC-Server.de/JARs/WorldEdit_v6.1.jar
file.reference.WorldGuard_v6.1.jar=../../AMC-Server.de/JARs/WorldGuard_v6.1.jar
includes=**
jar.compress=false
javac.classpath=\
${file.reference.WorldEdit_v6.1.jar}:\
${file.reference.WorldGuard_v6.1.jar}:\
${file.reference.Vault_v.1.5.6.jar}:\
${file.reference.WorldEdit_v6.1.3.jar}:\
${file.reference.spigot-1.10.2.jar}
# Space-separated list of extra javac options
javac.compilerargs=
javac.deprecation=false
javac.external.vm=true
javac.processorpath=\
${javac.classpath}
javac.source=1.7
javac.target=1.7
javac.test.classpath=\
${javac.classpath}:\
${build.classes.dir}
javac.test.processorpath=\
${javac.test.classpath}
javadoc.additionalparam=
javadoc.author=false
javadoc.encoding=${source.encoding}
javadoc.noindex=false
javadoc.nonavbar=false
javadoc.notree=false
javadoc.private=false
javadoc.splitindex=true
javadoc.use=true
javadoc.version=false
javadoc.windowtitle=
main.class=
manifest.file=manifest.mf
meta.inf.dir=${src.dir}/META-INF
mkdist.disabled=false
platform.active=default_platform
run.classpath=\
${javac.classpath}:\
${build.classes.dir}
# Space-separated list of JVM arguments used when running the project.
# You may also define separate properties like run-sys-prop.name=value instead of -Dname=value.
# To set system properties for unit tests define test-sys-prop.name=value:
run.jvmargs=
run.test.classpath=\
${javac.test.classpath}:\
${build.test.classes.dir}
source.encoding=UTF-8
src.dir=src
test.src.dir=test

15
nbproject/project.xml Normal file
View File

@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://www.netbeans.org/ns/project/1">
<type>org.netbeans.modules.java.j2seproject</type>
<configuration>
<data xmlns="http://www.netbeans.org/ns/j2se-project/3">
<name>Quake_1.9</name>
<source-roots>
<root id="src.dir"/>
</source-roots>
<test-roots>
<root id="test.src.dir"/>
</test-roots>
</data>
</configuration>
</project>

View File

@ -0,0 +1,260 @@
package com.Geekpower14.Quake.Arena;
import com.Geekpower14.Quake.Quake;
import com.Geekpower14.Quake.Stuff.Armor.ArmorBasic;
import com.Geekpower14.Quake.Stuff.Hat.HatBasic;
import com.Geekpower14.Quake.Stuff.Item.ItemBasic;
import com.Geekpower14.Quake.Utils.PlayerSerializer;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.Plugin;
public class APlayer {
private final Quake _plugin;
private final Arena _game;
private final Player _p;
private Boolean _Reloading = false;
private Boolean _Invincible = false;
private Boolean _VIP = false;
public int _score = 0;
public int _kill = 0;
public int _death = 0;
public ArmorBasic _armor;
public HatBasic _hat;
public ItemBasic _item;
public APlayer(Quake pl, Arena aren, Player player) {
_plugin = pl;
_game = aren;
_p = player;
if(Quake.hasPermission(player, "Quake.VIP"))
_VIP = true;
APlayer.createConfig(player);
SaveInventory();
}
public static void createConfig(Player p) {
String path = Quake.getPlugin().getDataFolder() + "/Players/" + p.getUniqueId() + ".yml";
File file = new File(path);
YamlConfiguration config = YamlConfiguration.loadConfiguration((File)file);
if (!file.exists()) {
config.set("Name", p.getName());
config.set("Hoe.Selected", "RailGun");
ArrayList<String> h = new ArrayList<>();
h.add("RailGun");
config.set("Hoe.Bought", h);
config.set("Hat.Selected", "");
ArrayList ha = new ArrayList<>();
config.set("Hat.Bought", ha);
config.set("Armor.Selected", "");
ArrayList ar = new ArrayList<>();
config.set("Armor.Bought", ar);
try {
config.save(new File(path));
} catch (IOException var7_7) {
// empty catch block
}
}
}
public void SaveInventory() {
FileConfiguration config = PlayerSerializer.PlayerToConfig(_p);
try {
config.save(new File(_plugin.getDataFolder() + "/Save_Players/" + _p.getUniqueId() + ".yml"));
} catch (IOException var2_2) {
// empty catch block
}
}
public void RestoreInventory() {
File f = new File(_plugin.getDataFolder() + "/Save_Players/" + _p.getUniqueId() + ".yml");
YamlConfiguration config = YamlConfiguration.loadConfiguration((File)f);
PlayerSerializer.ConfigToPlayer(_p, (FileConfiguration)config);
f.delete();
}
public String getConfig() {
return _plugin.getDataFolder() + "/Players/" + _p.getUniqueId() + ".yml";
}
public void initConfig() {
}
public void getKits() {
_item = _plugin._stuff.getSelectedItem(this);
_hat = _plugin._stuff.getSelectedHat(this);
_armor = _plugin._stuff.getSelectedArmor(this);
}
public void giveKit() {
if (_item != null) {
_p.getInventory().addItem(new ItemStack[]{_item.getItem()});
}
if (_hat != null) {
_p.getInventory().setHelmet(_hat.getItem());
}
if (_armor != null) {
_p.getInventory().setChestplate(_armor.getItem());
}
}
public void giveHat() {
if (_hat != null) {
_p.getInventory().setHelmet(_hat.getItem());
}
}
public void giveArmor() {
if (_armor != null) {
_p.getInventory().setChestplate(_armor.getItem());
}
}
public void giveItem() {
if (_item != null) {
_p.getInventory().addItem(new ItemStack[]{_item.getItem()});
}
}
public void saveConfig(FileConfiguration config) {
try {
config.save(new File(_plugin.getDataFolder(), "/Players/" + _p.getUniqueId() + ".yml"));
}
catch (IOException e) {
_plugin.getLogger().warning("save de " + _p.getName() + " impossible !");
}
}
public void setReloading(Long Ticks) {
_Reloading = true;
final Long temp = Ticks;
_p.setExp(0.0f);
final int infoxp = Bukkit.getScheduler().scheduleSyncRepeatingTask((Plugin)_plugin, new Runnable() {
@Override
public void run() {
float xp = _p.getExp();
if ((xp += getincr(temp)) >= 1.0f) {
xp = 1.0f;
}
_p.setExp(xp);
}
}, 0, 2);
Bukkit.getScheduler().scheduleSyncDelayedTask((Plugin)_plugin, new Runnable() {
@Override
public void run() {
APlayer.access$1(APlayer.this, false);
_p.setExp(1.0f);
_plugin.getServer().getScheduler().cancelTask(infoxp);
}
}, Ticks.longValue());
}
public void setReloading(Boolean t) {
_Reloading = t;
}
public void setinvincible(Boolean t) {
_Invincible = t;
}
public boolean isReloading() {
return _Reloading;
}
public boolean isInvincible() {
return _Invincible;
}
public boolean isVIP() {
return _VIP;
}
public void setInvincible(Long Ticks) {
_Invincible = true;
final Long temp = Ticks;
_p.setExp(0.0f);
final int infoxp = Bukkit.getScheduler().scheduleSyncRepeatingTask((Plugin)_plugin, new Runnable() {
@Override
public void run() {
float xp = _p.getExp();
if ((xp += getincr(temp)) >= 1.0f) {
xp = 1.0f;
}
_p.setExp(xp);
}
}, 0, 2);
Bukkit.getScheduler().scheduleSyncDelayedTask((Plugin)_plugin, new Runnable() {
@Override
public void run() {
APlayer.access$3(APlayer.this, false);
_p.setExp(1.0f);
_plugin.getServer().getScheduler().cancelTask(infoxp);
}
}, Ticks);
}
public float getincr(Long time) {
float result = 0.0f;
float temp = time;
result = 100.0f / (temp / 2.0f) / 100.0f;
return result;
}
public Arena getGame() {
return _game;
}
public Player getPlayer() {
return _p;
}
public void tell(String message) {
_p.sendMessage(message);
}
public void setLevel(int xp) {
_p.setLevel(xp);
}
public String getName() {
return _p.getName();
}
public String getDisplayName() {
return _p.getDisplayName();
}
public Location getLocation() {
return _p.getLocation();
}
public Location getEyeLocation() {
return _p.getEyeLocation();
}
public boolean isDead() {
return _p.isDead();
}
static /* synthetic */ void access$1(APlayer aPlayer, Boolean bl) {
aPlayer._Reloading = bl;
}
static /* synthetic */ void access$3(APlayer aPlayer, Boolean bl) {
aPlayer._Invincible = bl;
}
}

View File

@ -0,0 +1,95 @@
package com.Geekpower14.Quake.Arena;
import com.Geekpower14.Quake.Quake;
import java.util.ArrayList;
import java.util.Set;
import org.bukkit.ChatColor;
import org.bukkit.Color;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.LeatherArmorMeta;
import org.bukkit.scoreboard.Team;
public class ATeam {
private Team _team;
public String _name;
public ChatColor _color;
public Color _Scolor;
public Arena _aren;
public int _Score = 0;
public ATeam(Quake pl, Arena aren, String name, ChatColor color, Color scolor) {
_name = name;
_color = color;
_aren = aren;
_Scolor = scolor;
createTeam();
}
public void createTeam() {
_team = _aren._board.registerNewTeam(_name);
_team.setPrefix(String.valueOf(_color));
_team.setCanSeeFriendlyInvisibles(true);
}
public void setScore(int s) {
_Score = s;
}
public int getScore() {
return _Score;
}
public void addScore(int s) {
_Score += s;
}
public String getName() {
return _name;
}
public void addPlayer(Player p) {
_team.addEntry(p.getName());
}
public void removePlayer(Player p) {
_team.removeEntry(p.getName());
}
public Boolean hasPlayer(Player p) {
return _team.hasEntry(p.getName());
}
public void giveChestplate(Player p) {
ItemStack item = new ItemStack(Material.LEATHER_CHESTPLATE);
LeatherArmorMeta meta = (LeatherArmorMeta)item.getItemMeta();
meta.setDisplayName(_color + "Team " + _name);
ArrayList<String> l = new ArrayList<>();
l.add(ChatColor.RESET + "A beautiful leather dress!");
meta.setLore(l);
meta.setColor(_Scolor);
item.setItemMeta((ItemMeta)meta);
p.getInventory().setChestplate(item);
}
public Set<String> getPlayers() {
return _team.getEntries();
}
public int getSize() {
return _team.getEntries().size();
}
public void reset() {
_Score = 0;
_team.unregister();
createTeam();
}
public ChatColor getColor() {
return _color;
}
}

View File

@ -0,0 +1,425 @@
package com.Geekpower14.Quake.Arena;
import com.Geekpower14.Quake.Eco.EcoManager;
import com.Geekpower14.Quake.Quake;
import com.Geekpower14.Quake.Trans.Score;
import com.Geekpower14.Quake.Utils.FireworkEffectPlayer;
import com.Geekpower14.Quake.Utils.PlayerSerializer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Color;
import org.bukkit.FireworkEffect;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.Sound;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.plugin.Plugin;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import org.bukkit.scoreboard.Objective;
import org.bukkit.scoreboard.Scoreboard;
import org.bukkit.scoreboard.ScoreboardManager;
public abstract class Arena {
public String _name;
public int _ID;
public int _timer;
public Boolean _Active = false;
public Quake _plugin;
public int _ingame = 50;
public int _pregame = 40;
public int _starting = 30;
public long _after = 15;
public Boolean _finished = false;
public Boolean _stopping = false;
public int _compteur = 0;
public int _etat = _pregame;
public int _goal = 25;
public Boolean _full = false;
public Boolean _NaturalDeath = false;
public Boolean _VIP = false;
public Boolean _Sneak = true;
public Boolean _Global_Chat = false;
public Boolean _Auto_Respawn = false;
public HashMap<String, APlayer> _players = new HashMap();
public List<Location> _spawns_B = new ArrayList<>();
public List<Location> _spawns_R = new ArrayList<>();
public List<Location> _spawns = new ArrayList<>();
public int _Coins_Win = 0;
public int _Coins_Kill = 0;
public double _VIP_M = 2.0;
public double _VIPP_M = 3.0;
public String _map;
public int _maxplayer;
public int _minplayer;
public ScoreboardManager _scoremanager;
public Scoreboard _board;
public Objective _objective;
public Objective _obj_side;
FireworkEffectPlayer _fw;
public List<PotionEffect> _potions = new ArrayList<>();
public Arena(Quake pl, String n, int ID) {
_plugin = pl;
_name = n;
_ID = ID;
_maxplayer = 11;
_minplayer = 2;
_etat = _pregame;
_map = "unknown";
_fw = new FireworkEffectPlayer(_plugin);
testConfig();
loadConfig();
_scoremanager = Bukkit.getScoreboardManager();
_board = _scoremanager.getNewScoreboard();
_Active = true;
}
public void resetArena() {
_etat = _pregame;
_full = false;
_players.clear();
_stopping = false;
_finished = false;
_compteur = 0;
}
public abstract Boolean reloadConfig();
public abstract Boolean loadConfig();
public abstract Boolean testConfig();
public abstract Boolean saveConfig();
public String PoToStr(PotionEffect popo) {
return String.valueOf(popo.getType().getName()) + ":" + popo.getAmplifier();
}
public PotionEffect StrToPo(String popo) {
String[] list = popo.split(":");
return new PotionEffect(PotionEffectType.getByName((String)list[0]), Integer.MAX_VALUE, Integer.valueOf(list[1]).intValue());
}
protected void setDefaultConfig(FileConfiguration config, String key, Object value) {
if (!config.isSet(key)) {
config.set(key, value);
}
}
public void broadcast(String message) {
for(APlayer player : _players.values())
player.tell(ChatColor.GRAY + "[" + ChatColor.RED + "Quake" + ChatColor.GRAY + "]: " + message);
}
public void chat(String message) {
for(APlayer player : _players.values())
player.tell(message);
}
public void nbroadcast(String message) {
for(APlayer player : _players.values())
player.tell(message);
}
public void broadcastXP(int xp) {
for(APlayer player : _players.values())
player.setLevel(xp);
}
public void playsound(Sound sound, float a, float b) {
for(APlayer player : _players.values())
player.getPlayer().playSound(player.getPlayer().getLocation(), sound, a, b);
}
public void getGainKill(Player player) {
double m = 1.0;
if(Quake.hasPermission(player, "Quake.vip"))
m = _VIP_M;
if(Quake.hasPermission(player, "Quake.vip+"))
m = _VIPP_M;
EcoManager eco = _plugin._eco;
eco.addPlayerMoney(player, (int)((double)_Coins_Kill*m));
eco.addScore(player, Score.Type.Kill, 1);
}
public void getScoreShot(Player p) {
EcoManager eco = _plugin._eco;
eco.addScore(p, Score.Type.Shot, 1);
}
public void getScoreDeath(Player p) {
EcoManager eco = _plugin._eco;
eco.addScore(p, Score.Type.Death, 1);
}
public void getGainWin(Player player) {
double m = 1.0;
if (Quake.hasPermission(player, "Quake.vip")) {
m = _VIP_M;
}
if (Quake.hasPermission(player, "Quake.vip+")) {
m = _VIPP_M;
}
double gain = (double)_Coins_Win * m;
EcoManager eco = _plugin._eco;
eco.addPlayerMoney(player, (int)gain);
eco.addScore(player, Score.Type.Win, 1);
}
public void setActive(Boolean active) {
_Active = active;
}
public void setmap(String map) {
_map = map;
}
public void setmax(int max) {
_maxplayer = max;
}
public void setmin(int min) {
_minplayer = min;
}
public Location str2loc(String loc) {
if (loc == null) {
return null;
}
Location res = null;
String[] loca = loc.split(", ");
res = new Location(_plugin.getServer().getWorld(loca[0]), Double.parseDouble(loca[1]), Double.parseDouble(loca[2]), Double.parseDouble(loca[3]), Float.parseFloat(loca[4]), Float.parseFloat(loca[5]));
return res;
}
protected String loc2str(Location loc) {
return loc.getWorld().getName() + ", " + loc.getX() + ", " + loc.getY() + ", " + loc.getZ() + ", " + loc.getYaw() + ", " + loc.getPitch();
}
public abstract void joinArena(Player var1);
public abstract void updateScore();
public abstract void leaveArena(Player var1);
public abstract void CrashLeaveArena(Player var1);
public static void RejoinAfterCrash(Player p) {
Arena.quitcleaner(p);
if (Quake.getPlugin()._lobby._lobbyspawn != null) {
p.teleport(Quake.getPlugin()._lobby._lobbyspawn);
}
PlayerSerializer.RetorePlayer(p);
}
public void resetCountdown() {
broadcast(_plugin._trad.get("Game.Arena.Message.Aborde-Game"));
_etat = _pregame;
broadcastXP(_starting);
}
public void cleaner(Player player) {
player.setGameMode(GameMode.SURVIVAL);
player.setHealth(20.0);
player.setSaturation(10.0f);
player.setFoodLevel(20);
player.getInventory().clear();
player.getInventory().setHelmet(new ItemStack(Material.AIR, 1));
player.getInventory().setChestplate(new ItemStack(Material.AIR, 1));
player.getInventory().setLeggings(new ItemStack(Material.AIR, 1));
player.getInventory().setBoots(new ItemStack(Material.AIR, 1));
player.getInventory().setHeldItemSlot(0);
player.setExp(1.0f);
player.setLevel(0);
try {
player.updateInventory();
}
catch (Exception var2_2) {
// empty catch block
}
}
public static void quitcleaner(Player player) {
for (PotionEffect effect : player.getActivePotionEffects()) {
player.removePotionEffect(effect.getType());
}
try {
player.updateInventory();
}
catch (Exception effect) {
// empty catch block
}
}
public abstract void stop();
public void startDelayed() {
broadcast(_plugin._trad.get("Game.Arena.Message.RemainTime").replace("[TIME]", "" + _starting));
_etat = _starting;
broadcastXP(_etat);
_timer = _plugin.getServer().getScheduler().scheduleSyncRepeatingTask((Plugin)_plugin, (Runnable)new Timer(_plugin, this), 0, 20);
}
public abstract void start();
public void giveStuff(Player player) {
APlayer ap = getAPlayer(player);
ap.getKits();
ap.giveHat();
ap.giveItem();
ap.giveArmor();
player.getInventory().setItem(8, getLeaveDoor());
player.getInventory().setHeldItemSlot(0);
}
public ItemStack getLeaveDoor() {
ItemStack coucou = new ItemStack(Material.WOOD_DOOR, 1);
ItemMeta coucou_meta = coucou.getItemMeta();
coucou_meta.setDisplayName(_plugin._trad.get("Game.item.leave"));
coucou.setItemMeta(coucou_meta);
return coucou;
}
public void giveEffect(Player player) {
for (PotionEffect effect : player.getActivePotionEffects()) {
player.removePotionEffect(effect.getType());
}
for (PotionEffect popo : _potions) {
player.addPotionEffect(popo);
}
}
public void shotplayer(final Player shooter, Player victim, FireworkEffect effect) {
APlayer ashooter = getAPlayer(shooter);
APlayer avictim = getAPlayer(victim);
if (victim != shooter && !avictim.isInvincible()) {
Bukkit.getScheduler().scheduleSyncDelayedTask((Plugin)_plugin, new Runnable() {
@Override
public void run() {
getGainKill(shooter);
}
}, 2);
try {
_fw.playFirework(victim.getWorld(), victim.getLocation(), effect);
} catch (Exception e) {
e.printStackTrace();
}
kill(victim);
broadcast(_plugin._trad.get("Game.Arena.Message.Shot").replace("[SHOOTER]", shooter.getName()).replace("[KILLED]", victim.getName()));
++ashooter._score;
if (ashooter._score == _goal) {
Bukkit.getScheduler().scheduleSyncDelayedTask((Plugin)_plugin, new Runnable(){
@Override
public void run() {
win(shooter);
}
}, 2);
}
updateScore();
}
}
public void kill(Player p) {
p.setHealth(0.0);
_Auto_Respawn = true;
}
public abstract void win(Player var1);
public Color getColor(int i) {
Color c = null;
if (i == 1) {
c = Color.AQUA;
}
if (i == 2) {
c = Color.BLACK;
}
if (i == 3) {
c = Color.BLUE;
}
if (i == 4) {
c = Color.FUCHSIA;
}
if (i == 5) {
c = Color.GRAY;
}
if (i == 6) {
c = Color.GREEN;
}
if (i == 7) {
c = Color.LIME;
}
if (i == 8) {
c = Color.MAROON;
}
if (i == 9) {
c = Color.NAVY;
}
if (i == 10) {
c = Color.OLIVE;
}
if (i == 11) {
c = Color.ORANGE;
}
if (i == 12) {
c = Color.PURPLE;
}
if (i == 13) {
c = Color.RED;
}
if (i == 14) {
c = Color.SILVER;
}
if (i == 15) {
c = Color.TEAL;
}
if (i == 16) {
c = Color.WHITE;
}
if (i == 17) {
c = Color.YELLOW;
}
return c;
}
public void disable() {
_Active = false;
stop();
}
public void tp(Player player) {
player.teleport(getTp(player));
}
public abstract Location getTp(Player var1);
public Boolean isingame(Player player) {
return _players.containsKey(player.getName());
}
public int getplayers() {
return _players.size();
}
public APlayer getAPlayer(Player play) {
for (APlayer p : _players.values()) {
if (!p.getPlayer().getName().equals(play.getName())) continue;
return p;
}
return null;
}
}

View File

@ -0,0 +1,172 @@
package com.Geekpower14.Quake.Arena;
import com.Geekpower14.Quake.Quake;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
public class ArenaManager {
public Quake _plugin;
public HashMap<String, Arena> _ARENAS = new HashMap();
public ArenaManager(Quake pl) {
_plugin = pl;
loadArenas();
}
public final void loadArenas() {
File folder = new File(_plugin.getDataFolder(), "/arenas/");
if (!folder.exists()) {
folder.mkdir();
}
ArrayList<String> Maps = new ArrayList<>();
for(File f: folder.listFiles()) {
String name = f.getName().replaceAll(".yml", "");
Maps.add(name);
}
if(Maps.isEmpty())
return;
for(String mapname : Maps) {
YamlConfiguration config = YamlConfiguration.loadConfiguration(new File(_plugin.getDataFolder(), "/arenas/" + mapname + ".yml"));
String type = "Solo";
if(config.getString("Type", "Solo").equalsIgnoreCase("Team"))
type = "Team";
createArena(mapname, type);
}
}
public void createArena(String name, String Type2) {
if (name == null) {
return;
}
Arena arena = null;
if (Type2.equalsIgnoreCase("Solo")) {
arena = new SArena(_plugin, name, _ARENAS.size());
_ARENAS.put(name, arena);
} else if(Type2.equalsIgnoreCase("Team")) {
arena = new TArena(_plugin, name, _ARENAS.size());
_ARENAS.put(name, arena);
}
}
public String getPlayerhoe(String player) {
File fichier_config = new File(_plugin.getDataFolder(), "hoe.yml");
if(!fichier_config.exists())
return null;
YamlConfiguration config = YamlConfiguration.loadConfiguration((File)fichier_config);
return config.getString(player);
}
public void setPlayerhoe(String player, String hoe) {
YamlConfiguration config = YamlConfiguration.loadConfiguration((File)new File(_plugin.getDataFolder(), "hoe.yml"));
config.set(player, hoe);
try {
config.save(new File(_plugin.getDataFolder(), "hoe.yml"));
_plugin.saveConfig();
} catch (IOException var4_4) {
// empty catch block
}
}
public void removeArena(String name) {
Arena aren = _ARENAS.get(name);
aren.stop();
_ARENAS.remove(name);
}
public void deleteArena(String name) {
Arena aren = _ARENAS.get(name);
aren.stop();
File file = new File(_plugin.getDataFolder(), "/arenas/" + aren._name + ".yml");
file.delete();
_ARENAS.remove(name);
}
public Boolean exist(String aren) {
return _ARENAS.containsKey(aren);
}
public Boolean existid(int ID) {
Arena arena = getArenabyID(ID);
return arena != null;
}
public Arena getArenabyName(String name) {
if (_ARENAS.size() < 1) {
return null;
}
return _ARENAS.get(name);
}
public Arena getArenabyPlayer(Player player) {
if(_ARENAS.size() < 1) {
return null;
}
for(Arena aren : _ARENAS.values()) {
if(!aren.isingame(player))
continue;
return aren;
}
return null;
}
public Boolean isArenaWorld(World world) {
if (_ARENAS.size() < 1) {
return false;
}
for (Arena arena : _ARENAS.values()) {
Location wo;
World w;
if (arena instanceof SArena) {
SArena aren = (SArena)arena;
if(aren._spawns.isEmpty() || world != aren._spawns.get(0).getWorld())
continue;
return true;
}
if (!(arena instanceof TArena))
continue;
TArena aren = (TArena)arena;
if(aren._spawns_B.isEmpty() || world != aren._spawns_B.get(0).getWorld())
continue;
return true;
}
return false;
}
public Arena getArenabyID(int ID) {
if (_ARENAS.size() < 1) {
return null;
}
for(Arena aren : _ARENAS.values()) {
if (aren._ID != ID)
continue;
return aren;
}
return null;
}
public void reloadArenas() {
for(Arena aren : _ARENAS.values()) {
aren.reloadConfig();
}
}
public void Disable() {
for(Arena aren : _ARENAS.values()) {
aren.disable();
}
}
public void updateScoreArenas() {
for(Arena aren : _ARENAS.values()) {
aren.updateScore();
}
}
}

View File

@ -0,0 +1,261 @@
package com.Geekpower14.Quake.Arena;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.YamlConfiguration;
public class ConfigManager {
private YamlConfiguration _cfg = new YamlConfiguration();
private File _configFile;
private Map<String, Boolean> _booleans;
private Map<String, Integer> _ints;
private Map<String, Double> _doubles;
private Map<String, String> _strings;
public ConfigManager(File configFile) {
_configFile = configFile;
_booleans = new HashMap<>();
_ints = new HashMap<>();
_doubles = new HashMap<>();
_strings = new HashMap<>();
}
public void createDefaults() {
_cfg.options().indent(4);
for(ACFG cfg: ACFG.values())
_cfg.addDefault(cfg.getNode(), cfg.getValue());
save();
}
public boolean load() {
try {
_cfg.load(_configFile);
reloadMaps();
return true;
} catch (IOException | InvalidConfigurationException e) {
e.printStackTrace();
return false;
}
}
public void reloadMaps() {
for(String s : _cfg.getKeys(true)) {
Object object = _cfg.get(s);
if(object instanceof Boolean) {
_booleans.put(s, (Boolean)object);
continue;
}
if(object instanceof Integer) {
_ints.put(s, (Integer)object);
continue;
}
if(object instanceof Double) {
_doubles.put(s, (Double)object);
continue;
}
if(!(object instanceof String))
continue;
_strings.put(s, (String)object);
}
}
public boolean save() {
try {
_cfg.save(_configFile);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public boolean delete() {
return _configFile.delete();
}
public void setHeader(String header) {
_cfg.options().header(header);
}
public YamlConfiguration getYamlConfiguration() {
return _cfg;
}
public Object getUnsafe(String string) {
return _cfg.get(string);
}
public boolean getBoolean(ACFG cfg) {
return getBoolean(cfg, (Boolean)cfg.getValue());
}
private boolean getBoolean(ACFG cfg, boolean def) {
String path = cfg.getNode();
Boolean result = _booleans.get(path);
return result == null ? def : result;
}
public int getInt(ACFG cfg) {
return getInt(cfg, (Integer)cfg.getValue());
}
public int getInt(ACFG cfg, int def) {
String path = cfg.getNode();
Integer result = _ints.get(path);
return result == null ? def : result;
}
public double getDouble(ACFG cfg) {
return getDouble(cfg, (Double)cfg.getValue());
}
public double getDouble(ACFG cfg, double def) {
String path = cfg.getNode();
Double result = _doubles.get(path);
return result == null ? def : result;
}
public String getString(ACFG cfg) {
return getString(cfg, (String)cfg.getValue());
}
public String getString(ACFG cfg, String def) {
String path = cfg.getNode();
String result = _strings.get(path);
return result == null ? def : result;
}
public Set<String> getKeys(String path) {
if(_cfg.get(path) == null) {
return null;
}
ConfigurationSection section = _cfg.getConfigurationSection(path);
return section.getKeys(false);
}
public List<String> getStringList(String path, List<String> def) {
if(_cfg.get(path) == null) {
return def == null ? new LinkedList() : def;
}
return _cfg.getStringList(path);
}
public void setManually(String path, Object value) {
if(value instanceof Boolean) {
_booleans.put(path, (Boolean)value);
} else if (value instanceof Integer) {
_ints.put(path, (Integer)value);
} else if (value instanceof Double) {
_doubles.put(path, (Double)value);
} else if (value instanceof String) {
_strings.put(path, (String)value);
} else
_cfg.set(path, value);
}
public void set(ACFG cfg, Object value) {
setManually(cfg.getNode(), value);
}
public Location str2loc(String loc) {
if (loc == null) {
return null;
}
Location res = null;
String[] loca = loc.split(", ");
res = new Location(Bukkit.getServer().getWorld(loca[0]), Double.parseDouble(loca[1]), Double.parseDouble(loca[2]), Double.parseDouble(loca[3]), Float.parseFloat(loca[4]), Float.parseFloat(loca[5]));
return res;
}
public static enum ACFG {
Z("configversion", "v0.9.0.0"),
Spawns("Nombre", new ArrayList()),
CHAT_DEFAULTTEAM("chat.defaultTeam", Boolean.valueOf(false)),
MODULES_WORLDEDIT_AUTOLOAD("modules.worldedit.autoload", Boolean.valueOf(false)),
MODULES_WORLDEDIT_AUTOSAVE("modules.worldedit.autosave", Boolean.valueOf(false));
private String _node;
private final Object _value;
private final String _type;
public static ACFG getByNode(String node) {
ACFG[] arraCFG = ACFG.values();
int n = arraCFG.length;
int n2 = 0;
while (n2 < n) {
ACFG m = arraCFG[n2];
if (m.getNode().equals(node)) {
return m;
}
++n2;
}
return null;
}
private ACFG(String node, String s) {
_node = node;
_value = s;
_type = "string";
}
private ACFG(String node, Boolean b) {
_node = node;
_value = b;
_type = "boolean";
}
private ACFG(String node, Integer i) {
_node = node;
_value = i;
_type = "int";
}
private ACFG(String node, Double d) {
_node = node;
_value = d;
_type = "double";
}
private ACFG(String node, List<String> value) {
_node = node;
_value = value;
_type = "list";
}
public String getNode() {
return _node;
}
public void setNode(String value) {
_node = value;
}
@Override
public String toString() {
return String.valueOf(_value);
}
public Object getValue() {
return _value;
}
public static ACFG[] getValues() {
return ACFG.values();
}
public String getType() {
return _type;
}
}
}

View File

@ -0,0 +1,376 @@
package com.Geekpower14.Quake.Arena;
import com.Geekpower14.Quake.Quake;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.logging.Level;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Color;
import org.bukkit.FireworkEffect;
import org.bukkit.Location;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Firework;
import org.bukkit.entity.Player;
import org.bukkit.inventory.meta.FireworkMeta;
import org.bukkit.plugin.Plugin;
import org.bukkit.potion.PotionEffect;
import org.bukkit.scoreboard.DisplaySlot;
public class SArena extends Arena {
public SArena(Quake pl, String n, int ID) {
super(pl, n, ID);
}
@Override
public Boolean reloadConfig() {
if (_etat != _pregame) {
stop();
}
testConfig();
loadConfig();
return true;
}
@Override
public Boolean loadConfig() {
File fichier_config = new File(_plugin.getDataFolder(), "/arenas/" + _name + ".yml");
YamlConfiguration config = YamlConfiguration.loadConfiguration((File)fichier_config);
if (config.contains("Nombre")) {
int nombre = config.getInt("Nombre");
for (int i = 0; i < nombre; i++) {
String nom = config.getString("spawn" + i);
_spawns.add(i, str2loc(nom));
}
} else {
List<Location> s = new ArrayList();
for(String spawn : config.getStringList("Spawns")) {
s.add(str2loc(spawn));
}
_spawns = s;
}
_map = config.getString("Map");
_maxplayer = config.getInt("MaxPlayers");
_minplayer = config.getInt("MinPlayers");
_Active = config.getBoolean("Active");
_NaturalDeath = config.getBoolean("Natural-Death");
_Auto_Respawn = config.getBoolean("Auto-Respawn");
_VIP = config.getBoolean("VIP");
_goal = config.getInt("Goal");
_starting = config.getInt("Time-Before");
_after = config.getLong("Time-After");
_Coins_Win = config.getInt("Coins-per-Win");
_Coins_Kill = config.getInt("Coins-per-Kill");
_VIP_M = config.getDouble("VIP-Multiplicator");
_VIPP_M = config.getDouble("VIP+-Multiplicator");
_Global_Chat = config.getBoolean("Global-Chat");
_Sneak = config.getBoolean("Sneak");
ArrayList<PotionEffect> l = new ArrayList<>();
for (String popo : config.getStringList("Potions"))
l.add(StrToPo(popo));
_potions = l;
if(config.contains("Nombre"))
saveConfig();
return true;
}
@Override
public Boolean testConfig() {
YamlConfiguration config = YamlConfiguration.loadConfiguration((File)new File(_plugin.getDataFolder(), "/arenas/" + _name + ".yml"));
setDefaultConfig((FileConfiguration)config, "Version", Quake._version);
setDefaultConfig((FileConfiguration)config, "Name", _name);
setDefaultConfig((FileConfiguration)config, "Type", "Solo");
setDefaultConfig((FileConfiguration)config, "Map", "Unknown");
setDefaultConfig((FileConfiguration)config, "Active", true);
setDefaultConfig((FileConfiguration)config, "Natural-Death", false);
setDefaultConfig((FileConfiguration)config, "Auto-Respawn", false);
setDefaultConfig((FileConfiguration)config, "VIP", false);
setDefaultConfig((FileConfiguration)config, "Goal", 25);
setDefaultConfig((FileConfiguration)config, "Time-Before", 30);
setDefaultConfig((FileConfiguration)config, "Time-After", 15);
setDefaultConfig((FileConfiguration)config, "Coins-per-Win", 20);
setDefaultConfig((FileConfiguration)config, "Coins-per-Kill", 1);
setDefaultConfig((FileConfiguration)config, "VIP-Multiplicator", 2);
setDefaultConfig((FileConfiguration)config, "VIP+-Multiplicator", 3);
setDefaultConfig((FileConfiguration)config, "Global-Chat", false);
ArrayList<String> l = new ArrayList<>();
l.add("SPEED:2");
l.add("JUMP:1");
setDefaultConfig((FileConfiguration)config, "Potions", l);
setDefaultConfig((FileConfiguration)config, "MaxPlayers", 11);
setDefaultConfig((FileConfiguration)config, "MinPlayers", 2);
setDefaultConfig((FileConfiguration)config, "Sneak", true);
setDefaultConfig((FileConfiguration)config, "Spawns", new ArrayList());
try {
config.save(new File(_plugin.getDataFolder(), "/arenas/" + _name + ".yml"));
} catch (IOException e) {
_plugin.getLogger().warning("save default de " + _name + " impossible !");
disable();
}
return true;
}
@Override
public Boolean saveConfig() {
YamlConfiguration config = YamlConfiguration.loadConfiguration((File)new File(_plugin.getDataFolder(), "/arenas/" + _name + ".yml"));
config.set("Name", _name);
config.set("Type", "Solo");
config.set("Map", _map);
config.set("Active", _Active);
config.set("VIP", _VIP);
config.set("Global-Chat", _Global_Chat);
config.set("Natural-Death", _NaturalDeath);
config.set("Auto-Respawn", _Auto_Respawn);
config.set("Sneak", _Sneak);
ArrayList<String> l = new ArrayList<>();
for(PotionEffect popo : _potions)
l.add(PoToStr(popo));
config.set("Potions", l);
config.set("MaxPlayers", _maxplayer);
config.set("MinPlayers", _minplayer);
config.set("Sneak", _Sneak);
ArrayList<String> s = new ArrayList<>();
for(Location loc : _spawns)
s.add(loc2str(loc));
config.set("Spawns", s);
try {
config.save(new File(_plugin.getDataFolder(), "/arenas/" + _name + ".yml"));
_plugin.saveConfig();
} catch (IOException e) {
_plugin.getLogger().warning("save de " + _name + "impossible !");
disable();
return false;
}
return true;
}
@Override
public void joinArena(Player player) {
if (_spawns.isEmpty()) {
player.sendMessage(_plugin._trad.get("Game.Arena.error.NoSpawn"));
return;
}
if (_etat > _pregame && !Quake.hasPermission(player, "Quake.JoinInGame")) {
player.sendMessage(_plugin._trad.get("Game.Arena.error.inGame"));
return;
}
if (_VIP && !Quake.hasPermission(player, "Quake.VIP")) {
player.sendMessage(_plugin._trad.get("Game.Arena.error.VIP"));
return;
}
if (_full && !Quake.hasPermission(player, "Quake.VIP")) {
player.sendMessage(_plugin._trad.get("Game.Arena.error.full"));
return;
}
if (_players.size() > _maxplayer - 1) {
_full = true;
}
APlayer ap = new APlayer(_plugin, this, player);
_players.put(player.getName(), ap);
broadcast(_plugin._trad.get("Game.Arena.Message.Join").replace("[PLAYER]", player.getName()).replace("[NUMBER]", "" + _players.size()).replace("[MAX]", "" + _maxplayer));
if (_players.size() >= _minplayer && _etat == _pregame) {
startDelayed();
}
if (_etat > _pregame && Quake.hasPermission(player, "Quake.JoinInGame")) {
tp(player);
cleaner(player);
updateScore();
ap.setInvincible(40L);
final Player p = player;
Bukkit.getScheduler().scheduleSyncDelayedTask(_plugin, new Runnable() {
@Override
public void run() {
giveStuff(p);
}
}, 20);
Bukkit.getScheduler().scheduleSyncDelayedTask((Plugin)_plugin, new Runnable() {
@Override
public void run() {
giveEffect(p);
giveEffect(p);
}
}, 35);
} else {
tp(player);
cleaner(player);
player.getInventory().setItem(8, getLeaveDoor());
player.getInventory().setHeldItemSlot(0);
try {
player.updateInventory();
}
catch (Exception p) {
// empty catch block
}
}
}
@Override
public void leaveArena(Player player) {
APlayer ap = getAPlayer(player);
SArena.quitcleaner(player);
player.setScoreboard(_scoremanager.getNewScoreboard());
if (_players.size() <= 2 && !_stopping && _etat == _ingame) {
stop();
}
if (_players.size() < _minplayer && !_stopping && _etat <= _starting) {
resetCountdown();
}
if (_plugin._lobby._lobbyspawn != null) {
player.teleport(_plugin._lobby._lobbyspawn);
} else {
Location wo = (Location)_spawns.get(0);
if (wo != null) {
player.teleport(wo.getWorld().getSpawnLocation());
}
}
ap.RestoreInventory();
_players.remove(player.getName());
}
@Override
public void CrashLeaveArena(Player player) {
_players.remove(player.getName());
if (_players.size() <= 1 && !_stopping && _etat == _ingame) {
stop();
}
if (_players.size() < _minplayer && !_stopping && _etat <= _starting) {
resetCountdown();
}
}
@Override
public void updateScore() {
if(_players.size() <= 0)
return;
for(APlayer player2 : _players.values())
_objective.getScore(player2.getName()).setScore(player2._score);
for(APlayer player2 : _players.values())
player2.getPlayer().setScoreboard(_objective.getScoreboard());
}
@Override
public void stop() {
_stopping = true;
_plugin.getServer().getScheduler().cancelTask(_timer);
for(APlayer play : _players.values()) {
Player player = play.getPlayer();
SArena.quitcleaner(player);
player.setScoreboard(_scoremanager.getNewScoreboard());
if(_plugin._lobby._lobbyspawn != null)
player.teleport(_plugin._lobby._lobbyspawn);
play.RestoreInventory();
}
_stopping = false;
resetArena();
}
@Override
public void start() {
_etat = _ingame;
if (_objective != null) {
_objective.unregister();
}
_objective = _board.registerNewObjective(_name, "dummy");
_objective.setDisplaySlot(DisplaySlot.SIDEBAR);
_objective.setDisplayName("Score");
for(APlayer play : _players.values()) {
Player player = play.getPlayer();
cleaner(player);
giveStuff(player);
tp(player);
updateScore();
giveEffect(player);
}
}
public void addspawn(Location loc) {
_spawns.add(loc);
}
public void removespawn(String args) {
_spawns.remove(Integer.parseInt(args));
}
@Override
public void win(final Player player) {
getGainWin(player);
_finished = true;
nbroadcast(ChatColor.GOLD + "#" + ChatColor.GRAY + "--------------------" + ChatColor.GOLD + "#");
nbroadcast("" + ChatColor.GRAY);
nbroadcast(_plugin._trad.get("Game.Arena.Message.Won").replace("[NAME]", player.getName()));
nbroadcast("" + ChatColor.GRAY);
nbroadcast(ChatColor.GOLD + "#" + ChatColor.GRAY + "--------------------" + ChatColor.GOLD + "#");
_plugin.getLogger().log(Level.INFO, _plugin._trad.get("Game.Arena.Message.Won").replace("[NAME]", player.getName()));
final int nb = (int)((double)_after * 1.5);
final int infoxp = Bukkit.getScheduler().scheduleSyncRepeatingTask(_plugin, new Runnable() {
@Override
public void run() {
if(_compteur >= nb)
return;
Firework fw = (Firework)player.getWorld().spawnEntity(player.getLocation(), EntityType.FIREWORK);
FireworkMeta fwm = fw.getFireworkMeta();
Random r = new Random();
int rt = r.nextInt(4) + 1;
FireworkEffect.Type type = FireworkEffect.Type.BALL;
if (rt == 1) {
type = FireworkEffect.Type.BALL;
}
if (rt == 2) {
type = FireworkEffect.Type.BALL_LARGE;
}
if (rt == 3) {
type = FireworkEffect.Type.BURST;
}
if (rt == 4) {
type = FireworkEffect.Type.CREEPER;
}
if (rt == 5) {
type = FireworkEffect.Type.STAR;
}
int r1i = r.nextInt(17) + 1;
int r2i = r.nextInt(17) + 1;
Color c1 = getColor(r1i);
Color c2 = getColor(r2i);
FireworkEffect effect = FireworkEffect.builder().flicker(r.nextBoolean()).withColor(c1).withFade(c2).with(type).trail(r.nextBoolean()).build();
fwm.addEffect(effect);
int rp = r.nextInt(2) + 1;
fwm.setPower(rp);
fw.setFireworkMeta(fwm);
_compteur++;
}
}, 5, 5);
Bukkit.getScheduler().scheduleSyncDelayedTask((Plugin)_plugin, new Runnable(){
@Override
public void run() {
_plugin.getServer().getScheduler().cancelTask(infoxp);
stop();
}
}, _after * 20);
}
@Override
public Location getTp(Player player) {
int higher = _spawns.size() - 1;
if (_spawns.size() < 0) {
higher = 0;
}
int random = (int)(Math.random() * (double)higher);
Location loc = (Location)_spawns.get(random);
return loc;
}
}

View File

@ -0,0 +1,547 @@
package com.Geekpower14.Quake.Arena;
import com.Geekpower14.Quake.Quake;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.logging.Level;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Color;
import org.bukkit.FireworkEffect;
import org.bukkit.Location;
import org.bukkit.OfflinePlayer;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Firework;
import org.bukkit.entity.Player;
import org.bukkit.inventory.meta.FireworkMeta;
import org.bukkit.plugin.Plugin;
import org.bukkit.potion.PotionEffect;
import org.bukkit.scoreboard.DisplaySlot;
public class TArena extends Arena {
public List<ATeam> _Teams = new ArrayList<>();
public TArena(Quake pl, String n, int ID) {
super(pl, n, ID);
_Teams.add(new ATeam(pl, this, "Blue", ChatColor.BLUE, Color.BLUE));
_Teams.add(new ATeam(pl, this, "Red", ChatColor.RED, Color.RED));
}
@Override
public Boolean reloadConfig() {
if (_etat != _pregame) {
stop();
}
testConfig();
loadConfig();
return true;
}
@Override
public Boolean loadConfig() {
File fichier_config = new File(_plugin.getDataFolder(), "/arenas/" + _name + ".yml");
YamlConfiguration config = YamlConfiguration.loadConfiguration((File)fichier_config);
ArrayList<Location> s = new ArrayList<>();
for (String spawn : config.getStringList("Spawns_B")) {
s.add(str2loc(spawn));
}
_spawns_B = s;
ArrayList<Location> ss = new ArrayList<>();
for (String spawn2 : config.getStringList("Spawns_R")) {
ss.add(str2loc(spawn2));
}
_spawns_R = ss;
_map = config.getString("Map");
_maxplayer = config.getInt("MaxPlayers");
_minplayer = config.getInt("MinPlayers");
_Active = config.getBoolean("Active");
_NaturalDeath = config.getBoolean("Natural-Death");
_Auto_Respawn = config.getBoolean("Auto-Respawn");
_VIP = config.getBoolean("VIP");
_goal = config.getInt("Goal");
_starting = config.getInt("Time-Before");
_after = config.getLong("Time-After");
_Coins_Win = config.getInt("Coins-per-Win");
_Coins_Kill = config.getInt("Coins-per-Kill");
_VIP_M = config.getDouble("VIP-Multiplicator");
_VIPP_M = config.getDouble("VIP+-Multiplicator");
_Global_Chat = config.getBoolean("Global-Chat");
_Sneak = config.getBoolean("Sneak");
ArrayList<PotionEffect> l = new ArrayList<PotionEffect>();
for (String popo : config.getStringList("Potions")) {
l.add(StrToPo(popo));
}
_potions = l;
_plugin.getLogger().info("load de " + _name);
return true;
}
@Override
public Boolean testConfig() {
YamlConfiguration config = YamlConfiguration.loadConfiguration((File)new File(_plugin.getDataFolder(), "/arenas/" + _name + ".yml"));
setDefaultConfig((FileConfiguration)config, "Version", Quake._version);
setDefaultConfig((FileConfiguration)config, "Name", _name);
setDefaultConfig((FileConfiguration)config, "Type", "Team");
setDefaultConfig((FileConfiguration)config, "Map", "Unknown");
setDefaultConfig((FileConfiguration)config, "Active", true);
setDefaultConfig((FileConfiguration)config, "Natural-Death", false);
setDefaultConfig((FileConfiguration)config, "Auto-Respawn", false);
setDefaultConfig((FileConfiguration)config, "VIP", false);
setDefaultConfig((FileConfiguration)config, "Goal", 25);
setDefaultConfig((FileConfiguration)config, "Time-Before", 30);
setDefaultConfig((FileConfiguration)config, "Time-After", 15);
setDefaultConfig((FileConfiguration)config, "Coins-per-Win", 20);
setDefaultConfig((FileConfiguration)config, "Coins-per-Kill", 1);
setDefaultConfig((FileConfiguration)config, "VIP-Multiplicator", 2);
setDefaultConfig((FileConfiguration)config, "VIP+-Multiplicator", 3);
setDefaultConfig((FileConfiguration)config, "Global-Chat", false);
ArrayList<String> l = new ArrayList<>();
l.add("SPEED:2");
l.add("JUMP:1");
setDefaultConfig((FileConfiguration)config, "Potions", l);
setDefaultConfig((FileConfiguration)config, "MaxPlayers", 11);
setDefaultConfig((FileConfiguration)config, "MinPlayers", 2);
setDefaultConfig((FileConfiguration)config, "Sneak", true);
setDefaultConfig((FileConfiguration)config, "Spawns_B", new ArrayList());
setDefaultConfig((FileConfiguration)config, "Spawns_R", new ArrayList());
try {
config.save(new File(_plugin.getDataFolder(), "/arenas/" + _name + ".yml"));
}
catch (IOException e) {
_plugin.getLogger().warning("save default de " + _name + " impossible !");
disable();
}
return true;
}
@Override
public Boolean saveConfig() {
YamlConfiguration config = YamlConfiguration.loadConfiguration((File)new File(_plugin.getDataFolder(), "/arenas/" + _name + ".yml"));
_plugin.getLogger().info("save de " + _name);
config.set("Version", Quake._version);
config.set("Name", _name);
config.set("Type", "Team");
config.set("Map", _map);
config.set("Active", _Active);
config.set("Natural-Death", _NaturalDeath);
config.set("Auto-Respawn", _Auto_Respawn);
config.set("VIP", _VIP);
config.set("Goal", _goal);
config.set("Time-Before", _starting);
config.set("Time-After", _after);
config.set("Coins-per-Win", _Coins_Win);
config.set("Coins-per-Kill", _Coins_Kill);
config.set("VIP-Multiplicator", _VIP_M);
config.set("VIP+-Multiplicator", _VIPP_M);
config.set("Global-Chat", _Global_Chat);
ArrayList<String> l = new ArrayList<>();
for(PotionEffect popo : _potions) {
l.add(PoToStr(popo));
}
config.set("Potions", l);
config.set("MaxPlayers", _maxplayer);
config.set("MinPlayers", _minplayer);
config.set("Sneak", _Sneak);
ArrayList<String> s = new ArrayList<>();
for(Location loc : _spawns_B) {
s.add(loc2str(loc));
}
config.set("Spawns_B", s);
ArrayList<String> ss = new ArrayList<>();
for(Location loc2 : _spawns_R) {
ss.add(loc2str(loc2));
}
config.set("Spawns_R", ss);
try {
config.save(new File(_plugin.getDataFolder(), "/arenas/" + _name + ".yml"));
_plugin.saveConfig();
} catch (IOException e) {
_plugin.getLogger().warning("save de " + _name + "impossible !");
disable();
return false;
}
return true;
}
@Override
public void joinArena(Player player) {
if (_spawns_B.isEmpty() || _spawns_R.isEmpty()) {
player.sendMessage(_plugin._trad.get("Game.Arena.error.NoSpawn"));
return;
}
if (_etat > _pregame && !Quake.hasPermission(player, "Quake.JoinInGame")) {
player.sendMessage(_plugin._trad.get("Game.Arena.error.inGame"));
return;
}
if (_VIP && !Quake.hasPermission(player, "Quake.VIP")) {
player.sendMessage(_plugin._trad.get("Game.Arena.error.VIP"));
return;
}
if (_full && !Quake.hasPermission(player, "Quake.VIP")) {
player.sendMessage(_plugin._trad.get("Game.Arena.error.full"));
return;
}
if (_players.size() > _maxplayer - 1) {
_full = true;
}
APlayer ap = new APlayer(_plugin, this, player);
_players.put(player.getName(), ap);
addPlayerToTeam(player);
if (_players.size() >= _minplayer && _etat == _pregame) {
startDelayed();
}
if (_etat > _pregame && Quake.hasPermission(player, "Quake.JoinInGame")) {
tp(player);
cleaner(player);
updateScore();
ap.setInvincible(30L);
final Player p = player;
Bukkit.getScheduler().scheduleSyncDelayedTask((Plugin)_plugin, new Runnable() {
@Override
public void run() {
giveStuff(p);
}
}, 20);
Bukkit.getScheduler().scheduleSyncDelayedTask((Plugin)_plugin, new Runnable() {
@Override
public void run() {
giveEffect(p);
giveEffect(p);
}
}, 35);
} else {
tp(player);
cleaner(player);
player.getInventory().setItem(8, getLeaveDoor());
player.getInventory().setHeldItemSlot(0);
try {
player.updateInventory();
}
catch (Exception p) {
// empty catch block
}
}
}
@Override
public void leaveArena(Player player) {
APlayer ap = getAPlayer(player);
TArena.quitcleaner(player);
player.setScoreboard(_scoremanager.getNewScoreboard());
if (!(_Teams.get(0).getSize() > 1 && _Teams.get(1).getSize() > 1 || _stopping || _etat != _ingame)) {
stop();
}
if (_players.size() < _minplayer && !_stopping && _etat <= _starting) {
resetCountdown();
}
if (_plugin._lobby._lobbyspawn != null) {
player.teleport(_plugin._lobby._lobbyspawn);
} else {
Location wo = (Location)_spawns_B.get(0);
if (wo != null) {
player.teleport(wo.getWorld().getSpawnLocation());
}
}
ap.RestoreInventory();
getTeam(player).removePlayer(player);
_players.remove(player.getName());
}
@Override
public void CrashLeaveArena(Player player) {
_players.remove(player.getName());
getTeam(player).removePlayer(player);
if (_players.size() <= 1 && !_stopping && _etat == _ingame) {
stop();
}
if (_players.size() < _minplayer && !_stopping && _etat <= _starting) {
resetCountdown();
}
}
@Override
public void updateScore() {
for (APlayer player2 : _players.values())
_objective.getScore(player2.getName()).setScore(player2._score);
for (ATeam t : _Teams)
_obj_side.getScore(t.getColor() + t.getName()).setScore(t.getScore());
for (APlayer player2 : _players.values())
player2.getPlayer().setScoreboard(_objective.getScoreboard());
}
@Override
public void shotplayer(final Player shooter, Player victim, FireworkEffect effect) {
APlayer ashooter = getAPlayer(shooter);
APlayer avictim = getAPlayer(victim);
if (victim != shooter && !avictim.isInvincible() && !isSameTeam(victim, shooter)) {
Bukkit.getScheduler().scheduleSyncDelayedTask((Plugin)_plugin, new Runnable() {
@Override
public void run() {
getGainKill(shooter);
}
}, 2);
try {
_fw.playFirework(victim.getWorld(), victim.getLocation(), effect);
}
catch (Exception e) {
e.printStackTrace();
}
kill(victim);
broadcast(_plugin._trad.get("Game.Arena.Message.Shot").replace("[SHOOTER]", shooter.getName()).replace("[KILLED]", victim.getName()));
ashooter._score++;
getTeam(ashooter).addScore(1);
if (getTeam(ashooter).getScore() >= _goal) {
Bukkit.getScheduler().scheduleSyncDelayedTask(_plugin, new Runnable() {
@Override
public void run() {
win(getTeam(shooter));
}
}, 2);
}
updateScore();
}
}
@Override
public void resetArena() {
_etat = _pregame;
_full = false;
_players.clear();
for (ATeam at : _Teams) {
at.reset();
}
_stopping = false;
_finished = false;
_compteur = 0;
}
@Override
public void stop() {
_stopping = true;
_plugin.getServer().getScheduler().cancelTask(_timer);
for (APlayer play : _players.values()) {
Player player = play.getPlayer();
getTeam(player).removePlayer(player);
TArena.quitcleaner(player);
player.setScoreboard(_scoremanager.getNewScoreboard());
if(_plugin._lobby._lobbyspawn != null) {
player.teleport(_plugin._lobby._lobbyspawn);
}
play.RestoreInventory();
}
_stopping = false;
resetArena();
}
@Override
public void start() {
_etat = _ingame;
if (_objective != null) {
_objective.unregister();
_objective = null;
}
if (_obj_side != null) {
_obj_side.unregister();
_obj_side = null;
}
for (APlayer aPlayer : _players.values()) {
}
_obj_side = _board.registerNewObjective(String.valueOf(_name) + "_Team", "dummy");
_obj_side.setDisplaySlot(DisplaySlot.SIDEBAR);
_obj_side.setDisplayName("Score");
_objective = _board.registerNewObjective(String.valueOf(_name) + "_Perso", "dummy");
_objective.setDisplaySlot(DisplaySlot.PLAYER_LIST);
_objective.setDisplayName("Score_P");
for(APlayer play : _players.values()) {
Player player = play.getPlayer();
cleaner(player);
giveStuff(player);
tp(player);
giveEffect(player);
}
updateScore();
}
@Override
public void giveStuff(Player player) {
APlayer ap = getAPlayer(player);
ap.getKits();
ap.giveHat();
ap.giveItem();
getTeam(player).giveChestplate(player);
player.getInventory().setItem(8, getLeaveDoor());
player.getInventory().setHeldItemSlot(0);
}
private void addPlayerToTeam(Player p) {
ATeam result = _Teams.get(0);
for (ATeam t : _Teams) {
if (t.getSize() >= result.getSize()) continue;
result = t;
}
result.addPlayer(p);
broadcast(_plugin._trad.get("Game.Arena.Message.Team-Join").replace("[TEAM]", result.getName()).replace("[PLAYER]", p.getName()).replace("[NUMBER]", "" + _players.size()).replace("[MAX]", "" + _maxplayer));
}
public void changeTeam(Player p, String steam) {
ATeam nteam = getTeam(steam);
ATeam oteam = getTeam(p);
if (nteam == null) {
p.sendMessage(_plugin._trad.get("Game.Arena.error.BadTeamName"));
return;
}
if (_etat == _ingame && !Quake.hasPermission(p, "Quake.ChangeTeamInGame")) {
p.sendMessage(_plugin._trad.get("Game.Arena.error.ChangeTeamInGame"));
return;
}
oteam.removePlayer(p);
if (_etat == _ingame) {
kill(p);
}
nteam.addPlayer(p);
p.sendMessage(_plugin._trad.get("Game.Arena.Message.ChangeTeam").replace("[TEAM]", nteam.getColor() + nteam.getName()));
}
public ATeam getTeam(Player p) {
for(ATeam t : _Teams) {
if (!t.hasPlayer(p))
continue;
return t;
}
return _Teams.get(0);
}
public ATeam getTeam(String name) {
for (ATeam t : _Teams) {
if (!t.getName().equalsIgnoreCase(name))
continue;
return t;
}
return null;
}
public ATeam getTeam(APlayer p) {
return getTeam(p.getPlayer());
}
public Boolean isSameTeam(Player p, Player b) {
return getTeam(p).hasPlayer(b);
}
public int addspawn(Location loc, String team) {
if (team.equalsIgnoreCase("Blue")) {
_spawns_B.add(loc);
return _spawns_B.size();
}
if (team.equalsIgnoreCase("Red")) {
_spawns_R.add(loc);
return _spawns_R.size();
}
return 0;
}
public int removespawn(String args, String team) {
if (team.equalsIgnoreCase("Blue")) {
_spawns_B.remove(Integer.parseInt(args));
return _spawns_B.size();
}
if (team.equalsIgnoreCase("Red")) {
_spawns_R.remove(Integer.parseInt(args));
return _spawns_R.size();
}
return 0;
}
public void win(ATeam team) {
_finished = true;
nbroadcast(ChatColor.GOLD + "#" + ChatColor.GRAY + "--------------------" + ChatColor.GOLD + "#");
nbroadcast("" + ChatColor.GRAY);
nbroadcast(_plugin._trad.get("Game.Arena.Message.Team-Won").replace("[TEAM]", team.getName()));
nbroadcast("" + ChatColor.GRAY);
nbroadcast(ChatColor.GOLD + "#" + ChatColor.GRAY + "--------------------" + ChatColor.GOLD + "#");
_plugin.getLogger().log(Level.INFO, _plugin._trad.get("Game.Arena.Message.Won").replace("[TEAM]", team.getName()));
for(String p : team.getPlayers()) {
Player pl = Bukkit.getPlayer(p);
if(pl != null)
win(pl);
}
Bukkit.getScheduler().scheduleSyncDelayedTask((Plugin)_plugin, new Runnable() {
@Override
public void run() {
stop();
}
}, _after * 20);
}
@Override
public void win(final Player player) {
getGainWin(player);
final int nb = (int)((double)_after*1.5);
Bukkit.getScheduler().scheduleSyncDelayedTask(_plugin, new Runnable() {
@Override
public void run() {
if(_compteur <= nb)
Bukkit.getScheduler().scheduleSyncDelayedTask(_plugin, this, 5);
Firework fw = (Firework)player.getWorld().spawnEntity(player.getLocation(), EntityType.FIREWORK);
FireworkMeta fwm = fw.getFireworkMeta();
Random r = new Random();
int rt = r.nextInt(4) + 1;
FireworkEffect.Type type = FireworkEffect.Type.BALL;
if (rt == 1) {
type = FireworkEffect.Type.BALL;
}
if (rt == 2) {
type = FireworkEffect.Type.BALL_LARGE;
}
if (rt == 3) {
type = FireworkEffect.Type.BURST;
}
if (rt == 4) {
type = FireworkEffect.Type.CREEPER;
}
if (rt == 5) {
type = FireworkEffect.Type.STAR;
}
int r1i = r.nextInt(17) + 1;
int r2i = r.nextInt(17) + 1;
Color c1 = getColor(r1i);
Color c2 = getColor(r2i);
FireworkEffect effect = FireworkEffect.builder().flicker(r.nextBoolean()).withColor(c1).withFade(c2).with(type).trail(r.nextBoolean()).build();
fwm.addEffect(effect);
int rp = r.nextInt(2) + 1;
fwm.setPower(rp);
fw.setFireworkMeta(fwm);
_compteur++;
}
}, 5);
}
@Override
public Location getTp(Player player) {
List spawns = new ArrayList();
spawns = getTeam(player).getName().equalsIgnoreCase("Blue") ? _spawns_B : _spawns_R;
int higher = spawns.size() - 1;
if (spawns.size() < 0) {
higher = 0;
}
Random t = new Random();
int random = t.nextInt(higher);
Location loc = (Location)spawns.get(random);
return loc;
}
}

View File

@ -0,0 +1,51 @@
package com.Geekpower14.Quake.Arena;
import com.Geekpower14.Quake.Quake;
import org.bukkit.Sound;
public class Timer implements Runnable {
public Quake _plugin;
public Arena _arena;
public int _finish = 15;
public Timer(Quake pl, Arena aren) {
_plugin = pl;
_arena = aren;
}
@Override
public void run() {
if(_plugin.getServer().getOnlinePlayers().isEmpty())
return;
if(_arena._etat <= _arena._starting && _arena._etat != 0) {
_arena._etat--;
_arena.broadcastXP(_arena._etat);
}
if(_arena._etat == 10)
_arena.broadcast(_plugin._trad.get("Game.Arena.Message.RemainTime").replace("[TIME]", "10"));
if(_arena._etat <= 5 && _arena._etat >= 1) {
_arena.broadcast(_plugin._trad.get("Game.Arena.Message.RemainTime").replace("[TIME]", "" + _arena._etat));
_arena.playsound(Sound.BLOCK_NOTE_PLING, 0.6f, 50.0f);
//_arena.playsound(Sound.NOTE_PLING, 0.6f, 50.0f);
}
if (_arena._etat == 0) {
_arena.playsound(Sound.BLOCK_NOTE_PLING, 9.0f, 1.0f);
_arena.playsound(Sound.BLOCK_NOTE_PLING, 9.0f, 5.0f);
_arena.playsound(Sound.BLOCK_NOTE_PLING, 9.0f, 10.0f);
/*_arena.playsound(Sound.NOTE_PLING, 9.0f, 1.0f);
_arena.playsound(Sound.NOTE_PLING, 9.0f, 5.0f);
_arena.playsound(Sound.NOTE_PLING, 9.0f, 10.0f);*/
_arena.broadcast(_plugin._trad.get("Game.Arena.Message.Start"));
_arena.start();
_arena.nbroadcast("");
_arena.nbroadcast(_plugin._trad.get("Game.Arena.Message.Start-Info"));
}
}
}

View File

@ -0,0 +1,38 @@
package com.Geekpower14.Quake.Commands;
import com.Geekpower14.Quake.Quake;
import org.bukkit.entity.Player;
public class AddLobbyCommand
implements BasicCommand {
private final Quake _plugin;
public AddLobbyCommand(Quake pl) {
_plugin = pl;
}
@Override
public boolean onCommand(Player player, String[] args) {
if (Quake.hasPermission(player, getPermission())) {
_plugin._lobby.addLobby(player);
_plugin._lobby.saveconfig();
} else {
player.sendMessage(_plugin._trad.get("NoPermission"));
}
return true;
}
@Override
public String help(Player p) {
if (Quake.hasPermission(p, getPermission())) {
return "/quake addlobby - Add a sign wall lobby.";
}
return "";
}
@Override
public String getPermission() {
return "Quake.lobby";
}
}

View File

@ -0,0 +1,62 @@
package com.Geekpower14.Quake.Commands;
import com.Geekpower14.Quake.Arena.Arena;
import com.Geekpower14.Quake.Arena.SArena;
import com.Geekpower14.Quake.Arena.TArena;
import com.Geekpower14.Quake.Quake;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
public class AddSpawnCommand implements BasicCommand {
private final Quake _plugin;
public AddSpawnCommand(Quake pl) {
_plugin = pl;
}
@Override
public boolean onCommand(Player player, String[] args) {
if (Quake.hasPermission(player, getPermission())) {
Arena arena = null;
if (_plugin._am.exist(args[0])) {
arena = _plugin._am.getArenabyName(args[0]);
} else if (args[0].matches("^\\d*$")) {
arena = _plugin._am.getArenabyID(Integer.valueOf(args[0]));
}
if (arena == null) {
player.sendMessage(ChatColor.RED + "Please type a good arena name ! !");
return true;
}
if (arena instanceof SArena) {
SArena sa = (SArena)arena;
sa.addspawn(player.getLocation());
player.sendMessage(ChatColor.GREEN + "Spawn number " + (sa._spawns.size() - 1) + " defined !");
} else if (arena instanceof TArena) {
TArena ta = (TArena)arena;
if (args.length >= 2) {
int nb = ta.addspawn(player.getLocation(), args[1]);
player.sendMessage(ChatColor.GREEN + "Spawn number " + (nb - 1) + " defined !");
} else {
player.sendMessage(ChatColor.RED + "Please type a team name ! !");
}
}
arena.saveConfig();
} else {
player.sendMessage(_plugin._trad.get("NoPermission"));
}
return true;
}
@Override
public String help(Player p) {
if(Quake.hasPermission(p, getPermission()))
return "/quake addspawn [Arena] [TEAM|Only for team arena] - Add spawn to an arena.";
return "";
}
@Override
public String getPermission() {
return "Quake.edit";
}
}

View File

@ -0,0 +1,18 @@
/*
* Decompiled with CFR 0_114.
*
* Could not load the following classes:
* org.bukkit.entity.Player
*/
package com.Geekpower14.Quake.Commands;
import org.bukkit.entity.Player;
public interface BasicCommand {
public boolean onCommand(Player var1, String[] var2);
public String help(Player var1);
public String getPermission();
}

View File

@ -0,0 +1,56 @@
package com.Geekpower14.Quake.Commands;
import com.Geekpower14.Quake.Arena.Arena;
import com.Geekpower14.Quake.Arena.SArena;
import com.Geekpower14.Quake.Arena.TArena;
import com.Geekpower14.Quake.Quake;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
public class ChangeTeamCommand implements BasicCommand {
private final Quake _plugin;
public ChangeTeamCommand(Quake pl) {
_plugin = pl;
}
@Override
public boolean onCommand(Player player, String[] args) {
if (Quake.hasPermission(player, getPermission())) {
Arena arena = _plugin._am.getArenabyPlayer(player);
if (arena == null) {
player.sendMessage(_plugin._trad.get("Game.Arena.Message.NotInAGame"));
return true;
}
if (arena instanceof SArena) {
player.sendMessage(_plugin._trad.get("Game.Arena.error.NotInTeamGame"));
return true;
}
if (arena instanceof TArena) {
TArena ta = (TArena)arena;
if (args.length >= 1) {
ta.changeTeam(player, args[0]);
} else {
player.sendMessage(ChatColor.RED + "Please type a team name !");
}
}
} else {
player.sendMessage(_plugin._trad.get("NoPermission"));
}
return true;
}
@Override
public String help(Player p) {
if (Quake.hasPermission(p, getPermission())) {
return "/quake team [Name] - Change your team.";
}
return "";
}
@Override
public String getPermission() {
return "Quake.ChangeTeam";
}
}

View File

@ -0,0 +1,50 @@
package com.Geekpower14.Quake.Commands;
import com.Geekpower14.Quake.Quake;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
public class CreateCommand implements BasicCommand {
private final Quake _plugin;
public CreateCommand(Quake pl) {
_plugin = pl;
}
@Override
public boolean onCommand(Player player, String[] args) {
if (Quake.hasPermission(player, getPermission())) {
if (args.length != 2) {
player.sendMessage(ChatColor.RED + "Please type a name and a type for the arena !");
return true;
}
if (_plugin._am.exist(args[0])) {
player.sendMessage(ChatColor.RED + "Arena " + args[0] + " already exist !");
return true;
}
if (!args[1].equals("Team") && !args[1].equals("Solo")) {
player.sendMessage(ChatColor.RED + "Type " + args[1] + " is not valid (Solo or Team) !");
return true;
}
_plugin._am.createArena(args[0], args[1]);
player.sendMessage(ChatColor.YELLOW + "Arena " + args[0] + " build with success");
} else {
player.sendMessage(_plugin._trad.get("NoPermission"));
}
return true;
}
@Override
public String help(Player p) {
if (Quake.hasPermission(p, getPermission())) {
return "/quake create [Arena name] [Type] - Create an arena.";
}
return "";
}
@Override
public String getPermission() {
return "Quake.edit";
}
}

View File

@ -0,0 +1,56 @@
package com.Geekpower14.Quake.Commands;
import com.Geekpower14.Quake.Arena.Arena;
import com.Geekpower14.Quake.Quake;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
public class JoinCommand implements BasicCommand {
private final Quake _plugin;
public JoinCommand(Quake pl) {
_plugin = pl;
}
@Override
public boolean onCommand(Player player, String[] args) {
if (Quake.hasPermission(player, getPermission())) {
Arena arena = null;
if (_plugin._am.exist(args[0])) {
arena = _plugin._am.getArenabyName(args[0]);
} else if (args[0].matches("^\\d*$")) {
arena = _plugin._am.getArenabyID(Integer.valueOf(args[0]));
}
if (arena == null) {
player.sendMessage(ChatColor.RED + "Please type a good arena name ! !");
return true;
}
if (args.length != 1) {
player.sendMessage(ChatColor.RED + "Please type a number !");
return true;
}
if (arena.isingame(player)) {
player.sendMessage(ChatColor.RED + "You are already in game !");
return true;
}
arena.joinArena(player);
} else {
player.sendMessage(_plugin._trad.get("NoPermission"));
}
return true;
}
@Override
public String help(Player p) {
if (Quake.hasPermission(p, getPermission())) {
return "/quake join [Arena] - Join an arena.";
}
return "";
}
@Override
public String getPermission() {
return "Quake.player";
}
}

View File

@ -0,0 +1,42 @@
package com.Geekpower14.Quake.Commands;
import com.Geekpower14.Quake.Arena.Arena;
import com.Geekpower14.Quake.Quake;
import org.bukkit.entity.Player;
public class LeaveCommand implements BasicCommand {
private final Quake _plugin;
public LeaveCommand(Quake pl) {
_plugin = pl;
}
@Override
public boolean onCommand(Player player, String[] args) {
if (Quake.hasPermission(player, getPermission())) {
Arena arena = _plugin._am.getArenabyPlayer(player);
if (arena == null) {
player.sendMessage(_plugin._trad.get("Game.Arena.Message.NotInAGame"));
return true;
}
arena.leaveArena(player);
} else {
player.sendMessage(_plugin._trad.get("NoPermission"));
}
return false;
}
@Override
public String help(Player p) {
if (Quake.hasPermission(p, getPermission())) {
return "/quake leave - Leave an arena.";
}
return "";
}
@Override
public String getPermission() {
return "Quake.player";
}
}

View File

@ -0,0 +1,84 @@
/*
* Decompiled with CFR 0_114.
*
* Could not load the following classes:
* org.bukkit.Bukkit
* org.bukkit.ChatColor
* org.bukkit.entity.Player
*/
package com.Geekpower14.Quake.Commands;
import com.Geekpower14.Quake.Quake;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
public class MoneyCommand implements BasicCommand {
private final Quake _plugin;
public MoneyCommand(Quake pl) {
_plugin = pl;
}
@Override
public boolean onCommand(Player player, String[] args) {
if (Quake.hasPermission(player, getPermission())) {
int new_ = 0;
if (args.length < 2) {
player.sendMessage(ChatColor.RED + "Please write good command.");
player.sendMessage(help(player));
return true;
}
if (args[0].equalsIgnoreCase("get")) {
Player lol = Bukkit.getPlayer((String)args[1]);
new_ = _plugin._eco.getPlayerMoney(lol);
player.sendMessage(ChatColor.GREEN + lol.getName() + " have " + new_);
return true;
}
if (args.length < 3) {
player.sendMessage(ChatColor.RED + "Please write good command.");
player.sendMessage(help(player));
return true;
}
int amount = Integer.valueOf(args[2]);
if (args[0].equalsIgnoreCase("set")) {
Player lol = Bukkit.getPlayer((String)args[1]);
_plugin._eco.setPlayerMoney(Bukkit.getPlayer((String)args[1]), amount);
new_ = _plugin._eco.getPlayerMoney(lol);
player.sendMessage(ChatColor.GREEN + lol.getName() + " have now " + new_);
return true;
}
if (args[0].equalsIgnoreCase("add")) {
Player lol = Bukkit.getPlayer((String)args[1]);
_plugin._eco.addPlayerMoney(Bukkit.getPlayer((String)args[1]), amount);
new_ = _plugin._eco.getPlayerMoney(lol);
player.sendMessage(ChatColor.GREEN + lol.getName() + " have now " + new_);
return true;
}
if (args[0].equalsIgnoreCase("remove")) {
Player lol = Bukkit.getPlayer((String)args[1]);
_plugin._eco.soustrairePlayerMoney(Bukkit.getPlayer((String)args[1]), amount);
new_ = _plugin._eco.getPlayerMoney(lol);
player.sendMessage(ChatColor.GREEN + lol.getName() + " have now " + new_);
return true;
}
} else {
player.sendMessage(_plugin._trad.get("NoPermission"));
}
return true;
}
@Override
public String help(Player p) {
if (Quake.hasPermission(p, getPermission())) {
return "/quake money [set/add/remove/get] [Player] [Amount] - Set/Add/Remove/Get money of a player.";
}
return "";
}
@Override
public String getPermission() {
return "Quake.edit";
}
}

View File

@ -0,0 +1,99 @@
package com.Geekpower14.Quake.Commands;
import com.Geekpower14.Quake.Quake;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class MyCommandExecutor implements CommandExecutor {
public Quake _plugin;
private final HashMap<String, BasicCommand> _commands = new HashMap<>();
public MyCommandExecutor(Quake pl) {
_plugin = pl;
loadCommands();
}
private void loadCommands() {
_commands.put("leave", new LeaveCommand(_plugin));
_commands.put("addspawn", new AddSpawnCommand(_plugin));
_commands.put("addlobby", new AddLobbyCommand(_plugin));
_commands.put("create", new CreateCommand(_plugin));
_commands.put("setlobbyspawn", new SetLobbySpawnCommand(_plugin));
_commands.put("join", new JoinCommand(_plugin));
_commands.put("removelobby", new RemoveLobbyCommand(_plugin));
_commands.put("removespawn", new RemoveSpawnCommand(_plugin));
_commands.put("save", new SaveCommand(_plugin));
_commands.put("setmap", new SetMapCommand(_plugin));
_commands.put("setmin", new SetMinCommand(_plugin));
_commands.put("setmax", new SetMaxCommand(_plugin));
_commands.put("start", new StartCommand(_plugin));
_commands.put("stop", new StopCommand(_plugin));
_commands.put("shop", new ShopCommand(_plugin));
_commands.put("remove", new RemoveCommand(_plugin));
_commands.put("kill", new UtilsCommand(_plugin, "kill"));
_commands.put("add", new UtilsCommand(_plugin, "add"));
_commands.put("lol", new UtilsCommand(_plugin, "lol"));
_commands.put("reload", new ReloadCommand(_plugin));
_commands.put("team", new ChangeTeamCommand(_plugin));
_commands.put("money", new MoneyCommand(_plugin));
}
@Override
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
Player player = null;
if (!(sender instanceof Player)) {
sender.sendMessage("You need to be a player !");
return true;
}
player = (Player)sender;
if(cmd.getName().equalsIgnoreCase("quake")) {
if(args == null || args.length < 1) {
player.sendMessage(ChatColor.YELLOW + "Plugin By Geekpower14");
player.sendMessage(ChatColor.YELLOW + "Reloaded by Bl4ckSkull666 ( wwww.AMC-Server.de )");
player.sendMessage(ChatColor.YELLOW + "Version: " + _plugin.getDescription().getVersion());
return true;
}
if(args[0].equalsIgnoreCase("help")) {
help(player);
return true;
}
String sub = args[0];
ArrayList<String> l = new ArrayList<>();
l.addAll(Arrays.asList(args));
l.remove(0);
args = l.toArray(new String[0]);
if(!_commands.containsKey(sub)) {
player.sendMessage(ChatColor.RED + "Command dosent exist.");
player.sendMessage(ChatColor.GOLD + "Type /quake help for help");
return true;
}
try {
_commands.get(sub).onCommand(player, args);
} catch(Exception e) {
e.printStackTrace();
player.sendMessage(ChatColor.RED + "An error occured while executing the command. Check the console");
player.sendMessage(ChatColor.BLUE + "Type /quake help for help");
}
return true;
}
return true;
}
public void help(Player p) {
p.sendMessage("/Quake <command> <args>");
for (BasicCommand v : _commands.values()) {
p.sendMessage(ChatColor.GRAY + "- " + v.help(p));
}
}
}

View File

@ -0,0 +1,42 @@
package com.Geekpower14.Quake.Commands;
import com.Geekpower14.Quake.Quake;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
public class ReloadCommand implements BasicCommand {
private final Quake _plugin;
public ReloadCommand(Quake pl) {
_plugin = pl;
}
@Override
public boolean onCommand(Player player, String[] args) {
if (Quake.hasPermission(player, getPermission())) {
_plugin.loadConfig();
_plugin._stuff.reloadConfig();
_plugin._lobby.loadconfig();
_plugin._am.reloadArenas();
_plugin._trad.reloadConfig();
player.sendMessage(ChatColor.GREEN + "Plugin reloaded !");
} else {
player.sendMessage(_plugin._trad.get("NoPermission"));
}
return true;
}
@Override
public String help(Player p) {
if (Quake.hasPermission(p, getPermission())) {
return "/quake reload - Reload config.";
}
return "";
}
@Override
public String getPermission() {
return "Quake.admin";
}
}

View File

@ -0,0 +1,53 @@
package com.Geekpower14.Quake.Commands;
import com.Geekpower14.Quake.Arena.Arena;
import com.Geekpower14.Quake.Quake;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
public class RemoveCommand implements BasicCommand {
private final Quake _plugin;
public RemoveCommand(Quake pl) {
_plugin = pl;
}
@Override
public boolean onCommand(Player player, String[] args) {
if (Quake.hasPermission(player, getPermission())) {
Arena arena = null;
if (_plugin._am.exist(args[0])) {
arena = _plugin._am.getArenabyName(args[0]);
} else if (args[0].matches("^\\d*$")) {
arena = _plugin._am.getArenabyID(Integer.valueOf(args[0]));
}
if (arena == null) {
player.sendMessage(ChatColor.RED + "Please type a good arena name ! !");
return true;
}
if (args.length != 1) {
player.sendMessage(ChatColor.RED + "Please type a number !");
return true;
}
_plugin._am.deleteArena(arena._name);
player.sendMessage(ChatColor.GREEN + "Arena deleted with success !");
} else {
player.sendMessage(_plugin._trad.get("NoPermission"));
}
return true;
}
@Override
public String help(Player p) {
if (Quake.hasPermission(p, getPermission())) {
return "/quake remove [Arena name] - Remove an arena.";
}
return "";
}
@Override
public String getPermission() {
return "Quake.edit";
}
}

View File

@ -0,0 +1,51 @@
/*
* Decompiled with CFR 0_114.
*
* Could not load the following classes:
* org.bukkit.ChatColor
* org.bukkit.entity.Player
*/
package com.Geekpower14.Quake.Commands;
import com.Geekpower14.Quake.Quake;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
public class RemoveLobbyCommand implements BasicCommand {
private final Quake _plugin;
public RemoveLobbyCommand(Quake pl) {
_plugin = pl;
}
@Override
public boolean onCommand(Player player, String[] args) {
if (Quake.hasPermission(player, getPermission())) {
if (args.length != 1) {
player.sendMessage(ChatColor.RED + "Please type a good number of lobby !");
return true;
}
int lobby = Integer.valueOf(args[0]);
_plugin._lobby.removeLobby("lobby" + (lobby - 1));
player.sendMessage(ChatColor.YELLOW + "Lobby number : " + (lobby - 1) + " removed with success");
_plugin._lobby.saveconfig();
} else {
player.sendMessage(_plugin._trad.get("NoPermission"));
}
return true;
}
@Override
public String help(Player p) {
if (Quake.hasPermission(p, getPermission())) {
return "/quake removelobby [ID of the lobby] - Remove a lobby wall.";
}
return "";
}
@Override
public String getPermission() {
return "Quake.lobby";
}
}

View File

@ -0,0 +1,67 @@
package com.Geekpower14.Quake.Commands;
import com.Geekpower14.Quake.Arena.Arena;
import com.Geekpower14.Quake.Arena.SArena;
import com.Geekpower14.Quake.Arena.TArena;
import com.Geekpower14.Quake.Quake;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
public class RemoveSpawnCommand implements BasicCommand {
private final Quake _plugin;
public RemoveSpawnCommand(Quake pl) {
_plugin = pl;
}
@Override
public boolean onCommand(Player player, String[] args) {
if (Quake.hasPermission(player, getPermission())) {
Arena arena = null;
if (_plugin._am.exist(args[0])) {
arena = _plugin._am.getArenabyName(args[0]);
} else if (args[0].matches("^\\d*$")) {
arena = _plugin._am.getArenabyID(Integer.valueOf(args[0]));
}
if (arena == null) {
player.sendMessage(ChatColor.RED + "Please type a good arena name ! !");
return true;
}
if (args.length != 2) {
player.sendMessage(ChatColor.RED + "Please type a number !");
return true;
}
if (arena instanceof SArena) {
SArena sa = (SArena)arena;
sa.removespawn(args[1]);
player.sendMessage(ChatColor.GREEN + "Spawn number " + (sa._spawns.size() - 1) + " removed !");
} else if (arena instanceof TArena) {
TArena ta = (TArena)arena;
if (args.length >= 3) {
int nb = ta.removespawn(args[1], args[2]);
player.sendMessage(ChatColor.GREEN + "Spawn number " + (nb - 1) + " removed !");
} else {
player.sendMessage(ChatColor.RED + "Please type a team name ! !");
}
}
arena.saveConfig();
} else {
player.sendMessage(_plugin._trad.get("NoPermission"));
}
return true;
}
@Override
public String help(Player p) {
if (Quake.hasPermission(p, getPermission())) {
return "/quake removespawn [Arena] [Number] - Remove a spawn of the arena.";
}
return "";
}
@Override
public String getPermission() {
return "Quake.edit";
}
}

View File

@ -0,0 +1,56 @@
/*
* Decompiled with CFR 0_114.
*
* Could not load the following classes:
* org.bukkit.ChatColor
* org.bukkit.entity.Player
*/
package com.Geekpower14.Quake.Commands;
import com.Geekpower14.Quake.Arena.Arena;
import com.Geekpower14.Quake.Quake;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
public class SaveCommand implements BasicCommand {
private final Quake _plugin;
public SaveCommand(Quake pl) {
_plugin = pl;
}
@Override
public boolean onCommand(Player player, String[] args) {
if (Quake.hasPermission(player, getPermission())) {
Arena arena = null;
if (_plugin._am.exist(args[0])) {
arena = _plugin._am.getArenabyName(args[0]);
} else if (args[0].matches("^\\d*$")) {
arena = _plugin._am.getArenabyID(Integer.parseInt(args[0]));
}
if (arena == null) {
player.sendMessage(ChatColor.RED + "Please type a good arena name ! !");
return true;
}
arena.saveConfig();
player.sendMessage(ChatColor.GREEN + "Config saved for the arena : " + args[0]);
} else {
player.sendMessage(_plugin._trad.get("NoPermission"));
}
return true;
}
@Override
public String help(Player p) {
if (Quake.hasPermission(p, getPermission())) {
return "/quake save [Arena] - Save config of the arena.";
}
return "";
}
@Override
public String getPermission() {
return "Quake.edit";
}
}

View File

@ -0,0 +1,46 @@
/*
* Decompiled with CFR 0_114.
*
* Could not load the following classes:
* org.bukkit.ChatColor
* org.bukkit.entity.Player
*/
package com.Geekpower14.Quake.Commands;
import com.Geekpower14.Quake.Quake;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
public class SetLobbySpawnCommand implements BasicCommand {
private Quake _plugin;
public SetLobbySpawnCommand(Quake pl) {
_plugin = pl;
}
@Override
public boolean onCommand(Player player, String[] args) {
if (Quake.hasPermission(player, getPermission())) {
_plugin._lobby.setspawn(player);
player.sendMessage(ChatColor.YELLOW + "Lobby's spawn define with success !");
_plugin._lobby.saveconfig();
} else {
player.sendMessage(_plugin._trad.get("NoPermission"));
}
return true;
}
@Override
public String help(Player p) {
if (Quake.hasPermission(p, getPermission())) {
return "/quake setlobbyspawn - Set the spawn of the lobby.";
}
return "";
}
@Override
public String getPermission() {
return "Quake.lobby";
}
}

View File

@ -0,0 +1,61 @@
/*
* Decompiled with CFR 0_114.
*
* Could not load the following classes:
* org.bukkit.ChatColor
* org.bukkit.entity.Player
*/
package com.Geekpower14.Quake.Commands;
import com.Geekpower14.Quake.Arena.Arena;
import com.Geekpower14.Quake.Quake;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
public class SetMapCommand implements BasicCommand {
private final Quake _plugin;
public SetMapCommand(Quake pl) {
_plugin = pl;
}
@Override
public boolean onCommand(Player player, String[] args) {
if (Quake.hasPermission(player, getPermission())) {
Arena arena = null;
if (_plugin._am.exist(args[0])) {
arena = _plugin._am.getArenabyName(args[0]);
} else if (args[0].matches("^\\d*$")) {
arena = _plugin._am.getArenabyID(Integer.parseInt(args[0]));
}
if (arena == null) {
player.sendMessage(ChatColor.RED + "Please type a good arena name ! !");
return true;
}
if (args.length < 2) {
player.sendMessage(ChatColor.RED + "Please type a name !");
return true;
}
arena.setmap(args[1]);
arena.saveConfig();
player.sendMessage(ChatColor.GREEN + "Set the map with success !");
} else {
player.sendMessage(_plugin._trad.get("NoPermission"));
}
return true;
}
@Override
public String help(Player p) {
if (Quake.hasPermission(p, getPermission())) {
return "/quake setmap [Arena] [Name] - Set display name in the lobby.";
}
return "";
}
@Override
public String getPermission() {
return "Quake.edit";
}
}

View File

@ -0,0 +1,61 @@
/*
* Decompiled with CFR 0_114.
*
* Could not load the following classes:
* org.bukkit.ChatColor
* org.bukkit.entity.Player
*/
package com.Geekpower14.Quake.Commands;
import com.Geekpower14.Quake.Arena.Arena;
import com.Geekpower14.Quake.Quake;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
public class SetMaxCommand implements BasicCommand {
private final Quake _plugin;
public SetMaxCommand(Quake pl) {
_plugin = pl;
}
@Override
public boolean onCommand(Player player, String[] args) {
if (Quake.hasPermission(player, getPermission())) {
Arena arena = null;
if (_plugin._am.exist(args[0])) {
arena = _plugin._am.getArenabyName(args[0]);
} else if (args[0].matches("^\\d*$")) {
arena = _plugin._am.getArenabyID(Integer.parseInt(args[0]));
}
if (arena == null) {
player.sendMessage(ChatColor.RED + "Please type a good arena name ! !");
return true;
}
if (args.length < 2) {
player.sendMessage(ChatColor.RED + "Please type a number !");
return true;
}
arena.setmax(Integer.parseInt(args[1]));
arena.saveConfig();
player.sendMessage(ChatColor.GREEN + "Set the max player with success !");
} else {
player.sendMessage(_plugin._trad.get("NoPermission"));
}
return true;
}
@Override
public String help(Player p) {
if (Quake.hasPermission(p, getPermission())) {
return "/quake setmax [Arena] [Number] - Set max player in the arena.";
}
return "";
}
@Override
public String getPermission() {
return "Quake.edit";
}
}

View File

@ -0,0 +1,61 @@
/*
* Decompiled with CFR 0_114.
*
* Could not load the following classes:
* org.bukkit.ChatColor
* org.bukkit.entity.Player
*/
package com.Geekpower14.Quake.Commands;
import com.Geekpower14.Quake.Arena.Arena;
import com.Geekpower14.Quake.Quake;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
public class SetMinCommand implements BasicCommand {
private final Quake _plugin;
public SetMinCommand(Quake pl) {
_plugin = pl;
}
@Override
public boolean onCommand(Player player, String[] args) {
if (Quake.hasPermission(player, getPermission())) {
Arena arena = null;
if (_plugin._am.exist(args[0])) {
arena = _plugin._am.getArenabyName(args[0]);
} else if (args[0].matches("^\\d*$")) {
arena = _plugin._am.getArenabyID(Integer.valueOf(args[0]));
}
if (arena == null) {
player.sendMessage(ChatColor.RED + "Please type a good arena name ! !");
return true;
}
if (args.length < 2) {
player.sendMessage(ChatColor.RED + "Please type a number !");
return true;
}
arena.setmin(Integer.parseInt(args[1]));
arena.saveConfig();
player.sendMessage(ChatColor.GREEN + "Set the minimum player with success !");
} else {
player.sendMessage(_plugin._trad.get("NoPermission"));
}
return true;
}
@Override
public String help(Player p) {
if (Quake.hasPermission(p, getPermission())) {
return "/quake setmin [Arena] [Number] - Set minimum player in the arena.";
}
return "";
}
@Override
public String getPermission() {
return "Quake.edit";
}
}

View File

@ -0,0 +1,43 @@
/*
* Decompiled with CFR 0_114.
*
* Could not load the following classes:
* org.bukkit.entity.Player
*/
package com.Geekpower14.Quake.Commands;
import com.Geekpower14.Quake.Quake;
import org.bukkit.entity.Player;
public class ShopCommand implements BasicCommand {
private final Quake _plugin;
public ShopCommand(Quake pl) {
_plugin = pl;
}
@Override
public boolean onCommand(Player player, String[] args) {
if (Quake.hasPermission(player, getPermission())) {
_plugin._shop.getMainShop(player);
_plugin._imm.show(player);
} else {
player.sendMessage(_plugin._trad.get("NoPermission"));
}
return false;
}
@Override
public String help(Player p) {
if (Quake.hasPermission(p, getPermission())) {
return "/quake shop - Open the shop.";
}
return "";
}
@Override
public String getPermission() {
return "Quake.player";
}
}

View File

@ -0,0 +1,56 @@
/*
* Decompiled with CFR 0_114.
*
* Could not load the following classes:
* org.bukkit.ChatColor
* org.bukkit.entity.Player
*/
package com.Geekpower14.Quake.Commands;
import com.Geekpower14.Quake.Arena.Arena;
import com.Geekpower14.Quake.Quake;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
public class StartCommand implements BasicCommand {
private final Quake _plugin;
public StartCommand(Quake pl) {
_plugin = pl;
}
@Override
public boolean onCommand(Player player, String[] args) {
if(Quake.hasPermission(player, getPermission())) {
Arena arena = null;
if (_plugin._am.exist(args[0])) {
arena = _plugin._am.getArenabyName(args[0]);
} else if (args[0].matches("^\\d*$")) {
arena = _plugin._am.getArenabyID(Integer.parseInt(args[0]));
}
if (arena == null) {
player.sendMessage(ChatColor.RED + "Please type a good arena name ! !");
return true;
}
arena.start();
player.sendMessage(ChatColor.GREEN + "Force beginning for the arena : " + args[0]);
} else {
player.sendMessage(_plugin._trad.get("NoPermission"));
}
return true;
}
@Override
public String help(Player p) {
if (Quake.hasPermission(p, getPermission())) {
return "/quake start [Arena] - Force start an arena.";
}
return "";
}
@Override
public String getPermission() {
return "Quake.modo";
}
}

View File

@ -0,0 +1,56 @@
/*
* Decompiled with CFR 0_114.
*
* Could not load the following classes:
* org.bukkit.ChatColor
* org.bukkit.entity.Player
*/
package com.Geekpower14.Quake.Commands;
import com.Geekpower14.Quake.Arena.Arena;
import com.Geekpower14.Quake.Quake;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
public class StopCommand implements BasicCommand {
private final Quake _plugin;
public StopCommand(Quake pl) {
_plugin = pl;
}
@Override
public boolean onCommand(Player player, String[] args) {
if (Quake.hasPermission(player, getPermission())) {
Arena arena = null;
if (_plugin._am.exist(args[0])) {
arena = _plugin._am.getArenabyName(args[0]);
} else if (args[0].matches("^\\d*$")) {
arena = _plugin._am.getArenabyID(Integer.parseInt(args[0]));
}
if (arena == null) {
player.sendMessage(ChatColor.RED + "Please type a good arena name ! !");
return true;
}
arena.stop();
player.sendMessage(ChatColor.RED + "Force stop for the arena : " + args[0]);
} else {
player.sendMessage(_plugin._trad.get("NoPermission"));
}
return true;
}
@Override
public String help(Player p) {
if (Quake.hasPermission(p, getPermission())) {
return "/quake stop [Arena] - Force stop an arena.";
}
return "";
}
@Override
public String getPermission() {
return "Quake.modo";
}
}

View File

@ -0,0 +1,54 @@
/*
* Decompiled with CFR 0_114.
*
* Could not load the following classes:
* org.bukkit.entity.Player
*/
package com.Geekpower14.Quake.Commands;
import com.Geekpower14.Quake.Arena.APlayer;
import com.Geekpower14.Quake.Arena.Arena;
import com.Geekpower14.Quake.Quake;
import org.bukkit.entity.Player;
public class UtilsCommand implements BasicCommand {
private final Quake _plugin;
private String _cmd;
public UtilsCommand(Quake pl, String cmd) {
_plugin = pl;
_cmd = cmd;
}
@Override
public boolean onCommand(Player player, String[] args) {
if (Quake.hasPermission(player, getPermission())) {
if (_cmd.equals("kill")) {
player.setHealth(0.0);
}
if (_cmd.equals("add")) {
Arena aren = _plugin._am.getArenabyPlayer(player);
APlayer ap = aren.getAPlayer(player);
ap._score++;
aren.updateScore();
}
} else {
player.sendMessage(_plugin._trad.get("NoPermission"));
}
return false;
}
@Override
public String help(Player p) {
if(Quake.hasPermission(p, getPermission())) {
return "/quake " + _cmd + " - Do something.";
}
return "";
}
@Override
public String getPermission() {
return "Quake.admin";
}
}

View File

@ -0,0 +1,139 @@
package com.Geekpower14.Quake.Eco;
import com.Geekpower14.Quake.Quake;
import com.Geekpower14.Quake.Trans.Score;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import net.milkbowl.vault.economy.Economy;
import org.bukkit.ChatColor;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.plugin.RegisteredServiceProvider;
public class EcoManager {
private Quake _plugin;
public static Economy _economy = null;
public Boolean _useVault = false;
public EcoManager(Quake pl) {
_plugin = pl;
_useVault = _plugin._useVault;
if(_useVault) {
try {
setupEconomy();
} catch (Exception var2_2) {
// empty catch block
}
}
}
private boolean setupEconomy() {
RegisteredServiceProvider economyProvider = _plugin.getServer().getServicesManager().getRegistration((Class)Economy.class);
if(economyProvider != null)
_economy = (Economy)economyProvider.getProvider();
return _economy != null;
}
public int getPlayerMoney(Player player) {
int Money = 0;
if (_useVault) {
Money = (int)_economy.getBalance(player);
} else {
YamlConfiguration config = YamlConfiguration.loadConfiguration(new File(_plugin.getDataFolder(), "/Eco/" + player.getName() + ".yml"));
Money = config.getInt("Money");
}
return Money;
}
public void setPlayerMoney(Player player, int money) {
if(_useVault) {
Economy eco = _economy;
if(getPlayerMoney(player) == money) {
return;
}
if (getPlayerMoney(player) < money) {
eco.depositPlayer(player, (double)(money - getPlayerMoney(player)));
return;
}
if (getPlayerMoney(player) > money) {
eco.withdrawPlayer(player, (double)(getPlayerMoney(player) - money));
return;
}
} else {
YamlConfiguration config = YamlConfiguration.loadConfiguration((File)new File(_plugin.getDataFolder(), "/Eco/" + player.getName() + ".yml"));
config.set("Name", player.getName());
config.set("Money", money);
try {
config.save(new File(_plugin.getDataFolder(), "/Eco/" + player.getName() + ".yml"));
}
catch (IOException e) {
e.printStackTrace();
}
}
}
public void soustrairePlayerMoney(Player player, int price) {
int coins = getPlayerMoney(player);
setPlayerMoney(player, coins -= price);
}
public void addPlayerMoney(Player player, int price) {
int coins = getPlayerMoney(player);
setPlayerMoney(player, coins += price);
}
public boolean has(Player player, int price) {
int account = getPlayerMoney(player);
if(account >= price) {
return true;
}
return false;
}
public int getScore(Player p, Score.Type type) {
YamlConfiguration config = YamlConfiguration.loadConfiguration((File)new File(_plugin.getDataFolder(), "/Eco/" + p.getName() + ".yml"));
return config.getInt(type.toString());
}
public void setScore(Player p, Score.Type type, int score) {
YamlConfiguration config = YamlConfiguration.loadConfiguration((File)new File(_plugin.getDataFolder(), "/Eco/" + p.getName() + ".yml"));
config.set("Name", p.getName());
config.set(type.toString(), score);
try {
config.save(new File(_plugin.getDataFolder(), "/Eco/" + p.getName() + ".yml"));
} catch (IOException e) {
e.printStackTrace();
}
}
public void addScore(Player p, Score.Type type, int score) {
int k = getScore(p, type);
setScore(p, type, k += score);
}
public void subtractScore(Player p, Score.Type type, int score) {
int k = getScore(p, type);
setScore(p, type, k -= score);
}
public void convertToUUID() {
File folder = new File(_plugin.getDataFolder(), "/eco/");
if (!folder.exists()) {
folder.mkdir();
}
ArrayList<String> Maps = new ArrayList<>();
for(File f: folder.listFiles()) {
String MapName = f.getName();
String name = f.getName().replaceAll(".yml", "");
Maps.add(name);
_plugin.getLogger().info("Found arena : " + name);
}
if(Maps.isEmpty())
_plugin.getLogger().info(ChatColor.RED + "No Arena found in folder ");
}
}

View File

@ -0,0 +1,388 @@
package com.Geekpower14.Quake.Listener;
import com.Geekpower14.Quake.Arena.APlayer;
import com.Geekpower14.Quake.Arena.Arena;
import com.Geekpower14.Quake.Quake;
import com.Geekpower14.Quake.Utils.FireworkEffectPlayer;
import com.Geekpower14.Quake.Utils.ScoreB;
import java.io.File;
//1.8.8
//import net.minecraft.server.v1_8_R3.PacketPlayInClientCommand;
//import net.minecraft.server.v1_8_R3.PacketPlayInClientCommand.EnumClientCommand;
//1.9.2
//import net.minecraft.server.v1_9_R1.PacketPlayInClientCommand;
//import net.minecraft.server.v1_9_R1.PacketPlayInClientCommand.EnumClientCommand;
//1.9.4
//import net.minecraft.server.v1_9_R2.PacketPlayInClientCommand;
//import net.minecraft.server.v1_9_R2.PacketPlayInClientCommand.EnumClientCommand;
//1.10
import net.minecraft.server.v1_10_R1.PacketPlayInClientCommand;
import net.minecraft.server.v1_10_R1.PacketPlayInClientCommand.EnumClientCommand;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Color;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.Sign;
//1.8.8
//import org.bukkit.craftbukkit.v1_8_R3.entity.CraftPlayer;
//1.9.2
//import org.bukkit.craftbukkit.v1_9_R1.entity.CraftPlayer;
//1.9.4
//import org.bukkit.craftbukkit.v1_9_R2.entity.CraftPlayer;
//1.10
import org.bukkit.craftbukkit.v1_10_R1.entity.CraftPlayer;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.FoodLevelChangeEvent;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.event.player.PlayerDropItemEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.player.PlayerRespawnEvent;
import org.bukkit.event.player.PlayerTeleportEvent;
import org.bukkit.event.player.PlayerToggleSneakEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.Plugin;
public class PlayerListener implements Listener {
Quake _plugin;
FireworkEffectPlayer _fw;
public PlayerListener(Quake pl) {
_plugin = pl;
_fw = new FireworkEffectPlayer(_plugin);
}
@EventHandler(priority=EventPriority.HIGHEST)
public void onPlayerInteract(PlayerInteractEvent event) {
Player player = event.getPlayer();
Action action = event.getAction();
ItemStack hand = player.getItemInHand();
Arena arena = _plugin._am.getArenabyPlayer(player);
if (arena == null) {
Block block;
if ((action == Action.LEFT_CLICK_BLOCK || action == Action.RIGHT_CLICK_BLOCK) && _plugin._lobby.isinLobby(event.getClickedBlock().getLocation()) && (block = event.getClickedBlock()).getState() instanceof Sign) {
Sign sign = (Sign)block.getState();
if (sign.getLine(1).equals("")) {
return;
}
Arena aren = _plugin._am.getArenabyID(Integer.valueOf(sign.getLine(1).replace("T-", "").replace("S-", "")));
if (aren == null) {
return;
}
aren.joinArena(player);
event.setCancelled(true);
return;
}
if (event.getItem() != null && event.getItem().getType().equals(_plugin._shopId) && _plugin._shopWorlds.contains(event.getPlayer().getWorld().getName()) && Quake.hasPermission(player, "Quake.Shop")) {
_plugin._shop.getMainShop(player);
_plugin._imm.show(player);
event.setCancelled(true);
}
return;
}
APlayer ap = arena.getAPlayer(player);
if (hand != null && hand.getType() == Material.WOOD_DOOR) {
arena.leaveArena(player);
}
}
public float getincr(Long time) {
float result = 0.0f;
float temp = time;
result = 100.0f / (temp / 2.0f) / 100.0f;
return result;
}
@EventHandler(priority=EventPriority.HIGHEST)
public void onPlayerSneak(PlayerToggleSneakEvent event) {
Player p = event.getPlayer();
Arena arena = _plugin._am.getArenabyPlayer(p);
if (arena == null) {
return;
}
if(arena._Sneak) {
event.setCancelled(true);
}
}
@EventHandler(priority=EventPriority.HIGHEST)
public void onPlayerFellOutOfWorld(PlayerMoveEvent event) {
Player p = event.getPlayer();
Arena arena = _plugin._am.getArenabyPlayer(p);
if(arena == null)
return;
if(p.getLocation().getY() <= 0.0) {
p.teleport(arena.getTp(p));
arena.broadcast(_plugin._trad.get("Game.Arena.Message.Void").replace("[KILLED]", p.getName()));
arena.kill(p);
return;
}
}
public void giveScoreBoard(Player p) {
if (_plugin._scores.containsKey(p.getName())) {
_plugin._scores.get(p.getName()).updateScore();
} else {
_plugin._scores.put(p.getName(), new ScoreB(_plugin, p));
}
}
public Boolean isScoreWorld(String name) {
if (_plugin._ScoreWorlds.contains(name)) {
return true;
}
return false;
}
private Color getColor(int i) {
Color c = null;
if (i == 1) {
c = Color.AQUA;
}
if (i == 2) {
c = Color.BLACK;
}
if (i == 3) {
c = Color.BLUE;
}
if (i == 4) {
c = Color.FUCHSIA;
}
if (i == 5) {
c = Color.GRAY;
}
if (i == 6) {
c = Color.GREEN;
}
if (i == 7) {
c = Color.LIME;
}
if (i == 8) {
c = Color.MAROON;
}
if (i == 9) {
c = Color.NAVY;
}
if (i == 10) {
c = Color.OLIVE;
}
if (i == 11) {
c = Color.ORANGE;
}
if (i == 12) {
c = Color.PURPLE;
}
if (i == 13) {
c = Color.RED;
}
if (i == 14) {
c = Color.SILVER;
}
if (i == 15) {
c = Color.TEAL;
}
if (i == 16) {
c = Color.WHITE;
}
if (i == 17) {
c = Color.YELLOW;
}
return c;
}
@EventHandler(priority=EventPriority.HIGHEST)
public void onEntityDamaged(EntityDamageEvent event) {
if (!(event.getEntity() instanceof Player)) {
return;
}
Player p = (Player)event.getEntity();
Arena arena = _plugin._am.getArenabyPlayer(p);
if (arena == null) {
return;
}
if (arena._NaturalDeath && arena._etat == arena._ingame) {
if (event.getCause() == EntityDamageEvent.DamageCause.FALL) {
event.setCancelled(true);
}
} else {
event.setCancelled(true);
}
}
@EventHandler(priority=EventPriority.HIGHEST)
public void onPlayerCommand(PlayerCommandPreprocessEvent event) {
Player player = event.getPlayer();
Arena arena = _plugin._am.getArenabyPlayer(player);
if (arena == null) {
return;
}
if (event.getMessage().startsWith("/")) {
if (player.isOp()) {
return;
}
if (event.getMessage().startsWith("/quake")) {
return;
}
if (event.getMessage().startsWith("/q")) {
return;
}
player.sendMessage(_plugin._trad.get("Game.Arena.error.command"));
event.setCancelled(true);
} else if (!arena._Global_Chat) {
event.setCancelled(true);
arena.chat(player.getDisplayName() + ChatColor.GRAY + ": " + event.getMessage());
}
}
@EventHandler(priority=EventPriority.HIGHEST)
public void onPlayerTeleport(PlayerTeleportEvent event) {
Player p = event.getPlayer();
if (isScoreWorld(event.getFrom().getWorld().getName()) && !isScoreWorld(event.getTo().getWorld().getName())) {
p.setScoreboard(Bukkit.getScoreboardManager().getNewScoreboard());
return;
}
if (!isScoreWorld(event.getFrom().getWorld().getName()) && isScoreWorld(event.getTo().getWorld().getName())) {
if (_plugin._scores.containsKey(p.getName())) {
p.setScoreboard(_plugin._scores.get(p.getName()).getScoreBoard());
} else {
_plugin._scores.put(p.getName(), new ScoreB(_plugin, p));
}
return;
}
}
@EventHandler(priority=EventPriority.HIGHEST)
public void onPlayerChat(AsyncPlayerChatEvent event) {
Player player = event.getPlayer();
Arena arena = _plugin._am.getArenabyPlayer(player);
if (arena == null) {
return;
}
if (!arena._Global_Chat) {
event.setCancelled(true);
arena.chat(player.getDisplayName() + ChatColor.GRAY + ": " + event.getMessage());
}
}
@EventHandler(priority=EventPriority.HIGHEST)
public void onPlayerDeath(PlayerDeathEvent event) {
final Player player = event.getEntity();
final Arena arena = _plugin._am.getArenabyPlayer(event.getEntity());
if (arena == null) {
return;
}
APlayer ap = arena.getAPlayer(player);
ap.setinvincible(true);
ap.setReloading(false);
event.setDeathMessage("");
event.getDrops().clear();
event.setDroppedExp(0);
_plugin.getServer().getScheduler().scheduleSyncDelayedTask(_plugin, new Runnable() {
@Override
public void run() {
arena.getScoreDeath(player);
}
});
if(arena._Auto_Respawn) {
_plugin.getServer().getScheduler().scheduleSyncDelayedTask(_plugin, new Runnable() {
@Override
public void run() {
try {
if(Quake.getPlugin().getConfig().getInt("mc-version", 1002) >= 1000 && Quake.getPlugin().getConfig().getInt("mc-version", 1002) <= 1002)
((CraftPlayer)player).getHandle().playerConnection.a(new PacketPlayInClientCommand(EnumClientCommand.PERFORM_RESPAWN));
} catch (SecurityException | IllegalArgumentException t) {
t.printStackTrace();
}
}
}, 20L);
}
}
@EventHandler(priority=EventPriority.HIGHEST)
public void onPlayerRespawn(PlayerRespawnEvent event) {
final Arena arena = _plugin._am.getArenabyPlayer(event.getPlayer());
if (arena == null) {
return;
}
final Player player = event.getPlayer();
APlayer ap = arena.getAPlayer(player);
arena.giveStuff(player);
event.setRespawnLocation(arena.getTp(event.getPlayer()));
ap.setInvincible(50L);
Bukkit.getScheduler().scheduleSyncDelayedTask((Plugin)_plugin, new Runnable() {
@Override
public void run() {
arena.giveEffect(player);
}
}, 10);
}
@EventHandler(priority=EventPriority.HIGHEST)
public void onPlayerDrop(PlayerDropItemEvent event) {
Arena arena = _plugin._am.getArenabyPlayer(event.getPlayer());
if (arena == null) {
return;
}
event.setCancelled(true);
}
@EventHandler(priority=EventPriority.HIGHEST)
public void onPlayerFood(FoodLevelChangeEvent event) {
if (event.getEntity() instanceof Player) {
Arena arena = _plugin._am.getArenabyPlayer((Player)event.getEntity());
if (arena == null) {
return;
}
event.setCancelled(true);
}
}
@EventHandler(priority=EventPriority.HIGHEST)
public void onPlayerQuit(PlayerQuitEvent event) {
Arena arena = _plugin._am.getArenabyPlayer(event.getPlayer());
Player player = event.getPlayer();
_plugin._scores.remove(player.getName());
if (arena == null) {
return;
}
_plugin.getLogger().warning("Player : " + player.getName() + " Rage Quit !");
arena.CrashLeaveArena(event.getPlayer());
}
@EventHandler(priority=EventPriority.HIGHEST)
public void onPlayerLogin(PlayerJoinEvent event) {
Arena arena;
final Player player = event.getPlayer();
File f = new File(Quake.getPlugin().getDataFolder() + "/Save_Players/" + player.getName() + ".yml");
if (f.exists()) {
player.teleport(_plugin._lobby._lobbyspawn);
Bukkit.getScheduler().scheduleSyncDelayedTask((Plugin)_plugin, new Runnable(){
@Override
public void run() {
player.teleport(Quake.getPlugin()._lobby._lobbyspawn);
}
}, 30);
_plugin.getLogger().warning("Player : " + player.getName() + " rejoin after Rage Quit !");
Arena.RejoinAfterCrash(player);
}
if ((arena = _plugin._am.getArenabyPlayer(event.getPlayer())) != null) {
arena.leaveArena(event.getPlayer());
}
}
}

View File

@ -0,0 +1,33 @@
/*
* Decompiled with CFR 0_114.
*
* Could not load the following classes:
* org.bukkit.World
* org.bukkit.event.EventHandler
* org.bukkit.event.Listener
* org.bukkit.event.weather.WeatherChangeEvent
*/
package com.Geekpower14.Quake.Listener;
import com.Geekpower14.Quake.Quake;
import org.bukkit.World;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.weather.WeatherChangeEvent;
public class Weather implements Listener {
public final Quake _plugin;
public Weather(Quake pl) {
_plugin = pl;
}
@EventHandler
public void onWeatherChange(WeatherChangeEvent event) {
World w = event.getWorld();
if(_plugin._am.isArenaWorld(w) && event.toWeatherState()) {
event.setCancelled(true);
}
}
}

View File

@ -0,0 +1,24 @@
/*
* Decompiled with CFR 0_114.
*/
package com.Geekpower14.Quake.Lobby;
import com.Geekpower14.Quake.Arena.Arena;
import com.Geekpower14.Quake.Quake;
import com.Geekpower14.Quake.Utils.Area;
import java.util.ArrayList;
import java.util.List;
public class Lobby {
public final Quake _plugin;
public final List<Lobby_Sign> _LOBBYS_SIGN = new ArrayList<>();
public Lobby(Quake pl, Area area) {
_plugin = pl;
}
public Boolean init(List<Arena> arena) {
return true;
}
}

View File

@ -0,0 +1,273 @@
package com.Geekpower14.Quake.Lobby;
import com.Geekpower14.Quake.Arena.Arena;
import com.Geekpower14.Quake.Arena.SArena;
import com.Geekpower14.Quake.Arena.TArena;
import com.Geekpower14.Quake.Quake;
import com.sk89q.worldedit.bukkit.selections.Selection;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.block.Sign;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
public class LobbyManager {
public Quake _plugin;
public HashMap<String, Location> _locmin = new HashMap();
public HashMap<String, Location> _locmax = new HashMap();
public Location _lobbyspawn = null;
public List<Lobby> _LOBBYS = new ArrayList<>();
public List<Lobby_Sign> _LOBBYS_SIGN = new ArrayList<>();
public LobbyManager(Quake pl) {
_plugin = pl;
loadconfig();
}
public final void loadconfig() {
String nom;
File fichier_config = new File(_plugin.getDataFolder(), String.valueOf(File.separator) + "lobby.yml");
YamlConfiguration config = YamlConfiguration.loadConfiguration((File)fichier_config);
_lobbyspawn = str2loc(config.getString("LobbySpawn"));
int nombre = config.getInt("Nombre");
int i = 0;
while (i < nombre) {
nom = config.getString("min.lobby" + i);
_locmin.put("lobby" + i, str2loc(nom));
++i;
}
i = 0;
while (i < nombre) {
nom = config.getString("max.lobby" + i);
_locmax.put("lobby" + i, str2loc(nom));
++i;
}
_plugin.getLogger().info("load des Lobby ");
}
public void saveconfig() {
Location loc;
File fichier_config = new File(_plugin.getDataFolder(), String.valueOf(File.separator) + "lobby.yml");
YamlConfiguration config = YamlConfiguration.loadConfiguration(fichier_config);
if(_lobbyspawn != null) {
config.set("LobbySpawn", (String.valueOf(_lobbyspawn.getWorld().getName()) + ", " + _lobbyspawn.getX() + ", " + _lobbyspawn.getY() + ", " + _lobbyspawn.getZ() + ", " + _lobbyspawn.getYaw() + ", " + _lobbyspawn.getPitch()));
}
config.set("Nombre", _locmin.size());
for(String l2 : _locmin.keySet()) {
loc = _locmin.get(l2);
config.set("min." + l2, (String.valueOf(loc.getWorld().getName()) + ", " + loc.getX() + ", " + loc.getY() + ", " + loc.getZ() + ", " + loc.getYaw() + ", " + loc.getPitch()));
}
for(String l2 : _locmax.keySet()) {
loc = _locmax.get(l2);
config.set("max." + l2, (String.valueOf(loc.getWorld().getName()) + ", " + loc.getX() + ", " + loc.getY() + ", " + loc.getZ() + ", " + loc.getYaw() + ", " + loc.getPitch()));
}
try {
config.save(new File(_plugin.getDataFolder(), String.valueOf(File.separator) + "lobby.yml"));
_plugin.saveConfig();
} catch (IOException l) {
// empty catch block
}
_plugin.getLogger().info("save des Lobby ");
}
public Location str2loc(String loc) {
if (loc == null) {
return null;
}
Location res = null;
String[] loca = loc.split(", ");
res = new Location(_plugin.getServer().getWorld(loca[0]), Double.parseDouble(loca[1]), Double.parseDouble(loca[2]), Double.parseDouble(loca[3]), Float.parseFloat(loca[4]), Float.parseFloat(loca[5]));
return res;
}
public void setspawn(Player player) {
_lobbyspawn = player.getLocation();
}
public Boolean removeLobby(String lobby) {
_locmin.remove(lobby);
_locmax.remove(lobby);
HashMap<String, Location> tempmin = new HashMap<>();
HashMap<String, Location> tempmax = new HashMap<>();
int i = 0;
for (String s : _locmin.keySet()) {
tempmin.put("lobby" + i, _locmin.get(s));
tempmax.put("lobby" + i, _locmax.get(s));
++i;
}
_locmin = tempmin;
_locmax = tempmax;
return true;
}
public Boolean addLobby(Player player) {
String lobby = "lobby" + _locmin.size();
Selection selection = _plugin._worldEdit.getSelection(player);
if (selection != null) {
//World world = selection.getWorld();
Location un = selection.getMinimumPoint();
Location deux = selection.getMaximumPoint();
/*String direction = "";
if (un.getX() == deux.getX()) {
direction = "Z";
} else if (un.getZ() == deux.getZ()) {
direction = "X";
} else {
_plugin.log.warning("Pas m\u00eame X ou Z pour : " + lobby);
return false;
}*/
Location tempmin = un;
Location tempmax = deux;
_locmin.put(lobby, tempmin);
_locmax.put(lobby, tempmax);
player.sendMessage(ChatColor.YELLOW + "Lobby " + _locmin.size() + " cr\u00e9e avec succ\u00e9s");
initsign();
return true;
}
player.sendMessage(ChatColor.RED + "Veuillez faire une s\u00e9lection d'abord !");
return false;
}
public Boolean initsign() {
int index = 0;
int i = 0;
while(i < _locmin.size()) {
int x;
int y;
Arena arena;
String lobby = "lobby" + i;
Location min = _locmin.get(lobby);
Location max = _locmax.get(lobby);
int xmax = 0;
int xmin = 0;
int z = 0;
World w = min.getWorld();
if (w == null) {
return false;
}
if (min.getBlockX() == max.getBlockX()) {
xmax = max.getBlockZ();
xmin = min.getBlockZ();
z = min.getBlockX();
x = xmin;
while (x <= xmax) {
y = min.getBlockY();
while (y <= max.getBlockY()) {
arena = _plugin._am.getArenabyID(index);
if (arena != null) {
updateSign(w, z, y, x, arena);
} else {
clearSign(w, z, y, x);
}
++index;
++y;
}
++x;
}
} else if (min.getBlockZ() == max.getBlockZ()) {
xmax = max.getBlockX();
xmin = min.getBlockX();
z = min.getBlockZ();
x = xmin;
while (x <= xmax) {
y = max.getBlockY();
while (y >= min.getBlockY()) {
arena = _plugin._am.getArenabyID(index);
if (arena != null) {
updateSign(w, x, y, z, arena);
} else {
clearSign(w, x, y, z);
}
++index;
--y;
}
++x;
}
}
++i;
}
return true;
}
public Boolean isinLobby(Location loc) {
int oui = _locmin.size();
int i = 0;
while (i < _locmin.size()) {
String lobby = "lobby" + i;
Location min = _locmin.get(lobby);
Location max = _locmax.get(lobby);
if (min.getWorld() != loc.getWorld()) {
--oui;
} else if (loc.getX() < min.getX()) {
--oui;
} else if (loc.getX() > max.getX()) {
--oui;
} else if (loc.getZ() < min.getZ()) {
--oui;
} else if (loc.getZ() > max.getZ()) {
--oui;
} else if (loc.getY() < min.getY()) {
--oui;
} else if (loc.getY() > max.getY()) {
--oui;
}
++i;
}
if (oui <= 0) {
return false;
}
return true;
}
public void updateSign(World w, int x, int y, int z, Arena arena) {
Location bloc = new Location(w, (double)x, (double)y, (double)z);
if(bloc.getBlock() == null || bloc.getBlock().getType().equals(Material.AIR))
return;
Block block = bloc.getBlock();
if (block.getState() instanceof Sign) {
Sign sign = (Sign)block.getState();
String ligne0 = arena._etat <= arena._pregame ? (arena.getplayers() == arena._maxplayer ? ChatColor.DARK_PURPLE + "[FULL]" : (arena._VIP ? ChatColor.AQUA + "[VIP]" : (arena._etat <= arena._starting ? ChatColor.GOLD + "[Starting]" : ChatColor.GREEN + "[Join]"))) : ChatColor.RED + "[InGame]";
String tmp = "";
if (arena instanceof SArena) {
tmp = "S-";
}
if (arena instanceof TArena) {
tmp = "T-";
}
String ligne1 = tmp + arena._ID;
String ligne2 = (arena.getplayers() >= (arena._maxplayer * 0.75))? "" + ChatColor.RED + arena.getplayers() + "/" + arena._maxplayer : "" + arena.getplayers() + "/" + arena._maxplayer;
String ligne3 = arena._map;
sign.setLine(0, ligne0);
sign.setLine(1, ligne1);
sign.setLine(2, ligne2);
sign.setLine(3, ligne3);
sign.update(true);
}
}
public void clearSign(World w, int x, int y, int z) {
Location bloc = new Location(w, (double)x, (double)y, (double)z);
Block block = bloc.getBlock();
if (block.getState() instanceof Sign) {
Sign sign = (Sign)block.getState();
sign.setLine(0, ChatColor.GRAY + "[" + ChatColor.RED + "Quake" + ChatColor.GRAY + "]");
sign.setLine(1, "");
sign.setLine(2, ChatColor.GRAY + "Offline");
sign.setLine(3, "");
sign.update(true);
}
}
}

View File

@ -0,0 +1,15 @@
package com.Geekpower14.Quake.Lobby;
import com.Geekpower14.Quake.Arena.Arena;
import com.Geekpower14.Quake.Quake;
public class Lobby_Sign {
private final Quake _plugin;
private final Arena _arena;
public Lobby_Sign(Quake pl, Arena arena) {
_plugin = pl;
_arena = arena;
}
}

View File

@ -0,0 +1,282 @@
package com.Geekpower14.Quake;
import com.Geekpower14.Quake.Arena.ArenaManager;
import com.Geekpower14.Quake.Commands.MyCommandExecutor;
import com.Geekpower14.Quake.Eco.EcoManager;
import com.Geekpower14.Quake.Listener.PlayerListener;
import com.Geekpower14.Quake.Listener.Weather;
import com.Geekpower14.Quake.Lobby.LobbyManager;
import com.Geekpower14.Quake.Shop.IconMenuManager;
import com.Geekpower14.Quake.Shop.ShopManager;
import com.Geekpower14.Quake.Stuff.StuffManager;
import com.Geekpower14.Quake.Trans.Translate;
import com.Geekpower14.Quake.Utils.ParticleEffects;
import com.Geekpower14.Quake.Utils.Reflection;
import com.Geekpower14.Quake.Utils.ScoreB;
import com.Geekpower14.Quake.Utils.Version;
import com.sk89q.worldedit.bukkit.WorldEditPlugin;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import java.util.logging.Level;
import org.bukkit.Bukkit;
import org.bukkit.Color;
import org.bukkit.FireworkEffect;
import org.bukkit.Material;
import org.bukkit.command.CommandExecutor;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Firework;
import org.bukkit.entity.Player;
import org.bukkit.event.HandlerList;
import org.bukkit.event.Listener;
import org.bukkit.inventory.meta.FireworkMeta;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scoreboard.Scoreboard;
public class Quake
extends JavaPlugin {
public static boolean _debug = false;
public static String _version = "3.0.0";
public static Version _ver = new Version(_version);
public ArenaManager _am = null;
public LobbyManager _lobby = null;
public int _threadlob = 0;
public int _thread = 0;
public int _compteur = 0;
public Boolean _geeklove = true;
public static Quake _instance = null;
public WorldEditPlugin _worldEdit;
public ShopManager _shop;
public Translate _trad;
public StuffManager _stuff;
public IconMenuManager _imm;
public EcoManager _eco;
public FileConfiguration _config;
public Boolean _useVault = false;
public Material _shopId = Material.EMERALD;
public List<String> _shopWorlds = new ArrayList<>();
public List<String> _ScoreWorlds = new ArrayList<>();
public HashMap<String, ScoreB> _scores = new HashMap();
public Scoreboard _board;
@Override
public void onEnable() {
_instance = this;
_imm = new IconMenuManager((Plugin)this);
_board = Bukkit.getScoreboardManager().getNewScoreboard();
_config = YamlConfiguration.loadConfiguration((File)new File(getDataFolder(), "config.yml"));
_shopWorlds.add("world");
_ScoreWorlds.add("world");
loadConfig();
saveConfig();
getDataFolder().mkdir();
new File(getDataFolder().getPath() + "/arenas").mkdir();
_worldEdit = (WorldEditPlugin)Bukkit.getServer().getPluginManager().getPlugin("WorldEdit");
if(_worldEdit == null) {
getLogger().warning("WorldEdit not found !!");
}
try {
_eco = new EcoManager(this);
} catch (Exception var1_2) {
// empty catch block
}
_trad = new Translate(this);
_shop = new ShopManager(this);
_stuff = new StuffManager(this);
getServer().getPluginManager().registerEvents(new PlayerListener(this), this);
getServer().getPluginManager().registerEvents(new Weather(this), this);
getCommand("Quake").setExecutor(new MyCommandExecutor(this));
_am = new ArenaManager(this);
_lobby = new LobbyManager(this);
_threadlob = Bukkit.getScheduler().scheduleSyncRepeatingTask(this, new Runnable(){
@Override
public void run() {
_lobby.initsign();
}
}, 0, 2);
_thread = Bukkit.getScheduler().scheduleSyncRepeatingTask((Plugin)this, (Runnable)new Task(this), 0, 20);
}
@Override
public void onDisable() {
_am.Disable();
_stuff.disable();
getServer().getScheduler().cancelTask(_threadlob);
getServer().getScheduler().cancelTask(_thread);
HandlerList.unregisterAll((Plugin)this);
}
public void loadConfig() {
_debug = _config.getBoolean("debug", false);
_useVault = _config.getBoolean("useVault", true);
_shopId = Material.getMaterial(_config.getString("shop.id", "EMERALD"));
if(_config.contains("shop.world")) {
_shopWorlds = _config.getStringList("shop.world");
}
if(_config.contains("ScoreBoard.world")) {
_ScoreWorlds = _config.getStringList("ScoreBoard.world");
}
}
@Override
public void saveConfig() {
_config.set("debug", _debug);
_config.set("useVault", _useVault);
_config.set("shop.id", _shopId.name());
_config.set("shop.world", _shopWorlds);
_config.set("ScoreBoard.world", _ScoreWorlds);
try {
_config.save(new File(getDataFolder(), "config.yml"));
} catch (IOException e) {
getLogger().log(Level.WARNING, "Failed to save configuration!");
}
}
public static Boolean hasPermission(Player p, String perm) {
if(perm.equalsIgnoreCase(""))
return true;
if(p.isOp())
return true;
if(p.hasPermission("Quake.admin"))
return true;
return p.hasPermission(perm);
}
public static void sendTabName(Player p, String s, Boolean visible, int ping) {
try {
Object packet = (Object)Reflection.getNMSClass("PacketPlayOutPlayerInfo").newInstance();
ParticleEffects.ReflectionUtilities.setValue(packet, "a", s);
ParticleEffects.ReflectionUtilities.setValue(packet, "b", visible);
ParticleEffects.ReflectionUtilities.setValue(packet, "c", ping);
ParticleEffects.sendPacket(packet, p);
} catch (Exception e) {
e.printStackTrace();
}
}
public void win(final Player player) {
final int infoxp = Bukkit.getScheduler().scheduleSyncRepeatingTask(this, new Runnable() {
@Override
public void run() {
if(_compteur >= 150)
return;
Firework fw = (Firework)player.getWorld().spawnEntity(player.getLocation(), EntityType.FIREWORK);
FireworkMeta fwm = fw.getFireworkMeta();
Random r = new Random();
int rt = r.nextInt(4) + 1;
FireworkEffect.Type type = FireworkEffect.Type.BALL;
if(rt == 1)
type = FireworkEffect.Type.BALL;
if(rt == 2)
type = FireworkEffect.Type.BALL_LARGE;
if(rt == 3)
type = FireworkEffect.Type.BURST;
if(rt == 4)
type = FireworkEffect.Type.CREEPER;
if(rt == 5)
type = FireworkEffect.Type.STAR;
int r1i = r.nextInt(17) + 1;
int r2i = r.nextInt(17) + 1;
Color c1 = getColor(r1i);
Color c2 = getColor(r2i);
FireworkEffect effect = FireworkEffect.builder().flicker(r.nextBoolean()).withColor(c1).withFade(c2).with(type).trail(r.nextBoolean()).build();
fwm.addEffect(effect);
int rp = r.nextInt(2) + 1;
fwm.setPower(rp);
fw.setFireworkMeta(fwm);
_compteur++;
}
}, 5, 1);
Bukkit.getScheduler().scheduleSyncDelayedTask((Plugin)this, new Runnable() {
@Override
public void run() {
getServer().getScheduler().cancelTask(infoxp);
}
}, 300);
}
private Color getColor(int i) {
Color c = null;
if (i == 1) {
c = Color.AQUA;
}
if (i == 2) {
c = Color.BLACK;
}
if (i == 3) {
c = Color.BLUE;
}
if (i == 4) {
c = Color.FUCHSIA;
}
if (i == 5) {
c = Color.GRAY;
}
if (i == 6) {
c = Color.GREEN;
}
if (i == 7) {
c = Color.LIME;
}
if (i == 8) {
c = Color.MAROON;
}
if (i == 9) {
c = Color.NAVY;
}
if (i == 10) {
c = Color.OLIVE;
}
if (i == 11) {
c = Color.ORANGE;
}
if (i == 12) {
c = Color.PURPLE;
}
if (i == 13) {
c = Color.RED;
}
if (i == 14) {
c = Color.SILVER;
}
if (i == 15) {
c = Color.TEAL;
}
if (i == 16) {
c = Color.WHITE;
}
if (i == 17) {
c = Color.YELLOW;
}
return c;
}
public static Quake getPlugin() {
return _instance;
}
public static void debug(Exception ex) {
debug("An error was found:", ex);
}
public static void debug(String msg) {
debug(msg, null);
}
public static void debug(String msg, Exception ex) {
if(_instance._config.getBoolean("debug", false))
_instance.getLogger().log(Level.INFO, "An error was found:", ex);
}
}

View File

@ -0,0 +1,87 @@
package com.Geekpower14.Quake.Shop;
import com.Geekpower14.Quake.Utils.IconMenu;
import java.util.HashMap;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.Plugin;
public class IconMenuManager implements Listener {
private final HashMap<Player, IconMenu> _menus = new HashMap();
private final Plugin _plugin;
public IconMenuManager(Plugin pl) {
_plugin = pl;
_plugin.getServer().getPluginManager().registerEvents((Listener)this, _plugin);
}
public void closeall() {
for(Player p : _menus.keySet())
destroy(p);
}
public void create(Player p, String name, int size, IconMenu.OptionClickEventHandler handler) {
if(_menus.containsKey(p))
destroy(p);
IconMenu im = new IconMenu(name, size, handler, _plugin);
_menus.put(p, im);
}
public void show(Player p) {
if(!_menus.containsKey(p))
return;
_menus.get(p).open(p);
}
public void reopen(Player p) {
if(!_menus.containsKey(p))
return;
_menus.get(p).reopen(p);
}
public void setOption(Player p, int position, ItemStack icon, String reg) {
if(!_menus.containsKey(p))
return;
_menus.get(p).setOption(position, icon, reg);
}
public void setOption(Player p, int position, ItemStack icon, String name, String reg, String[] info) {
if(!_menus.containsKey(p))
return;
_menus.get(p).setOption(position, icon, name, reg, info);
}
public void destroy(Player p) {
if(!_menus.containsKey(p))
return;
_menus.get(p).destroy();
_menus.remove(p);
p.getOpenInventory().close();
}
@EventHandler
public void onInventoryClick(InventoryClickEvent event) {
if(!(event.getWhoClicked() instanceof Player))
return;
Player p = (Player)event.getWhoClicked();
if(_menus.containsKey(p))
_menus.get(p).onInventoryClick(event);
}
@EventHandler
public void onInventoryClose(InventoryCloseEvent event) {
if(!(event.getPlayer() instanceof Player))
return;
Player p = (Player)event.getPlayer();
if(_menus.containsKey(p))
_menus.get(p).onInventoryClose(event);
}
}

View File

@ -0,0 +1,70 @@
package com.Geekpower14.Quake.Shop;
import org.bukkit.inventory.ItemStack;
public class Item {
public String _name;
public ItemStack _icon;
public String[] _description;
public String _reg;
public int _position;
public int _price;
public Item(String n, ItemStack ic, String id, String[] desc, int prix, int pos) {
_name = n;
_icon = ic;
_reg = id;
_description = desc;
_position = pos;
_price = prix;
}
public void setName(String n) {
_name = n;
}
public void setIcon(ItemStack ic) {
_icon = ic;
}
public void setID(String id) {
_reg = id;
}
public void setDescription(String[] desc) {
_description = desc;
}
public void setPosition(int pos) {
_position = pos;
}
public void setPrice(int prix) {
_price = prix;
}
public String getName() {
return _name;
}
public ItemStack getIcon() {
return _icon;
}
public String getID() {
return _reg;
}
public String[] getDescription() {
return _description;
}
public int getPos() {
return _position;
}
public int getPrice() {
return _price;
}
}

View File

@ -0,0 +1,466 @@
package com.Geekpower14.Quake.Shop;
import com.Geekpower14.Quake.Arena.APlayer;
import com.Geekpower14.Quake.Eco.EcoManager;
import com.Geekpower14.Quake.Quake;
import com.Geekpower14.Quake.Stuff.Armor.ArmorBasic;
import com.Geekpower14.Quake.Stuff.Hat.HatBasic;
import com.Geekpower14.Quake.Stuff.Item.ItemBasic;
import com.Geekpower14.Quake.Utils.IconMenu;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.plugin.Plugin;
public class ShopManager {
public Quake _plugin;
public HashMap<String, Item> _objects = new HashMap();
public ShopManager(Quake b) {
_plugin = b;
}
public void getMainShop(Player p) {
_plugin._imm.create(p, "Quake Manager", 54, new IconMenu.OptionClickEventHandler() {
@Override
public void onOptionClick(IconMenu.OptionClickEvent event) {
if (event.getName() == null) {
return;
}
Quake.getPlugin()._shop.Main_Manager(event.getPlayer(), event.getName());
}
});
_plugin._imm.setOption(p, 0, new ItemStack(Material.DIAMOND_HOE, 1), _plugin._trad.get("Shop.ManagerHoe"), "Hoe_manager", new String[]{_plugin._trad.get("Shop.SelectHoe")});
_plugin._imm.setOption(p, 3, new ItemStack(Material.LEATHER_CHESTPLATE, 1), _plugin._trad.get("Shop.ManagerArmor"), "Armor_manager", new String[]{_plugin._trad.get("Shop.SelectArmor")});
_plugin._imm.setOption(p, 5, new ItemStack(Material.JACK_O_LANTERN, 1), _plugin._trad.get("Shop.ManagerHat"), "Hat_manager", new String[]{_plugin._trad.get("Shop.SelectHat")});
_plugin._imm.setOption(p, 8, new ItemStack(Material.EMERALD, 1), _plugin._trad.get("Shop.Shop"), "Shop", new String[]{_plugin._trad.get("Shop.BuyNewStuff")});
_plugin._imm.setOption(p, 49, new ItemStack(Material.BED, 1), _plugin._trad.get("Shop.Exit"), "Exit", new String[]{_plugin._trad.get("Shop.ExitDesc")});
}
public void getHoeManager(Player player, int page) {
APlayer.createConfig(player);
_plugin._imm.create(player, "Hoe Manager", 54, new IconMenu.OptionClickEventHandler(){
@Override
public void onOptionClick(IconMenu.OptionClickEvent event) {
if (event.getName() == null) {
return;
}
event.setWillDestroy(true);
Quake.getPlugin()._shop.Hoe_Manager(event.getPlayer(), event.getName());
}
});
List<String> Hoes = _plugin._stuff.getItems(player);
int i = 0;
i = page;
while (i <= (page >= 1 ? 44 * page : 44)) {
if (Hoes.size() < i + 1) break;
ItemBasic item = _plugin._stuff.getItem(Hoes.get(i));
String[] stockArr = new String[item.getItem().getItemMeta().getLore().size()];
stockArr = item.getItem().getItemMeta().getLore().toArray(stockArr);
_plugin._imm.setOption(player, i, item.getItem(), item.getItem().getItemMeta().getDisplayName(), item._name, stockArr);
++i;
}
_plugin._imm.setOption(player, 49, new ItemStack(Material.BED, 1), _plugin._trad.get("Shop.navigation.home"), "Home", new String[]{_plugin._trad.get("Shop.navigation.homeDesc")});
}
public void getHatManager(Player player, int page) {
_plugin._imm.create(player, "Hat Manager", 54, new IconMenu.OptionClickEventHandler(){
@Override
public void onOptionClick(IconMenu.OptionClickEvent event) {
if (event.getName() == null) {
return;
}
event.setWillDestroy(true);
Quake.getPlugin()._shop.Hat_Manager(event.getPlayer(), event.getName());
}
});
List<String> Hat = _plugin._stuff.getHats(player);
int i = 0;
i = page;
while (i <= (page >= 1 ? 44 * page : 44)) {
if (Hat.size() < i + 1) break;
HatBasic item = _plugin._stuff.getHat(Hat.get(i));
String[] stockArr = new String[item.getItem().getItemMeta().getLore().size()];
stockArr = item.getItem().getItemMeta().getLore().toArray(stockArr);
_plugin._imm.setOption(player, i, item.getItem(), item.getItem().getItemMeta().getDisplayName(), item._name, stockArr);
++i;
}
_plugin._imm.setOption(player, 49, new ItemStack(Material.BED, 1), _plugin._trad.get("Shop.navigation.home"), "Home", new String[]{_plugin._trad.get("Shop.navigation.homeDesc")});
}
public void getArmorManager(Player player, int page) {
_plugin._imm.create(player, "Armor Manager", 54, new IconMenu.OptionClickEventHandler(){
@Override
public void onOptionClick(IconMenu.OptionClickEvent event) {
if (event.getName() == null) {
return;
}
event.setWillDestroy(true);
Quake.getPlugin()._shop.Armor_Manager(event.getPlayer(), event.getName());
}
});
List<String> Armor = _plugin._stuff.getArmors(player);
int i = 0;
i = page;
while (i <= (page >= 1 ? 44 * page : 44)) {
if (Armor.size() < i + 1) break;
ArmorBasic item = _plugin._stuff.getArmor(Armor.get(i));
String[] stockArr = new String[item.getItem().getItemMeta().getLore().size()];
stockArr = item.getItem().getItemMeta().getLore().toArray(stockArr);
_plugin._imm.setOption(player, i, item.getItem(), item.getItem().getItemMeta().getDisplayName(), item._name, stockArr);
++i;
}
_plugin._imm.setOption(player, 49, new ItemStack(Material.BED, 1), _plugin._trad.get("Shop.navigation.home"), "Home", new String[]{_plugin._trad.get("Shop.navigation.homeDesc")});
}
public void getShopMenu(Player player, int page) {
int slot;
String name = "Shop";
if (page > 0) {
name = "Shop - Page " + page;
}
_plugin._imm.create(player, name, 54, new IconMenu.OptionClickEventHandler(){
@Override
public void onOptionClick(IconMenu.OptionClickEvent event) {
if (event.getName() == null) {
return;
}
Quake.getPlugin()._shop.Shop_Manager(event.getPlayer(), event.getName());
if (!event.getName().equalsIgnoreCase("Home")) {
openShop(event.getPlayer());
}
}
});
ArrayList<ItemBasic> Hoes = _plugin._stuff.getItems();
ArrayList<ArmorBasic> Armor = _plugin._stuff.getArmors();
ArrayList<HatBasic> Hat = _plugin._stuff.getHats();
int i = slot = page >= 1 ? 44 * page : 0;
int tmp = 0;
tmp = 0;
while (i <= slot + 44 && tmp < Hoes.size()) {
if (Hoes.size() < tmp + 1) break;
ItemBasic item = Hoes.get(tmp);
String[] arrstring = new String[2];
arrstring[0] = _plugin._trad.get("Shop.price").replace("[PRICE]", Integer.toString(item._price));
arrstring[1] = !item._needToBuy.equals("") ? _plugin._trad.get("Shop.needToBuy").replace("[NEED]", item._needToBuy) : "";
_plugin._imm.setOption(player, i, item.getItem(), item.getItem().getItemMeta().getDisplayName(), "HOE_" + item._name, arrstring);
tmp++;
i++;
}
tmp = 0;
while (i <= slot + 44 && tmp < Hat.size()) {
if (Hat.size() < tmp + 1) break;
HatBasic item = Hat.get(tmp);
String[] arrstring = new String[2];
arrstring[0] = _plugin._trad.get("Shop.price").replace("[PRICE]", Integer.toString(item._price));
arrstring[1] = !item._needToBuy.equals("") ? _plugin._trad.get("Shop.needToBuy").replace("[NEED]", item._needToBuy) : "";
_plugin._imm.setOption(player, i, item.getItem(), item.getItem().getItemMeta().getDisplayName(), "HAT_" + item._name, arrstring);
tmp++;
i++;
}
tmp = 0;
while (i <= slot + 44 && tmp < Armor.size()) {
if (Armor.size() < tmp + 1) break;
ArmorBasic item = Armor.get(tmp);
String[] arrstring = new String[2];
arrstring[0] = _plugin._trad.get("Shop.price").replace("[PRICE]", Integer.toString(item._price));
arrstring[1] = !item._needToBuy.equals("") ? _plugin._trad.get("Shop.needToBuy").replace("[NEED]", item._needToBuy) : "";
_plugin._imm.setOption(player, i, item.getItem(), item.getItem().getItemMeta().getDisplayName(), "ARMOR_" + item._name, arrstring);
tmp++;
i++;
}
if (page > 0) {
_plugin._imm.setOption(player, 45, new ItemStack(Material.SIGN, 1), _plugin._trad.get("Shop.navigation.previousPage"), "Page-" + (page - 1), new String[]{_plugin._trad.get("Shop.navigation.previousPageDesc")});
}
_plugin._imm.setOption(player, 49, new ItemStack(Material.BED, 1), _plugin._trad.get("Shop.navigation.home"), "Home", new String[]{_plugin._trad.get("Shop.navigation.homeDesc")});
Item so = getItemShop(player);
_plugin._imm.setOption(player, 50, so.getIcon(), so.getName(), "Nothing", so.getDescription());
if (i == slot + 44) {
_plugin._imm.setOption(player, 53, new ItemStack(Material.SIGN, 1), _plugin._trad.get("Shop.navigation.nextPage"), "Page-" + (page + 1), new String[]{_plugin._trad.get("Shop.navigation.nextPageDesc")});
}
}
public void getShopItem(Player player) {
PlayerInventory i = player.getInventory();
ItemStack coucou = new ItemStack(Material.EMERALD, 1);
ItemMeta coucou_meta = coucou.getItemMeta();
coucou_meta.setDisplayName(_plugin._trad.get("Shop.item.name"));
coucou.setItemMeta(coucou_meta);
i.addItem(new ItemStack[]{coucou});
}
public ItemStack getShop() {
ItemStack coucou = new ItemStack(_plugin._shopId, 1);
ItemMeta coucou_meta = coucou.getItemMeta();
coucou_meta.setDisplayName(_plugin._trad.get("Shop.item.name"));
coucou.setItemMeta(coucou_meta);
return coucou;
}
public String getMeta() {
return _plugin._trad.get("Shop.item.name");
}
public Item getItemShop(Player player) {
EcoManager eco = _plugin._eco;
int coins = eco.getPlayerMoney(player);
return new Item("Shop", new ItemStack(Material.EMERALD, 1), "shop", new String[] {_plugin._trad.get("Shop.youHave"), "" + ChatColor.GOLD + coins + " " + _plugin._trad.get("Shop.Coins.name")}, 0, 0);
}
public void openShop(final Player p) {
Bukkit.getScheduler().scheduleSyncDelayedTask((Plugin)_plugin, new Runnable(){
@Override
public void run() {
Quake.getPlugin()._shop.getShopMenu(p, 0);
Quake.getPlugin()._imm.show(p);
}
}, 2);
}
public void Main_Manager(final Player p, String id) {
if (id.equalsIgnoreCase("Hoe_manager")) {
Bukkit.getScheduler().scheduleSyncDelayedTask((Plugin)_plugin, new Runnable() {
@Override
public void run() {
Quake.getPlugin()._shop.getHoeManager(p, 0);
Quake.getPlugin()._imm.show(p);
}
}, 2);
return;
}
if (id.equalsIgnoreCase("Hat_manager")) {
Bukkit.getScheduler().scheduleSyncDelayedTask((Plugin)_plugin, new Runnable() {
@Override
public void run() {
Quake.getPlugin()._shop.getHatManager(p, 0);
Quake.getPlugin()._imm.show(p);
}
}, 2);
return;
}
if (id.equalsIgnoreCase("Armor_manager")) {
Bukkit.getScheduler().scheduleSyncDelayedTask((Plugin)_plugin, new Runnable() {
@Override
public void run() {
Quake.getPlugin()._shop.getArmorManager(p, 0);
Quake.getPlugin()._imm.show(p);
}
}, 2);
return;
}
if (id.equalsIgnoreCase("Shop")) {
Bukkit.getScheduler().scheduleSyncDelayedTask((Plugin)_plugin, new Runnable() {
@Override
public void run() {
Quake.getPlugin()._shop.getShopMenu(p, 0);
Quake.getPlugin()._imm.show(p);
}
}, 2);
return;
}
}
public void Hoe_Manager(final Player p, String id) {
if (id.equalsIgnoreCase("Home")) {
Bukkit.getScheduler().scheduleSyncDelayedTask((Plugin)_plugin, new Runnable() {
@Override
public void run() {
Quake.getPlugin()._shop.getMainShop(p);
Quake.getPlugin()._imm.show(p);
}
}, 2);
return;
}
if (_plugin._stuff.setSelectedItem(p, id)) {
p.sendMessage(_plugin._trad.get("Shop.Selection.Hoe"));
} else {
p.sendMessage(ChatColor.RED + " Error: Hoe not successful selected !");
}
Bukkit.getScheduler().scheduleSyncDelayedTask((Plugin)_plugin, new Runnable() {
@Override
public void run() {
Quake.getPlugin()._shop.getHoeManager(p, 0);
Quake.getPlugin()._imm.show(p);
}
}, 2);
}
public void Hat_Manager(final Player p, String id) {
if (id.equalsIgnoreCase("Home")) {
Bukkit.getScheduler().scheduleSyncDelayedTask((Plugin)_plugin, new Runnable() {
@Override
public void run() {
Quake.getPlugin()._shop.getMainShop(p);
Quake.getPlugin()._imm.show(p);
}
}, 2);
return;
}
if (_plugin._stuff.setSelectedHat(p, id)) {
p.sendMessage(_plugin._trad.get("Shop.Selection.Hat"));
} else {
p.sendMessage(ChatColor.RED + " Error: Hat not successful selected !");
}
Bukkit.getScheduler().scheduleSyncDelayedTask((Plugin)_plugin, new Runnable() {
@Override
public void run() {
Quake.getPlugin()._shop.getHatManager(p, 0);
Quake.getPlugin()._imm.show(p);
}
}, 2);
}
public void Armor_Manager(final Player p, String id) {
if (id.equalsIgnoreCase("Home")) {
Bukkit.getScheduler().scheduleSyncDelayedTask((Plugin)_plugin, new Runnable(){
@Override
public void run() {
Quake.getPlugin()._shop.getMainShop(p);
Quake.getPlugin()._imm.show(p);
}
}, 2);
return;
}
if (_plugin._stuff.setSelectedArmor(p, id)) {
p.sendMessage(_plugin._trad.get("Shop.Selection.Armor"));
} else {
p.sendMessage(ChatColor.RED + " Error: Armor not successful selected !");
}
Bukkit.getScheduler().scheduleSyncDelayedTask((Plugin)_plugin, new Runnable() {
@Override
public void run() {
Quake.getPlugin()._shop.getArmorManager(p, 0);
Quake.getPlugin()._imm.show(p);
}
}, 2);
}
public void Shop_Manager(final Player p, String id) {
if (id.startsWith("Page")) {
final String[] pa = id.split("-");
Bukkit.getScheduler().scheduleSyncDelayedTask((Plugin)_plugin, new Runnable(){
@Override
public void run() {
Quake.getPlugin()._shop.getShopMenu(p, Integer.valueOf(pa[1]));
Quake.getPlugin()._imm.show(p);
}
}, 2);
return;
}
if (id.equalsIgnoreCase("Home")) {
Bukkit.getScheduler().scheduleSyncDelayedTask((Plugin)_plugin, new Runnable(){
@Override
public void run() {
Quake.getPlugin()._shop.getMainShop(p);
Quake.getPlugin()._imm.show(p);
}
}, 2);
return;
}
if (id.startsWith("HOE")) {
ItemBasic need;
String[] pa = id.split("_");
String ide = pa[1];
ItemBasic item = _plugin._stuff.getItem(ide);
if (!item._needToBuy.equals("") && (need = _plugin._stuff.getItem(item._needToBuy)) != null && !_plugin._stuff.hasItem(p, item._needToBuy)) {
p.sendMessage(_plugin._trad.get("Shop.YouNeed").replace("[NEED]", item._needToBuy));
return;
}
if (!Quake.hasPermission(p, item._needPerm)) {
p.sendMessage(_plugin._trad.get("Shop.NoPermissionToBuy"));
return;
}
if (!_plugin._eco.has(p, item._price)) {
p.sendMessage(_plugin._trad.get("Shop.NotEnoughMoney"));
return;
}
if (_plugin._stuff.hasItem(p, item._name)) {
p.sendMessage(_plugin._trad.get("Shop.AlreadyHaveItem"));
return;
}
_plugin._eco.soustrairePlayerMoney(p, item._price);
_plugin._stuff.addItem(p, item._name);
p.sendMessage(_plugin._trad.get("Shop.YouHaveBoughtItem").replace("[NAME]", item._name));
return;
}
if (id.startsWith("HAT")) {
HatBasic need;
String[] pa = id.split("_");
String ide = pa[1];
HatBasic item = _plugin._stuff.getHat(ide);
if (!item._needToBuy.equals("") && (need = _plugin._stuff.getHat(item._needToBuy)) != null && !_plugin._stuff.hasHat(p, item._needToBuy)) {
p.sendMessage(_plugin._trad.get("Shop.YouNeed").replace("[NEED]", item._needToBuy));
return;
}
if (!Quake.hasPermission(p, item._needPerm)) {
p.sendMessage(_plugin._trad.get("Shop.NoPermissionToBuy"));
return;
}
if (!_plugin._eco.has(p, item._price)) {
p.sendMessage(_plugin._trad.get("Shop.NotEnoughMoney"));
return;
}
if (_plugin._stuff.hasHat(p, item._name)) {
p.sendMessage(_plugin._trad.get("Shop.AlreadyHaveThisHat"));
return;
}
_plugin._eco.soustrairePlayerMoney(p, item._price);
_plugin._stuff.addHat(p, item._name);
p.sendMessage(_plugin._trad.get("Shop.YouHaveBoughtItem").replace("[NAME]", item._name));
return;
}
if (id.startsWith("ARMOR")) {
ArmorBasic need;
String[] pa = id.split("_");
String ide = pa[1];
ArmorBasic item = _plugin._stuff.getArmor(ide);
if (!item._needToBuy.equals("") && (need = _plugin._stuff.getArmor(item._needToBuy)) != null && !_plugin._stuff.hasArmor(p, item._needToBuy)) {
p.sendMessage(_plugin._trad.get("Shop.YouNeed").replace("[NEED]", item._needToBuy));
return;
}
if (!Quake.hasPermission(p, item._needPerm)) {
p.sendMessage(_plugin._trad.get("Shop.NoPermissionToBuy"));
return;
}
if (!_plugin._eco.has(p, item._price)) {
p.sendMessage(_plugin._trad.get("Shop.NotEnoughMoney"));
return;
}
if (_plugin._stuff.hasArmor(p, item._name)) {
p.sendMessage(_plugin._trad.get("Shop.AlreadyHaveThisArmor"));
return;
}
_plugin._eco.soustrairePlayerMoney(p, item._price);
_plugin._stuff.addArmor(p, item._name);
p.sendMessage(_plugin._trad.get("Shop.YouHaveBoughtItem").replace("[NAME]", item._name));
return;
}
}
}

View File

@ -0,0 +1,28 @@
package com.Geekpower14.Quake.Stuff.Armor;
import com.Geekpower14.Quake.Quake;
import org.bukkit.inventory.ItemStack;
public abstract class ArmorBasic {
public Quake _plugin = Quake.getPlugin();
public int _price = 0;
public String _name = "Unknown";
public String _needPerm = "";
public String _givePerm = "Quake.admin";
public String _needToBuy = "";
public abstract ItemStack getItem();
public String getNeededPerm() {
return _needPerm;
}
public String getGivePerm() {
return _givePerm;
}
public abstract void disable();
public abstract void saveConfig();
}

View File

@ -0,0 +1,40 @@
package com.Geekpower14.Quake.Stuff.Armor;
import java.io.File;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.event.HandlerList;
import org.bukkit.event.Listener;
import org.bukkit.inventory.ItemStack;
public class ArmorCustomFile extends ArmorBasic implements Listener {
FileConfiguration _config;
public ArmorCustomFile(String path) {
_config = YamlConfiguration.loadConfiguration(new File(path));
_price = _config.getInt("Price");
_name = _config.getString("Name");
_givePerm = "Quake.admin";
_needToBuy = "";
ItemStack item = _config.getItemStack("Material");
if (item == null) {
_plugin.getLogger().severe(_config.getString("Name") + " not a valid Material.");
} else
_plugin.getServer().getPluginManager().registerEvents((Listener)this, _plugin);
}
@Override
public ItemStack getItem() {
return _config.getItemStack("Material");
}
@Override
public void disable() {
HandlerList.unregisterAll((Listener)this);
}
@Override
public void saveConfig() {
}
}

View File

@ -0,0 +1,17 @@
/*
* Decompiled with CFR 0_114.
*/
package com.Geekpower14.Quake.Stuff.Armor;
public class ArmorFactory {
public static ArmorBasic getInstance(String hatName, String path) {
if (hatName.equals("ArmorRED")) {
return new ArmorRED();
}
if (hatName.equals("ArmorCustomFile")) {
return new ArmorCustomFile(path);
}
return null;
}
}

View File

@ -0,0 +1,26 @@
/*
* Decompiled with CFR 0_114.
*
* Could not load the following classes:
* org.bukkit.inventory.ItemStack
*/
package com.Geekpower14.Quake.Stuff.Armor;
import org.bukkit.inventory.ItemStack;
public class ArmorRED
extends ArmorBasic {
@Override
public ItemStack getItem() {
return null;
}
@Override
public void disable() {
}
@Override
public void saveConfig() {
}
}

View File

@ -0,0 +1,28 @@
package com.Geekpower14.Quake.Stuff.Hat;
import com.Geekpower14.Quake.Quake;
import org.bukkit.inventory.ItemStack;
public abstract class HatBasic {
public Quake _plugin = Quake.getPlugin();
public int _price = 0;
public String _name = "Unknown";
public String _needPerm = "";
public String _givePerm = "Quake.admin";
public String _needToBuy = "";
public abstract ItemStack getItem();
public String getNeededPerm() {
return _needPerm;
}
public String getGivePerm() {
return _givePerm;
}
public abstract void disable();
public abstract void saveConfig();
}

View File

@ -0,0 +1,77 @@
package com.Geekpower14.Quake.Stuff.Hat;
import com.Geekpower14.Quake.Trans.Translate;
import java.io.File;
import java.util.ArrayList;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.SkullType;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.event.HandlerList;
import org.bukkit.event.Listener;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.SkullMeta;
public class HatCustomFile extends HatBasic implements Listener {
FileConfiguration _config;
public HatCustomFile(String path) {
_config = YamlConfiguration.loadConfiguration(new File(path));
_price = _config.getInt("Price");
_name = _config.getString("Name");
_givePerm = "Quake.admin";
_needToBuy = "";
Material material = Material.getMaterial(_config.getString("Material"));
if(material == null || material == Material.AIR) {
_plugin.getLogger().severe(_config.getString("Material") + " not a valid Material. Example: " + Material.APPLE.name());
}
_plugin.getServer().getPluginManager().registerEvents((Listener)this, _plugin);
}
public static ItemStack Skull(String skullOwner) {
ItemStack skull = new ItemStack(Material.SKULL_ITEM, 1, (short)SkullType.PLAYER.ordinal());
SkullMeta skullMeta = (SkullMeta)skull.getItemMeta();
skullMeta.setOwner(skullOwner);
skull.setItemMeta((ItemMeta)skullMeta);
return skull;
}
@Override
public ItemStack getItem() {
ItemStack item = null;
if(_config.getString("Material").startsWith("Player:")) {
String tmp = _config.getString("Material");
String[] tb = tmp.split(":");
item = HatCustomFile.Skull(tb[1]);
} else {
Material material = Material.getMaterial((String)_config.getString("Material"));
if (material == null || material == Material.AIR) {
_plugin.getLogger().severe(_config.getString("Material") + " not a valid Material. Example: " + Material.APPLE.name());
}
item = new ItemStack(material, 1);
}
ItemMeta meta = item.getItemMeta();
meta.setDisplayName(ChatColor.GREEN + _name);
ArrayList<String> arg0 = new ArrayList<>();
String desc = _config.getString("Description");
if(desc == null) {
_plugin.getLogger().severe("Description not set");
}
arg0.add(ChatColor.RESET + Translate.replaceColors(desc));
meta.setLore(arg0);
item.setItemMeta(meta);
return item;
}
@Override
public void disable() {
HandlerList.unregisterAll((Listener)this);
}
@Override
public void saveConfig() {
}
}

View File

@ -0,0 +1,21 @@
/*
* Decompiled with CFR 0_114.
*/
package com.Geekpower14.Quake.Stuff.Hat;
import com.Geekpower14.Quake.Stuff.Hat.HatBasic;
import com.Geekpower14.Quake.Stuff.Hat.HatCustomFile;
import com.Geekpower14.Quake.Stuff.Hat.HatJACK;
public class HatFactory {
public static HatBasic getInstance(String hatName, String path) {
if (hatName.equals("HatJACK")) {
return new HatJACK();
}
if (hatName.equals("HatCustomFile")) {
return new HatCustomFile(path);
}
return null;
}
}

View File

@ -0,0 +1,41 @@
package com.Geekpower14.Quake.Stuff.Hat;
import java.util.ArrayList;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.event.HandlerList;
import org.bukkit.event.Listener;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
public class HatJACK extends HatBasic implements Listener {
public HatJACK() {
_price = 50;
_name = "JackOHat";
_givePerm = "Quake.admin";
_needToBuy = "";
_plugin.getServer().getPluginManager().registerEvents((Listener)this, _plugin);
}
@Override
public ItemStack getItem() {
ItemStack item = new ItemStack(Material.JACK_O_LANTERN, 1);
ItemMeta meta = item.getItemMeta();
meta.setDisplayName(ChatColor.GREEN + _name);
ArrayList<String> arg0 = new ArrayList<>();
arg0.add(ChatColor.BOLD + "It's cool !");
meta.setLore(arg0);
item.setItemMeta(meta);
return item;
}
@Override
public void disable() {
HandlerList.unregisterAll((Listener)this);
}
@Override
public void saveConfig() {
}
}

View File

@ -0,0 +1,82 @@
package com.Geekpower14.Quake.Stuff.Item;
import com.Geekpower14.Quake.Arena.APlayer;
import com.Geekpower14.Quake.Arena.Arena;
import java.util.ArrayList;
import org.bukkit.Bukkit;
import org.bukkit.Color;
import org.bukkit.FireworkEffect;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.Listener;
import org.bukkit.inventory.ItemStack;
import org.bukkit.util.Vector;
public class DiamondHoe extends ItemBasic implements Listener {
public DiamondHoe() {
_name = "Amazing RailGun";
_needToBuy = "GoldenGun";
_Time = 20L;
_price = 1200;
loadConfig();
saveConfig();
_plugin.getServer().getPluginManager().registerEvents((Listener)this, _plugin);
}
@Override
public ItemStack getItem() {
ItemStack item = defaultItem(Material.DIAMOND_HOE, _Time);
return item;
}
@Override
public void shot(Player player) {
BasicShot(player, FireworkEffect.builder().withColor(Color.AQUA).with(FireworkEffect.Type.BURST).build());
}
@Override
public void eject(Player player) {
}
public void explode(Player player, FireworkEffect effect) {
Arena arena = _plugin._am.getArenabyPlayer(player);
if (arena == null) {
return;
}
APlayer ap = arena.getAPlayer(player);
if (ap.isReloading()) {
return;
}
ap.setReloading(true);
try {
_fw.playFirework(player.getWorld(), player.getLocation(), effect);
} catch (Exception e) {
e.printStackTrace();
}
long startTime = System.currentTimeMillis();
int maxRange = 15;
ArrayList<Player> targets = new ArrayList<>();
for(Player online: Bukkit.getOnlinePlayers()) {
if (online != player && online.getLocation().distance(player.getEyeLocation()) < (double)maxRange) {
targets.add(online);
}
}
Location loc = player.getEyeLocation();
for(Player p : targets) {
if (p.getUniqueId() == player.getUniqueId()) continue;
Location two = p.getEyeLocation();
Vector from = new Vector(loc.getX(), loc.getY(), loc.getZ());
Vector to = new Vector(two.getX(), two.getY(), two.getZ());
Vector vector = to.subtract(from).normalize();
vector.add(new Vector(0, 1, 0));
vector.multiply(1.7);
p.setVelocity(vector);
}
ap.setReloading(_Time);
}
}

View File

@ -0,0 +1,36 @@
package com.Geekpower14.Quake.Stuff.Item;
import org.bukkit.Color;
import org.bukkit.FireworkEffect;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.Listener;
import org.bukkit.inventory.ItemStack;
public class GoldHoe extends ItemBasic implements Listener {
public GoldHoe() {
_name = "GoldenGun";
_needToBuy = "Boosted RailGun";
_Time = 28L;
_price = 800;
loadConfig();
saveConfig();
_plugin.getServer().getPluginManager().registerEvents((Listener)this, _plugin);
}
@Override
public ItemStack getItem() {
ItemStack item = defaultItem(Material.GOLD_HOE, _Time);
return item;
}
@Override
public void shot(Player player) {
BasicShot(player, FireworkEffect.builder().withColor(Color.YELLOW).with(FireworkEffect.Type.BALL_LARGE).build());
}
@Override
public void eject(Player player) {
}
}

View File

@ -0,0 +1,36 @@
package com.Geekpower14.Quake.Stuff.Item;
import org.bukkit.Color;
import org.bukkit.FireworkEffect;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.Listener;
import org.bukkit.inventory.ItemStack;
public class IronHoe extends ItemBasic implements Listener {
public IronHoe() {
_name = "Boosted RailGun";
_needToBuy = "Advanced RailGun";
_Time = 32L;
_price = 600;
loadConfig();
saveConfig();
_plugin.getServer().getPluginManager().registerEvents((Listener)this, _plugin);
}
@Override
public ItemStack getItem() {
ItemStack item = defaultItem(Material.IRON_HOE, _Time);
return item;
}
@Override
public void shot(Player player) {
BasicShot(player, FireworkEffect.builder().withColor(Color.GRAY).with(FireworkEffect.Type.BALL_LARGE).build());
}
@Override
public void eject(Player player) {
}
}

View File

@ -0,0 +1,295 @@
package com.Geekpower14.Quake.Stuff.Item;
import com.Geekpower14.Quake.Arena.APlayer;
import com.Geekpower14.Quake.Arena.Arena;
import com.Geekpower14.Quake.Quake;
import com.Geekpower14.Quake.Utils.FireworkEffectPlayer;
import com.Geekpower14.Quake.Utils.ParticleEffects;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.FireworkEffect;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.Sound;
import org.bukkit.block.Block;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.HandlerList;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.util.Vector;
public abstract class ItemBasic implements Listener {
public Quake _plugin = Quake.getPlugin();
public int _price = 0;
public String _name = "Unknown";
public String _alias = "";
public String _needPerm = "";
public String _givePerm = "Quake.admin";
public String _needToBuy = "";
public Long _Time;
FireworkEffectPlayer _fw;
public abstract ItemStack getItem();
public ItemStack defaultItem(Material material, Long time) {
ItemStack item = new ItemStack(material, 1);
ItemMeta meta = item.getItemMeta();
meta.setDisplayName(ChatColor.GREEN + _alias);
ArrayList<String> arg0 = new ArrayList<>();
arg0.add(_plugin._trad.get("Shop.Hoe.Desc1"));
float t = (float)time;
arg0.add(_plugin._trad.get("Shop.Hoe.Desc2").replace("[TIME]", "" + t / 20.0f));
meta.setLore(arg0);
item.setItemMeta(meta);
return item;
}
public ItemBasic() {
loadConfig();
_fw = new FireworkEffectPlayer(_plugin);
}
public ItemBasic(Arena aren, String name) {
loadConfig();
_name = name;
_fw = new FireworkEffectPlayer(_plugin);
}
public ItemBasic(Arena aren, String name, int price) {
loadConfig();
_price = price;
_name = name;
_fw = new FireworkEffectPlayer(_plugin);
}
public String getNeededPerm() {
return _needPerm;
}
public String getGivePerm() {
return _givePerm;
}
protected void BasicShot(Player player, FireworkEffect effect) {
Arena arena = _plugin._am.getArenabyPlayer(player);
if (arena == null) {
return;
}
APlayer ap = arena.getAPlayer(player);
if (ap.isReloading()) {
return;
}
ap.setReloading(true);
int compte = 0;
List<Player> victims = getTargetV3(arena, player, 100, 1.2, false);
for(Player victim : victims) {
arena.shotplayer(player, victim, effect);
}
compte = victims.size();
player.getWorld().playSound(player.getLocation(), Sound.ENTITY_GENERIC_EXPLODE, 0.1f, 2.0f);
player.getWorld().playSound(player.getLocation(), Sound.ENTITY_GENERIC_EXPLODE, 0.1f, 1.5f);
player.getWorld().playSound(player.getLocation(), Sound.ENTITY_GENERIC_EXPLODE, 0.1f, 1.4f);
player.getWorld().playSound(player.getLocation(), Sound.ENTITY_GENERIC_EXPLODE, 0.1f, 1.3f);
player.getWorld().playSound(player.getLocation(), Sound.ENTITY_GENERIC_EXPLODE, 0.1f, 1.2f);
/*player.getWorld().playSound(player.getLocation(), org.bukkit.Sound.EXPLODE, 0.1f, 2.0f);
player.getWorld().playSound(player.getLocation(), Sound.EXPLODE, 0.1f, 1.5f);
player.getWorld().playSound(player.getLocation(), Sound.EXPLODE, 0.1f, 1.4f);
player.getWorld().playSound(player.getLocation(), Sound.EXPLODE, 0.1f, 1.3f);
player.getWorld().playSound(player.getLocation(), Sound.EXPLODE, 0.1f, 1.2f);*/
if (compte == 2) {
arena.broadcast(_plugin._trad.get("Game.Arena.Kill.Double"));
} else if (compte == 3) {
arena.broadcast(_plugin._trad.get("Game.Arena.Kill.Triple"));
} else if (compte >= 4) {
arena.broadcast(_plugin._trad.get("Game.Arena.Kill.More"));
}
arena.getScoreShot(player);
ap.setReloading(_Time);
}
public List<Player> getTargetV3(Arena arena, Player player, int maxRange, double aiming, boolean wallHack) {
ArrayList<Player> target = new ArrayList<>();
Location playerEyes = player.getEyeLocation();
Vector direction = playerEyes.getDirection().normalize();
ArrayList<Player> targets = new ArrayList<>();
for(Player online: player.getWorld().getPlayers()) {
Arena oArena = Quake.getPlugin()._am.getArenabyPlayer(online);
if(oArena == null || !oArena.equals(arena))
continue;
if(online != player && online.getLocation().distanceSquared(playerEyes) < (double)(maxRange * maxRange)) {
targets.add(online);
}
}
Location loc = playerEyes.clone();
Vector progress = direction.clone().multiply(0.7);
maxRange = 100 * maxRange / 70;
int loop = 0;
while(loop < maxRange) {
loop++;
loc.add(progress);
Block block = loc.getBlock();
if (!wallHack && block.getType().isSolid())
break;
double lx = loc.getX();
double ly = loc.getY();
double lz = loc.getZ();
for(APlayer apa: arena._players.values()) {
try {
ParticleEffects.FIREWORKS_SPARK.sendToPlayer(apa.getPlayer(), loc, 0.1f, 0.1f, 0.1f, 0.05f, 2);
} catch (Exception e) {
e.printStackTrace();
}
}
for(Player possibleTarget : targets) {
if(possibleTarget.getUniqueId() == player.getUniqueId())
continue;
Location testLoc = possibleTarget.getLocation().add(0.0, 0.85, 0.0);
double px = testLoc.getX();
double py = testLoc.getY();
double pz = testLoc.getZ();
boolean dX = Math.abs(lx - px) < 0.7 * aiming;
boolean dY = Math.abs(ly - py) < 1.7 * aiming;
boolean dZ = Math.abs(lz - pz) < 0.7 * aiming;
if(!dX || !dY || !dZ || target.contains(possibleTarget))
continue;
target.add(possibleTarget);
}
}
return target;
}
public Boolean istheSame(ItemStack it) {
ItemStack item = getItem();
ItemMeta meta = item.getItemMeta();
ItemMeta met = it.getItemMeta();
if (meta == null && met == null) {
return true;
}
if (meta == null || met == null) {
return false;
}
if (!meta.getDisplayName().equalsIgnoreCase(met.getDisplayName())) {
return false;
}
return meta.getLore().equals(met.getLore());
}
@EventHandler(priority=EventPriority.HIGHEST)
public void onPlayerInteract(PlayerInteractEvent event) {
Action action = event.getAction();
Player player = event.getPlayer();
ItemStack hand = player.getItemInHand();
Quake.debug("Debug Item Player Listener Interact Part 1");
Arena arena = _plugin._am.getArenabyPlayer(player);
if (arena == null) {
return;
}
Quake.debug("Debug Item Player Listener Interact Part 2");
APlayer ap = arena.getAPlayer(player);
if (action == Action.LEFT_CLICK_AIR || action == Action.LEFT_CLICK_BLOCK) {
Quake.debug("Debug Item Player Listener Interact Part 3");
if (!istheSame(hand)) {
event.setCancelled(true);
return;
}
Quake.debug("Debug Item Player Listener Interact Part 4");
if (arena._etat != arena._ingame || arena._finished) {
event.setCancelled(true);
return;
}
Quake.debug("Debug Item Player Listener Interact Part 5");
if (ap.isReloading()) {
event.setCancelled(true);
return;
}
Quake.debug("Debug Item Player Listener Interact Part 6");
eject(player);
event.setCancelled(true);
return;
}
if (action == Action.RIGHT_CLICK_AIR || action == Action.RIGHT_CLICK_BLOCK) {
Quake.debug("Debug Item Player Listener Interact Part 7");
if (!istheSame(hand)) {
event.setCancelled(true);
return;
}
Quake.debug("Debug Item Player Listener Interact Part 8");
if (arena._etat != arena._ingame || arena._finished) {
event.setCancelled(true);
return;
}
Quake.debug("Debug Item Player Listener Interact Part 9");
if (ap.isReloading()) {
event.setCancelled(true);
return;
}
Quake.debug("Debug Item Player Listener Interact Part 10");
shot(player);
event.setCancelled(true);
}
}
public abstract void eject(Player var1);
public abstract void shot(Player var1);
public void disable() {
HandlerList.unregisterAll((Listener)this);
}
public final void loadConfig() {
YamlConfiguration config = YamlConfiguration.loadConfiguration((File)new File(_plugin.getDataFolder(), "/Stuff/Hoes/" + _name + ".yml"));
if (config.contains("Name")) {
_name = config.getString("Name");
}
_alias = _name;
if (config.contains("Alias")) {
_alias = config.getString("Alias");
}
if (config.contains("Reload-Time")) {
_Time = config.getLong("Reload-Time");
}
if (config.contains("Price")) {
_price = config.getInt("Price");
}
if (config.contains("Needed-Permissions")) {
_needPerm = config.getString("Needed-Permissions");
}
if (config.contains("Permissions-To-Give")) {
_givePerm = config.getString("Permissions-To-Give");
}
}
public final void saveConfig() {
YamlConfiguration config = YamlConfiguration.loadConfiguration((File)new File(""));
config.set("Name",_name);
config.set("Alias", _alias);
config.set("Reload-Time", _Time);
config.set("Price", _price);
config.set("Needed-Permissions", _needPerm);
config.set("Permissions-To-Give", _givePerm);
try {
config.save(new File(_plugin.getDataFolder(), "/Stuff/Hoes/" + _name + ".yml"));
}
catch (IOException e) {
_plugin.getLogger().warning("save de " + _name + " impossible !");
}
}
}

View File

@ -0,0 +1,36 @@
package com.Geekpower14.Quake.Stuff.Item;
import org.bukkit.Color;
import org.bukkit.FireworkEffect;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.Listener;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.Plugin;
public class StoneHoe extends ItemBasic implements Listener {
public StoneHoe() {
_name = "Advanced RailGun";
_Time = 36L;
_price = 400;
loadConfig();
saveConfig();
_plugin.getServer().getPluginManager().registerEvents((Listener)this, _plugin);
}
@Override
public ItemStack getItem() {
ItemStack item = defaultItem(Material.STONE_HOE, _Time);
return item;
}
@Override
public void shot(Player player) {
BasicShot(player, FireworkEffect.builder().withColor(Color.GREEN).with(FireworkEffect.Type.BALL_LARGE).build());
}
@Override
public void eject(Player player) {
}
}

View File

@ -0,0 +1,52 @@
/*
* Decompiled with CFR 0_114.
*
* Could not load the following classes:
* org.bukkit.Color
* org.bukkit.FireworkEffect
* org.bukkit.FireworkEffect$Builder
* org.bukkit.FireworkEffect$Type
* org.bukkit.Material
* org.bukkit.Server
* org.bukkit.entity.Player
* org.bukkit.event.Listener
* org.bukkit.inventory.ItemStack
* org.bukkit.plugin.Plugin
* org.bukkit.plugin.PluginManager
*/
package com.Geekpower14.Quake.Stuff.Item;
import org.bukkit.Color;
import org.bukkit.FireworkEffect;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.Listener;
import org.bukkit.inventory.ItemStack;
public class WoodenHoe extends ItemBasic implements Listener {
public WoodenHoe() {
_name = "RailGun";
_Time = 40L;
_givePerm = "";
_price = 0;
loadConfig();
saveConfig();
_plugin.getServer().getPluginManager().registerEvents((Listener)this, _plugin);
}
@Override
public ItemStack getItem() {
ItemStack item = defaultItem(Material.WOOD_HOE, _Time);
return item;
}
@Override
public void shot(Player player) {
BasicShot(player, FireworkEffect.builder().withColor(Color.RED).with(FireworkEffect.Type.BALL_LARGE).build());
}
@Override
public void eject(Player player) {
}
}

View File

@ -0,0 +1,407 @@
package com.Geekpower14.Quake.Stuff;
import com.Geekpower14.Quake.Arena.APlayer;
import com.Geekpower14.Quake.Quake;
import com.Geekpower14.Quake.Stuff.Armor.ArmorBasic;
import com.Geekpower14.Quake.Stuff.Armor.ArmorFactory;
import com.Geekpower14.Quake.Stuff.Hat.HatBasic;
import com.Geekpower14.Quake.Stuff.Hat.HatFactory;
import com.Geekpower14.Quake.Stuff.Item.DiamondHoe;
import com.Geekpower14.Quake.Stuff.Item.GoldHoe;
import com.Geekpower14.Quake.Stuff.Item.IronHoe;
import com.Geekpower14.Quake.Stuff.Item.ItemBasic;
import com.Geekpower14.Quake.Stuff.Item.StoneHoe;
import com.Geekpower14.Quake.Stuff.Item.WoodenHoe;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.ChatColor;
import org.bukkit.Color;
import org.bukkit.Material;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.LeatherArmorMeta;
public class StuffManager {
private final Quake _plugin;
private ArrayList<ArmorBasic> _armors = new ArrayList();
private ArrayList<HatBasic> _hats = new ArrayList();
private ArrayList<ItemBasic> _item = new ArrayList();
public StuffManager(Quake pl) {
_plugin = pl;
loadItem();
loadHat();
loadArmor();
}
public void reloadConfig() {
loadItem();
loadHat();
loadArmor();
}
public final void loadItem() {
_item = new ArrayList();
_item.add(new WoodenHoe());
_item.add(new StoneHoe());
_item.add(new IronHoe());
_item.add(new GoldHoe());
_item.add(new DiamondHoe());
}
public final void loadHat() {
File[] files;
_hats = new ArrayList();
File f = new File(_plugin.getDataFolder(), "/Stuff/Hats");
if (!f.exists()) {
YamlConfiguration nhat = YamlConfiguration.loadConfiguration((File)new File(""));
nhat.set("Implementation", "HatCustomFile");
nhat.set("Price", 50);
nhat.set("Name", "JackOHat");
nhat.set("Material", Material.JACK_O_LANTERN.toString());
nhat.set("Description", (String.valueOf(ChatColor.BOLD.toString()) + "It's cool !"));
try {
nhat.save(new File(_plugin.getDataFolder(), "/Stuff/Hats/JackOHat.yml"));
}
catch (IOException e) {
_plugin.getLogger().warning("save JackOHat impossible !");
}
YamlConfiguration nhatt = YamlConfiguration.loadConfiguration((File)new File(""));
nhatt.set("Implementation", "HatCustomFile");
nhatt.set("Price", 500000);
nhatt.set("Name", "Geekpower14");
nhatt.set("Material", "Player:geekpower14");
nhatt.set("Description", (String.valueOf(ChatColor.BOLD.toString()) + "He's cool !"));
try {
nhatt.save(new File(_plugin.getDataFolder(), "/Stuff/Hats/Geekpower14.yml"));
}
catch (IOException e) {
_plugin.getLogger().warning("save JackOHat impossible !");
}
f.mkdirs();
}
File[] arrfile = files = new File(_plugin.getDataFolder(), "/Stuff/Hats").listFiles();
int n = arrfile.length;
int e = 0;
while (e < n) {
YamlConfiguration config;
File file = arrfile[e];
_plugin.getLogger().warning(file.getPath());
if (file.isFile() && file.getPath().endsWith(".yml") && (config = YamlConfiguration.loadConfiguration((File)file)).contains("Implementation")) {
_plugin.getLogger().info(String.valueOf(file.getPath()) + " found implementation");
HatBasic hat = HatFactory.getInstance(config.getString("Implementation"), file.getPath());
if (hat == null) {
_plugin.getLogger().severe(String.valueOf(file.getPath()) + " invalid implementation");
} else {
_hats.add(hat);
}
}
++e;
}
}
public final void loadArmor() {
File[] files;
_armors = new ArrayList();
File f = new File(_plugin.getDataFolder(), "/Stuff/Armors");
if (!f.exists()) {
YamlConfiguration nhat = YamlConfiguration.loadConfiguration((File)new File(""));
nhat.set("Implementation", "ArmorCustomFile");
nhat.set("Price", 100);
nhat.set("Name", "ArmorRED");
ItemStack item = new ItemStack(Material.LEATHER_CHESTPLATE);
LeatherArmorMeta meta = (LeatherArmorMeta)item.getItemMeta();
meta.setDisplayName(ChatColor.RED + "ArmorRED");
ArrayList<String> l = new ArrayList<String>();
l.add(ChatColor.RESET + "A beautiful leather dress!");
meta.setLore(l);
meta.setColor(Color.RED);
item.setItemMeta((ItemMeta)meta);
nhat.set("Material", item);
try {
nhat.save(new File(_plugin.getDataFolder(), "/Stuff/Armors/ArmorRED.yml"));
}
catch (IOException e) {
_plugin.getLogger().warning("save ArmorRED impossible !");
}
f.mkdirs();
}
File[] e = files = new File(_plugin.getDataFolder(), "/Stuff/Armors").listFiles();
int l = e.length;
int meta = 0;
while (meta < l) {
YamlConfiguration config;
File file = e[meta];
_plugin.getLogger().warning(file.getPath());
if (file.isFile() && file.getPath().endsWith(".yml") && (config = YamlConfiguration.loadConfiguration((File)file)).contains("Implementation")) {
_plugin.getLogger().info(file.getPath() + " found implementation");
ArmorBasic armor = ArmorFactory.getInstance(config.getString("Implementation"), file.getPath());
if (armor == null) {
_plugin.getLogger().severe(file.getPath() + " invalid implementation");
} else {
_armors.add(armor);
}
}
++meta;
}
}
public ArrayList<ItemBasic> getItems() {
return _item;
}
public ItemBasic getSelectedItem(APlayer player) {
YamlConfiguration config = YamlConfiguration.loadConfiguration((File)new File(_plugin.getDataFolder(), "/Players/" + player.getPlayer().getName() + ".yml"));
String id = config.getString("Hoe.Selected");
if (id == null) {
id = "RailGun";
}
return getItem(id);
}
public ItemBasic getSelectedItem(Player player) {
YamlConfiguration config = YamlConfiguration.loadConfiguration((File)new File(_plugin.getDataFolder(), "/Players/" + player.getName() + ".yml"));
String id = config.getString("Hoe.Selected");
if (id == null) {
id = "RailGun";
}
return getItem(id);
}
public Boolean setSelectedItem(Player p, String name) {
if (getItem(name) == null) {
return false;
}
YamlConfiguration config = YamlConfiguration.loadConfiguration((File)new File(_plugin.getDataFolder(), "/Players/" + p.getName() + ".yml"));
config.set("Hoe.Selected", name);
try {
config.save(new File(_plugin.getDataFolder(), "/Players/" + p.getName() + ".yml"));
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
public Boolean hasItem(Player p, String name) {
YamlConfiguration config = YamlConfiguration.loadConfiguration((File)new File(_plugin.getDataFolder(), "/Players/" + p.getName() + ".yml"));
List list = config.getStringList("Hoe.Bought");
if (list.contains(name)) {
return true;
}
ArrayList<String> result = new ArrayList<>();
for (ItemBasic it : _item) {
if (!Quake.hasPermission(p, it._givePerm)) continue;
result.add(it._name);
}
if (result.contains(name)) {
return true;
}
return false;
}
public List<String> getItems(Player p) {
YamlConfiguration config = YamlConfiguration.loadConfiguration((File)new File(_plugin.getDataFolder(), "/Players/" + p.getName() + ".yml"));
List<String> list = config.getStringList("Hoe.Bought");
ArrayList<String> result = new ArrayList<>();
for (String l : list) {
ItemBasic ite = getItem(l);
if (ite == null || !Quake.hasPermission(p, ite._needPerm) || result.contains(l))
continue;
result.add(l);
}
for (ItemBasic it : _item) {
if (!Quake.hasPermission(p, it._givePerm) || result.contains(it._name)) continue;
result.add(it._name);
}
return result;
}
public List<String> getHats(Player p) {
YamlConfiguration config = YamlConfiguration.loadConfiguration((File)new File(_plugin.getDataFolder(), "/Players/" + p.getName() + ".yml"));
List<String> list = config.getStringList("Hat.Bought");
ArrayList<String> result = new ArrayList<>();
for (String l : list) {
HatBasic ite = getHat(l);
if (ite == null || !Quake.hasPermission(p, ite._needPerm) || result.contains(l))
continue;
result.add(l);
}
for(HatBasic it : _hats) {
if (!Quake.hasPermission(p, it._givePerm) || result.contains(it._name))
continue;
result.add(it._name);
}
return result;
}
public List<String> getArmors(Player p) {
YamlConfiguration config = YamlConfiguration.loadConfiguration((File)new File(_plugin.getDataFolder(), "/Players/" + p.getName() + ".yml"));
List<String> list = config.getStringList("Armor.Bought");
ArrayList<String> result = new ArrayList<>();
for (String l : list) {
ArmorBasic ite = getArmor(l);
if (ite == null || !Quake.hasPermission(p, ite._needPerm) || result.contains(l))
continue;
result.add(l);
}
for (ArmorBasic it : _armors) {
if (!Quake.hasPermission(p, it._givePerm) || result.contains(it._name))
continue;
result.add(it._name);
}
return result;
}
public void addItem(Player p, String name) {
if (getItem(name) == null) {
return;
}
YamlConfiguration config = YamlConfiguration.loadConfiguration((File)new File(_plugin.getDataFolder(), "/Players/" + p.getName() + ".yml"));
List list = config.getStringList("Hoe.Bought");
list.add(name);
config.set("Hoe.Bought", list);
try {
config.save(new File(_plugin.getDataFolder(), "/Players/" + p.getName() + ".yml"));
} catch (IOException e) {
e.printStackTrace();
}
}
public void addHat(Player p, String name) {
if (getHat(name) == null) {
return;
}
YamlConfiguration config = YamlConfiguration.loadConfiguration((File)new File(_plugin.getDataFolder(), "/Players/" + p.getName() + ".yml"));
List list = config.getStringList("Hat.Bought");
list.add(name);
config.set("Hat.Bought", list);
try {
config.save(new File(_plugin.getDataFolder(), "/Players/" + p.getName() + ".yml"));
} catch (IOException e) {
e.printStackTrace();
}
}
public void addArmor(Player p, String name) {
if (getArmor(name) == null) {
return;
}
YamlConfiguration config = YamlConfiguration.loadConfiguration((File)new File(_plugin.getDataFolder(), "/Players/" + p.getName() + ".yml"));
List list = config.getStringList("Armor.Bought");
list.add(name);
config.set("Armor.Bought", list);
try {
config.save(new File(_plugin.getDataFolder(), "/Players/" + p.getName() + ".yml"));
} catch (IOException e) {
e.printStackTrace();
}
}
public Boolean setSelectedHat(Player p, String name) {
if (getHat(name) == null) {
return false;
}
YamlConfiguration config = YamlConfiguration.loadConfiguration((File)new File(_plugin.getDataFolder(), "/Players/" + p.getName() + ".yml"));
config.set("Hat.Selected", name);
try {
config.save(new File(_plugin.getDataFolder(), "/Players/" + p.getName() + ".yml"));
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
public Boolean setSelectedArmor(Player p, String name) {
if (getArmor(name) == null) {
return false;
}
YamlConfiguration config = YamlConfiguration.loadConfiguration((File)new File(_plugin.getDataFolder(), "/Players/" + p.getName() + ".yml"));
config.set("Armor.Selected", name);
try {
config.save(new File(_plugin.getDataFolder(), "/Players/" + p.getName() + ".yml"));
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
public Boolean hasHat(Player p, String name) {
YamlConfiguration config = YamlConfiguration.loadConfiguration((File)new File(_plugin.getDataFolder(), "/Players/" + p.getName() + ".yml"));
List list = config.getStringList("Hat.Bought");
if (list.contains(name)) {
return true;
}
return false;
}
public HatBasic getSelectedHat(APlayer player) {
YamlConfiguration config = YamlConfiguration.loadConfiguration((File)new File(player.getConfig()));
String id = config.getString("Hat.Selected");
return getHat(id);
}
public ArmorBasic getSelectedArmor(APlayer player) {
YamlConfiguration config = YamlConfiguration.loadConfiguration((File)new File(player.getConfig()));
String id = config.getString("Armor.Selected");
return getArmor(id);
}
public Boolean hasArmor(Player p, String name) {
YamlConfiguration config = YamlConfiguration.loadConfiguration((File)new File(_plugin.getDataFolder(), "/Players/" + p.getName() + ".yml"));
List list = config.getStringList("Armor.Bought");
if (list.contains(name)) {
return true;
}
return false;
}
public ItemBasic getItem(String name) {
for (ItemBasic it : _item) {
if (!it._name.equalsIgnoreCase(name)) continue;
return it;
}
return null;
}
public HatBasic getHat(String name) {
for (HatBasic it : _hats) {
if (!it._name.equalsIgnoreCase(name)) continue;
return it;
}
return null;
}
public ArmorBasic getArmor(String name) {
for (ArmorBasic it : _armors) {
if (!it._name.equalsIgnoreCase(name)) continue;
return it;
}
return null;
}
public ArrayList<HatBasic> getHats() {
return _hats;
}
public ArrayList<ArmorBasic> getArmors() {
return _armors;
}
public void disable() {
for (ItemBasic it22 : _item) {
it22.disable();
}
for (HatBasic it : _hats) {
it.disable();
}
for (ArmorBasic it2 : _armors) {
it2.disable();
}
}
}

View File

@ -0,0 +1,87 @@
package com.Geekpower14.Quake;
import com.Geekpower14.Quake.Arena.Arena;
import com.Geekpower14.Quake.Arena.SArena;
import com.Geekpower14.Quake.Arena.TArena;
import com.Geekpower14.Quake.Utils.ScoreB;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
public class Task implements Runnable {
private final Quake _plugin;
public Task(Quake pl) {
_plugin = pl;
}
/*
* Enabled force condition propagation
* Lifted jumps to return sites
*/
public void resetTime(Arena arena) {
Location wo = null;
if(arena instanceof TArena) {
if(((TArena)arena)._spawns_B.isEmpty())
return;
wo = ((TArena)arena)._spawns_B.get(0);
} else if(arena instanceof SArena) {
if(((SArena)arena)._spawns.isEmpty())
return;
wo = ((SArena)arena)._spawns.get(0);
}
if(wo == null || wo.getWorld() == null || wo.getWorld().getTime() < 10000)
return;
wo.getWorld().setTime(4000);
_plugin.getLogger().info("Time set for :" + arena._name);
}
@Override
public void run() {
for(Player p: Bukkit.getOnlinePlayers()) {
//while (n2 < n) {
Arena arena = _plugin._am.getArenabyPlayer(p);
if (arena != null) {
resetTime(arena);
return;
}
if (_plugin._shopWorlds.contains(p.getWorld().getName()) && !p.getInventory().contains(_plugin._shop.getShop()) && Quake.hasPermission(p, "Quake.Shop")) {
ItemStack[] arritemStack = p.getInventory().getContents();
int n3 = arritemStack.length;
int n4 = 0;
while (n4 < n3) {
ItemStack it = arritemStack[n4];
if (it != null && it.getItemMeta() != null && it.getItemMeta().getDisplayName() != null && it.getItemMeta().getDisplayName().equalsIgnoreCase(_plugin._shop.getShop().getItemMeta().getDisplayName())) {
try {
p.getInventory().remove(it);
} catch (Exception var10_10) {
// empty catch block
}
}
++n4;
}
p.getInventory().addItem(new ItemStack[]{_plugin._shop.getShop()});
}
if (isScoreWorld(p.getWorld().getName())) {
giveScoreBoard(p);
}
}
}
public void giveScoreBoard(Player p) {
if (_plugin._scores.containsKey(p.getName())) {
_plugin._scores.get(p.getName()).updateScore();
} else {
_plugin._scores.put(p.getName(), new ScoreB(_plugin, p));
}
}
public Boolean isScoreWorld(String name) {
if (_plugin._ScoreWorlds.contains(name)) {
return true;
}
return false;
}
}

View File

@ -0,0 +1,28 @@
/*
* Decompiled with CFR 0_114.
*/
package com.Geekpower14.Quake.Trans;
public class Score {
public static enum Type {
Win("Wins"),
Kill("Kills"),
Death("Deaths"),
Shot("Shots"),
TeamWin("TeamWins");
String _type;
private Type(String s) {
_type = s;
}
@Override
public String toString() {
return _type;
}
}
}

View File

@ -0,0 +1,137 @@
package com.Geekpower14.Quake.Trans;
import com.Geekpower14.Quake.Quake;
import java.io.File;
import java.io.IOException;
import org.bukkit.ChatColor;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
public class Translate {
Quake _plugin;
FileConfiguration _config;
private void setDefaultConfig(String key, String value) {
if (!_config.isSet(key)) {
_config.set(key, value);
}
}
public void reloadConfig() {
_config = YamlConfiguration.loadConfiguration((File)new File(_plugin.getDataFolder(), "/Language.yml"));
}
public Translate(Quake pl) {
_plugin = pl;
_config = YamlConfiguration.loadConfiguration((File)new File(_plugin.getDataFolder(), "/Language.yml"));
try {
setDefaultConfig("Shop.item.name", "&aShop &6(Click to Open)");
setDefaultConfig("Shop.item.description", "");
setDefaultConfig("Game.hoe.diamond", "Amazing RailGun");
setDefaultConfig("Game.hoe.gold", "GoldenGun");
setDefaultConfig("Game.hoe.iron", "Boosted RailGun");
setDefaultConfig("Game.hoe.stone", "Advanced RailGun");
setDefaultConfig("Game.hoe.wood", "RailGun");
setDefaultConfig("Game.item.leave", "&aExit &6(Click to Leave)");
setDefaultConfig("Shop.Coins.name", "Coins");
setDefaultConfig("ScoreBoard.Kills.name", "Kills");
setDefaultConfig("ScoreBoard.Deaths.name", "Deaths");
setDefaultConfig("ScoreBoard.Shots.name", "Shots");
setDefaultConfig("ScoreBoard.Wins.name", "Wins");
setDefaultConfig("ScoreBoard.name", "Scores");
setDefaultConfig("Shop.price", "&r&o&6Price: [PRICE]");
setDefaultConfig("Shop.needToBuy", "&r&o&6Need: [NEED]");
setDefaultConfig("Shop.navigation.previousPage", "&aBack");
setDefaultConfig("Shop.navigation.previousPageDesc", "Back to previous page !");
setDefaultConfig("Shop.navigation.home", "&aHome");
setDefaultConfig("Shop.navigation.homeDesc", "Back to Home !");
setDefaultConfig("Shop.navigation.nextPage", "&aNext");
setDefaultConfig("Shop.navigation.nextPageDesc", "Go to next page !");
setDefaultConfig("Shop.youHave", "&aYou have :");
setDefaultConfig("NoPermission", "&cYou have not the permissions.");
setDefaultConfig("Shop.NoPermissionToBuy", "&cYou have not the permission to buy it !");
setDefaultConfig("Shop.NotEnoughMoney", "&cYou have not enough money to buy it !");
setDefaultConfig("Shop.AlreadyHaveItem", "&cYou have already this Item !");
setDefaultConfig("Shop.YouHaveBoughtItem", "&aYou have bought [NAME] !");
setDefaultConfig("Shop.AlreadyHaveThisHat", "&cYou have already this Hat !");
setDefaultConfig("Shop.AlreadyHaveThisArmor", "&cYou have already this Armor !");
setDefaultConfig("Shop.SelectHoe", "Select your Hoe !");
setDefaultConfig("Shop.SelectArmor", "Select your Armor !");
setDefaultConfig("Shop.SelectHat", "Select your Hat !");
setDefaultConfig("Shop.BuyNewStuff", "Buy new stuff !");
setDefaultConfig("Shop.ExitDesc", "Exit !");
setDefaultConfig("Shop.ManagerHoe", "&aHoe Manager");
setDefaultConfig("Shop.ManagerArmor", "&aArmor Manager");
setDefaultConfig("Shop.ManagerHat", "&aHat Manager");
setDefaultConfig("Shop.Shop", "&aShop");
setDefaultConfig("Shop.Exit", "&aExit");
setDefaultConfig("Shop.Selection.Hoe", "&aHoe successful selected !");
setDefaultConfig("Shop.Selection.Hat", "&aHat successful selected");
setDefaultConfig("Shop.Selection.Armor", "&aArmor successful selected !");
setDefaultConfig("Shop.YouNeed", "&cYou need [NEED] !");
setDefaultConfig("Shop.Hoe.Desc1", "&lRight-Click to Instant-Kill !");
setDefaultConfig("Shop.Hoe.Desc2", "&lRecharge in [TIME] s");
setDefaultConfig("", "");
setDefaultConfig("", "");
setDefaultConfig("", "");
setDefaultConfig("", "");
setDefaultConfig("", "");
setDefaultConfig("", "");
setDefaultConfig("Shop.message.error.Unknown-Item", "&cError Unknown Item !");
setDefaultConfig("Shop.message.error.NoEnought-Coin", "&cYou have not enought coins !");
setDefaultConfig("Shop.message.error.HaveAlreadyHoe", "&cYou have already this hoe !");
setDefaultConfig("Shop.message.error.HaveBetterHoe", "&cYou have a better hoe !");
setDefaultConfig("Shop.message.error.MustHaveLowerHoe", "You must have the lower hoe !");
setDefaultConfig("Shop.message.success.NewHoe", "&aCongratulation, You have a new hoe !");
setDefaultConfig("Game.Arena.Message.Join", "[PLAYER]&e joined the arena ([NUMBER]/[MAX])");
setDefaultConfig("Game.Arena.Message.Team-Join", "[PLAYER]&e joined as [TEAM] ([NUMBER]/[MAX])");
setDefaultConfig("Game.Arena.Message.RemainTime", "&eGame Starting in [TIME] sec");
setDefaultConfig("Game.Arena.Message.ChangeTeam", "&aYou are now [TEAM] &a!");
setDefaultConfig("Game.Arena.Message.Aborde-Game", "&eA player leave the arena ! Starting Aborded!");
setDefaultConfig("Game.Arena.Message.Start", "&eLet's go ! May the Odds be ever in your favour ..");
setDefaultConfig("Game.Arena.Message.Start-Info", "&eRigh-Click with your gun to Instant-Kill other players !");
setDefaultConfig("Game.Arena.Message.Shot", "&c[SHOOTER] &8shot [KILLED]");
setDefaultConfig("Game.Arena.Message.Void", "&c[KILLED] fell out of the world !");
setDefaultConfig("Game.Arena.Message.Won", "&7[NAME] won the Game !");
setDefaultConfig("Game.Arena.Message.Team-Won", "&7[TEAM] &7won the Game !");
setDefaultConfig("Game.Arena.Message.ChangeTeamInGame", "&cYou can't change Team in Game !");
setDefaultConfig("Game.Arena.Message.NotInAGame", "&cYou are not in game !");
setDefaultConfig("Game.Arena.error.NotInTeamGame", "&cYou are not in a Team Game !");
setDefaultConfig("Game.Arena.error.BadTeamName", "&cBad Team Name !");
setDefaultConfig("Game.Arena.error.inGame", "&cGame in progress !");
setDefaultConfig("Game.Arena.error.NoSpawn", "&cWhere are no spawn !");
setDefaultConfig("Game.Arena.error.full", "&cGame is Full !");
setDefaultConfig("Game.Arena.error.VIP", "&cGame is VIP !");
setDefaultConfig("Game.Arena.error.command", "&cCommands not allowed in the arena !");
setDefaultConfig("Game.Arena.Kill.Double", "&cDouble Kill !!");
setDefaultConfig("Game.Arena.Kill.Triple", "&cTriple Kill !!!");
setDefaultConfig("Game.Arena.Kill.More", "&cEpic Kill !!!!");
_config.save(new File(_plugin.getDataFolder(), "/Language.yml"));
}
catch (IOException e) {
e.printStackTrace();
}
}
public String get(String path) {
String result = _config.getString(path);
if (result == null) {
return ChatColor.RED + path + " Undefined in config";
}
return Translate.replaceColors(result);
}
public static String replaceColors(String message) {
String s = message;
ChatColor[] arrchatColor = ChatColor.values();
int n = arrchatColor.length;
int n2 = 0;
while (n2 < n) {
ChatColor color = arrchatColor[n2];
s = s.replaceAll("(?i)&" + color.getChar(), color + "");
n2++;
}
return s;
}
}

View File

@ -0,0 +1,123 @@
package com.Geekpower14.Quake.Utils;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.Bukkit;
import org.bukkit.Location;
public class Area {
private Location _min = new Location(null, 0.0, 0.0, 0.0);
private Location _max = new Location(null, 0.0, 0.0, 0.0);
public Area(Location un, Location deux) {
if (un == null || deux == null) {
return;
}
if (un.getX() >= deux.getX()) {
_max.setX(un.getX());
_min.setX(deux.getX());
} else {
_max.setX(deux.getX());
_min.setX(un.getX());
}
if (un.getY() >= deux.getY()) {
_max.setY(un.getY());
_min.setY(deux.getY());
} else {
_max.setY(deux.getY());
_min.setY(un.getY());
}
if (un.getZ() >= deux.getZ()) {
_max.setZ(un.getZ());
_min.setZ(deux.getZ());
} else {
_max.setZ(deux.getZ());
_min.setZ(un.getZ());
}
}
public Area(List<String> src) {
if (src == null) {
return;
}
if (src.size() < 1 || src.size() > 2) {
return;
}
Location un = str2loc(src.get(0));
Location deux = str2loc(src.get(1));
if (un.getX() >= deux.getX()) {
_max.setX(un.getX());
_min.setX(deux.getX());
} else {
_max.setX(deux.getX());
_min.setX(un.getX());
}
if (un.getY() >= deux.getY()) {
_max.setY(un.getY());
_min.setY(deux.getY());
} else {
_max.setY(deux.getY());
_min.setY(un.getY());
}
if (un.getZ() >= deux.getZ()) {
_max.setZ(un.getZ());
_min.setZ(deux.getZ());
} else {
_max.setZ(deux.getZ());
_min.setZ(un.getZ());
}
}
public Location getMin() {
return _min;
}
public Location getMax() {
return _max;
}
public Boolean isInArea(Location loc) {
if (loc == null) {
return false;
}
if (loc.getX() > _max.getX() || _min.getX() > loc.getX()) {
return false;
}
if (loc.getY() > _max.getY() || _min.getY() > loc.getY()) {
return false;
}
return !(loc.getZ() > _max.getZ() || _min.getZ() > loc.getZ());
}
public Boolean isInLimit(Location loc, int range) {
if (loc == null) {
return false;
}
if (loc.getX() > _max.getX() - (double)range || _min.getX() + (double)range > loc.getX()) {
return true;
}
return loc.getZ() > _max.getZ() - (double)range || _min.getZ() + (double)range > loc.getZ();
}
public List<String> ToString() {
ArrayList<String> result = new ArrayList<>();
result.add(loc2str(_min));
result.add(loc2str(_max));
return result;
}
private Location str2loc(String loc) {
if (loc == null) {
return null;
}
Location res = null;
String[] loca = loc.split(", ");
res = new Location(Bukkit.getServer().getWorld(loca[0]), Double.parseDouble(loca[1]), Double.parseDouble(loca[2]), Double.parseDouble(loca[3]), Float.parseFloat(loca[4]), Float.parseFloat(loca[5]));
return res;
}
private String loc2str(Location loc) {
return loc.getWorld().getName() + ", " + loc.getX() + ", " + loc.getY() + ", " + loc.getZ() + ", " + loc.getYaw() + ", " + loc.getPitch();
}
}

View File

@ -0,0 +1,268 @@
/*
* Decompiled with CFR 0_114.
*
* Could not load the following classes:
* org.bukkit.configuration.ConfigurationSection
* org.bukkit.configuration.file.YamlConfiguration
* org.bukkit.configuration.file.YamlConfigurationOptions
*/
package com.Geekpower14.Quake.Utils;
import java.io.File;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.YamlConfiguration;
public class Config {
private YamlConfiguration _cfg = new YamlConfiguration();
private File _configFile;
private Map<String, Boolean> _booleans;
private Map<String, Integer> _ints;
private Map<String, Double> _doubles;
private Map<String, String> _strings;
public Config(File configFile) {
_configFile = configFile;
_booleans = new HashMap<>();
_ints = new HashMap<>();
_doubles = new HashMap<>();
_strings = new HashMap<>();
}
public void createDefaults() {
_cfg.options().indent(4);
ACFG[] arraCFG = ACFG.values();
int n = arraCFG.length;
int n2 = 0;
while (n2 < n) {
ACFG cfg = arraCFG[n2];
_cfg.addDefault(cfg.getNode(), cfg.getValue());
++n2;
}
save();
}
public boolean load() {
try {
_cfg.load(_configFile);
reloadMaps();
return true;
}
catch (Exception e) {
e.printStackTrace();
return false;
}
}
public void reloadMaps() {
for (String s : _cfg.getKeys(true)) {
Object object = _cfg.get(s);
if (object instanceof Boolean) {
_booleans.put(s, (Boolean)object);
continue;
}
if (object instanceof Integer) {
_ints.put(s, (Integer)object);
continue;
}
if (object instanceof Double) {
_doubles.put(s, (Double)object);
continue;
}
if (!(object instanceof String)) continue;
_strings.put(s, (String)object);
}
}
public boolean save() {
try {
_cfg.save(_configFile);
return true;
}
catch (Exception e) {
e.printStackTrace();
return false;
}
}
public boolean delete() {
return _configFile.delete();
}
public void setHeader(String header) {
_cfg.options().header(header);
}
public YamlConfiguration getYamlConfiguration() {
return _cfg;
}
public Object getUnsafe(String string) {
return _cfg.get(string);
}
public boolean getBoolean(ACFG cfg) {
return getBoolean(cfg, (Boolean)cfg.getValue());
}
private boolean getBoolean(ACFG cfg, boolean def) {
String path = cfg.getNode();
Boolean result = _booleans.get(path);
return result == null ? def : result;
}
public int getInt(ACFG cfg) {
return getInt(cfg, (Integer)cfg.getValue());
}
public int getInt(ACFG cfg, int def) {
String path = cfg.getNode();
Integer result = _ints.get(path);
return result == null ? def : result;
}
public double getDouble(ACFG cfg) {
return getDouble(cfg, (Double)cfg.getValue());
}
public double getDouble(ACFG cfg, double def) {
String path = cfg.getNode();
Double result = _doubles.get(path);
return result == null ? def : result;
}
public String getString(ACFG cfg) {
return getString(cfg, (String)cfg.getValue());
}
public String getString(ACFG cfg, String def) {
String path = cfg.getNode();
String result = _strings.get(path);
return result == null ? def : result;
}
public Set<String> getKeys(String path) {
if (_cfg.get(path) == null) {
return null;
}
ConfigurationSection section = _cfg.getConfigurationSection(path);
return section.getKeys(false);
}
public List<String> getStringList(String path, List<String> def) {
if (_cfg.get(path) == null) {
return def == null ? new LinkedList() : def;
}
return _cfg.getStringList(path);
}
public void setManually(String path, Object value) {
if (value instanceof Boolean) {
_booleans.put(path, (Boolean)value);
} else if (value instanceof Integer) {
_ints.put(path, (Integer)value);
} else if (value instanceof Double) {
_doubles.put(path, (Double)value);
} else if (value instanceof String) {
_strings.put(path, (String)value);
}
if (value == null) {
_booleans.remove(value);
_ints.remove(value);
_doubles.remove(value);
_strings.remove(value);
}
_cfg.set(path, value);
}
public void set(ACFG cfg, Object value) {
setManually(cfg.getNode(), value);
}
public static enum ACFG {
Z("configversion", "v0.9.0.0"),
CHAT_COLORNICK("chat.colorNick", true),
CHAT_DEFAULTTEAM("chat.defaultTeam", false),
MODULES_WORLDEDIT_AUTOLOAD("modules.worldedit.autoload", false),
MODULES_WORLDEDIT_AUTOSAVE("modules.worldedit.autosave", false);
private String _node;
private Object _value;
private String _type;
public static ACFG getByNode(String node) {
ACFG[] arraCFG = ACFG.values();
int n = arraCFG.length;
int n2 = 0;
while (n2 < n) {
ACFG m = arraCFG[n2];
if (m.getNode().equals(node)) {
return m;
}
++n2;
}
return null;
}
private ACFG(String node, String value) {
_node = node;
_value = value;
_type = "string";
}
private ACFG(String node, Boolean value) {
_node = node;
_value = value;
_type = "boolean";
}
private ACFG(String node, Integer value) {
_node = node;
_value = value;
_type = "int";
}
private ACFG(String node, Double value) {
_node = node;
_value = value;
_type = "double";
}
private ACFG(String node, List<String> value) {
_node = node;
_value = value;
_type = "list";
}
public String getNode() {
return _node;
}
public void setNode(String value) {
_node = value;
}
@Override
public String toString() {
return String.valueOf(_value);
}
public Object getValue() {
return _value;
}
public static ACFG[] getValues() {
return ACFG.values();
}
public String getType() {
return _type;
}
}
}

View File

@ -0,0 +1,84 @@
package com.Geekpower14.Quake.Utils;
import com.Geekpower14.Quake.Quake;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.bukkit.FireworkEffect;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.entity.Firework;
import org.bukkit.inventory.meta.FireworkMeta;
public class FireworkEffectPlayer {
public Quake _plugin;
private Method _world_getHandle = null;
private Method _nms_world_broadcastEntityEffect = null;
private Method _firework_getHandle = null;
public FireworkEffectPlayer(Quake pl) {
_plugin = pl;
}
public void playFirework(World world, Location loc, FireworkEffect fe) throws Exception {
Firework fw = (Firework)world.spawn(loc, (Class)Firework.class);
Object nms_world = null;
Object nms_firework = null;
if (_world_getHandle == null) {
_world_getHandle = FireworkEffectPlayer.getMethod(world.getClass(), "getHandle");
_firework_getHandle = FireworkEffectPlayer.getMethod(fw.getClass(), "getHandle");
}
nms_world = _world_getHandle.invoke(world, (Object[])null);
nms_firework = _firework_getHandle.invoke(fw, (Object[])null);
if (_nms_world_broadcastEntityEffect == null) {
_nms_world_broadcastEntityEffect = FireworkEffectPlayer.getMethod(nms_world.getClass(), "broadcastEntityEffect");
}
FireworkMeta data = fw.getFireworkMeta();
data.clearEffects();
data.setPower(1);
data.addEffect(fe);
fw.setFireworkMeta(data);
_nms_world_broadcastEntityEffect.invoke(nms_world, nms_firework, (byte)17);
fw.remove();
}
public void playFirework(World world, Location loc) throws Exception {
Firework fw = (Firework)world.spawn(loc, (Class)Firework.class);
if (_world_getHandle == null) {
_world_getHandle = FireworkEffectPlayer.getMethod(world.getClass(), "getHandle");
_firework_getHandle = FireworkEffectPlayer.getMethod(fw.getClass(), "getHandle");
}
Object nms_world = _world_getHandle.invoke(world, (Object[])null);
Object nms_firework = _firework_getHandle.invoke(fw, (Object[])null);
if (_nms_world_broadcastEntityEffect == null) {
_nms_world_broadcastEntityEffect = FireworkEffectPlayer.getMethod(nms_world.getClass(), "broadcastEntityEffect");
}
FireworkMeta data = fw.getFireworkMeta();
data.clearEffects();
data.setPower(1);
fw.setFireworkMeta(data);
try {
_nms_world_broadcastEntityEffect.invoke(nms_world, nms_firework, (byte)17);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
e.printStackTrace();
}
fw.remove();
}
private static Method getMethod(Class<?> cl, String method) {
Method[] arrmethod = cl.getMethods();
int n = arrmethod.length;
int n2 = 0;
while (n2 < n) {
Method m = arrmethod[n2];
if (m.getName().equals(method)) {
return m;
}
++n2;
}
return null;
}
}

View File

@ -0,0 +1,221 @@
package com.Geekpower14.Quake.Utils;
import java.util.Arrays;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.plugin.Plugin;
public class IconMenu implements Listener {
private String _name = null;
private int _size;
private OptionClickEventHandler _handler;
private Plugin _plugin;
private String[] _optionNames;
private String[] _optionRegs;
private ItemStack[] _optionIcons;
private boolean _autodestroy = true;
public IconMenu(String name, int size, OptionClickEventHandler handler, Plugin plugin) {
_name = name;
_size = size;
_handler = handler;
_plugin = plugin;
_optionNames = new String[size];
_optionRegs = new String[size];
_optionIcons = new ItemStack[size];
_autodestroy = true;
}
public IconMenu setOption(int position, ItemStack icon, String name, String reg, String[] info) {
_optionRegs[position] = reg;
_optionNames[position] = name;
_optionIcons[position] = setItemNameAndLore(icon, name, info);
return this;
}
public IconMenu setOption(int position, ItemStack icon, String reg) {
_optionRegs[position] = reg;
_optionNames[position] = _name;
_optionIcons[position] = icon;
return this;
}
public void open(Player player) {
Inventory inventory = Bukkit.createInventory((InventoryHolder)player, (int)_size, (String)_name);
int i = 0;
while (i < _optionIcons.length) {
if (_optionIcons[i] != null) {
inventory.setItem(i, _optionIcons[i]);
}
++i;
}
player.openInventory(inventory);
}
public void reopen(Player p) {
int i = 0;
while (i < _optionIcons.length) {
if (_optionIcons[i] != null) {
p.getOpenInventory().setItem(i, _optionIcons[i]);
}
++i;
}
}
public void setAutoDestroy(boolean autodestroy) {
_autodestroy = autodestroy;
}
public void destroy() {
try {
_handler = null;
_plugin = null;
_optionNames = null;
_optionIcons = null;
_optionRegs = null;
}
catch (Exception e) {
e.printStackTrace();
}
}
public void onInventoryClose(InventoryCloseEvent event) {
if (!event.getInventory().getName().equals(_name)) {
return;
}
if(_autodestroy) {
destroy();
}
}
public void onInventoryClick(InventoryClickEvent event) {
if (!event.getInventory().getName().equals(_name)) {
return;
}
event.setCancelled(true);
int slot = event.getRawSlot();
if (slot >= 0 && slot < _size && _optionNames[slot] != null) {
if (_optionRegs[slot].equals("") || _optionRegs[slot].trim().equals("-cancel-")) {
event.setCancelled(true);
return;
}
Plugin plugin = _plugin;
OptionClickEvent e = new OptionClickEvent((Player)event.getWhoClicked(), slot, _optionRegs[slot], this, event.isRightClick(), event.isLeftClick(), event.isShiftClick());
_handler.onOptionClick(e);
if (e.willClose()) {
final Player p = (Player)event.getWhoClicked();
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
p.closeInventory();
}
}, 1);
}
if (e.willDestroy()) {
destroy();
}
event.setCancelled(true);
}
}
private ItemStack setItemNameAndLore(ItemStack item, String name, String[] lore) {
ItemMeta im = item.getItemMeta();
if (im == null) {
return item;
}
if(!name.equals("")) {
im.setDisplayName(name);
}
if (lore != null) {
im.setLore(Arrays.asList(lore));
}
item.setItemMeta(im);
return item;
}
public int size() {
return _size;
}
public class OptionClickEvent {
private final Player _player;
private final int _position;
private final String _name;
private boolean _close;
private boolean _destroy;
private final IconMenu _im;
private final boolean _rightClick;
private final boolean _leftClick;
private boolean _Shift;
public OptionClickEvent(Player player, int position, String name, IconMenu im, boolean rightClick, boolean leftClick, boolean Shift) {
_player = player;
_position = position;
_name = name;
_close = true;
_destroy = false;
_im = im;
_rightClick = rightClick;
_leftClick = leftClick;
_Shift = Shift;
}
public Player getPlayer() {
return _player;
}
public int getPosition() {
return _position;
}
public String getName() {
return _name;
}
public IconMenu getIconMenu() {
return _im;
}
public boolean willClose() {
return _close;
}
public boolean willDestroy() {
return _destroy;
}
public void setWillClose(boolean close) {
_close = close;
}
public void setWillDestroy(boolean destroy) {
_destroy = destroy;
}
public boolean isRightClick() {
return _rightClick;
}
public boolean isLeftClick() {
return _leftClick;
}
public boolean isShiftClick() {
return _Shift;
}
}
public static interface OptionClickEventHandler {
public void onOptionClick(OptionClickEvent var1);
}
}

View File

@ -0,0 +1,172 @@
package com.Geekpower14.Quake.Utils.InvSerialization;
import java.util.Map;
import org.bukkit.Material;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.BookMeta;
import org.bukkit.inventory.meta.EnchantmentStorageMeta;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class BookSerialization {
protected BookSerialization() {
}
public static BookMeta getBookMeta(String json) {
try {
return BookSerialization.getBookMeta(new JSONObject(json));
}
catch (JSONException e) {
e.printStackTrace();
return null;
}
}
public static BookMeta getBookMeta(JSONObject json) {
try {
ItemStack dummyItems = new ItemStack(Material.WRITTEN_BOOK, 1);
BookMeta meta = (BookMeta)dummyItems.getItemMeta();
String title = null;
String author = null;
JSONArray pages = null;
if (json.has("title")) {
title = json.getString("title");
}
if (json.has("author")) {
author = json.getString("author");
}
if (json.has("pages")) {
pages = json.getJSONArray("pages");
}
if (title != null) {
meta.setTitle(title);
}
if (author != null) {
meta.setAuthor(author);
}
if (pages != null) {
String[] allPages = new String[pages.length()];
for (int i = 0; i < pages.length(); ++i) {
String page = pages.getString(i);
if (page.isEmpty() || page == null) {
page = "";
}
allPages[i] = page;
}
meta.setPages(allPages);
}
return meta;
}
catch (JSONException e) {
e.printStackTrace();
return null;
}
}
public static JSONObject serializeBookMeta(BookMeta meta) {
try {
JSONObject root = new JSONObject();
if (meta.hasTitle()) {
root.put("title", meta.getTitle());
}
if (meta.hasAuthor()) {
root.put("author", meta.getAuthor());
}
if (meta.hasPages()) {
String[] pages = meta.getPages().toArray(new String[0]);
root.put("pages", pages);
}
return root;
}
catch (JSONException e) {
e.printStackTrace();
return null;
}
}
public static String serializeBookMetaAsString(BookMeta meta) {
return BookSerialization.serializeBookMetaAsString(meta, false);
}
public static String serializeBookMetaAsString(BookMeta meta, boolean pretty) {
return BookSerialization.serializeBookMetaAsString(meta, pretty, 5);
}
public static String serializeBookMetaAsString(BookMeta meta, boolean pretty, int indentFactor) {
try {
if (pretty) {
return BookSerialization.serializeBookMeta(meta).toString(indentFactor);
}
return BookSerialization.serializeBookMeta(meta).toString();
}
catch (JSONException e) {
e.printStackTrace();
return null;
}
}
public static EnchantmentStorageMeta getEnchantedBookMeta(String json) {
try {
return BookSerialization.getEnchantedBookMeta(new JSONObject(json));
}
catch (JSONException e) {
e.printStackTrace();
return null;
}
}
public static EnchantmentStorageMeta getEnchantedBookMeta(JSONObject json) {
try {
ItemStack dummyItems = new ItemStack(Material.ENCHANTED_BOOK, 1);
EnchantmentStorageMeta meta = (EnchantmentStorageMeta)dummyItems.getItemMeta();
if (json.has("enchantments")) {
Map<Enchantment, Integer> enchants = EnchantmentSerialization.getEnchantments(json.getString("enchantments"));
for (Enchantment e : enchants.keySet()) {
meta.addStoredEnchant(e, enchants.get((Object)e).intValue(), true);
}
}
return meta;
}
catch (JSONException e) {
e.printStackTrace();
return null;
}
}
public static JSONObject serializeEnchantedBookMeta(EnchantmentStorageMeta meta) {
try {
JSONObject root = new JSONObject();
String enchants = EnchantmentSerialization.serializeEnchantments(meta.getStoredEnchants());
root.put("enchantments", enchants);
return root;
}
catch (JSONException e) {
e.printStackTrace();
return null;
}
}
public static String serializeEnchantedBookMetaAsString(EnchantmentStorageMeta meta) {
return BookSerialization.serializeEnchantedBookMetaAsString(meta, false);
}
public static String serializeEnchantedBookMetaAsString(EnchantmentStorageMeta meta, boolean pretty) {
return BookSerialization.serializeEnchantedBookMetaAsString(meta, pretty, 5);
}
public static String serializeEnchantedBookMetaAsString(EnchantmentStorageMeta meta, boolean pretty, int indentFactor) {
try {
if (pretty) {
return BookSerialization.serializeEnchantedBookMeta(meta).toString(indentFactor);
}
return BookSerialization.serializeEnchantedBookMeta(meta).toString();
}
catch (JSONException e) {
e.printStackTrace();
return null;
}
}
}

View File

@ -0,0 +1,78 @@
package com.Geekpower14.Quake.Utils.InvSerialization;
import org.bukkit.Color;
import org.json.JSONException;
import org.json.JSONObject;
public class ColorSerialization {
protected ColorSerialization() {
}
public static JSONObject serializeColor(Color color) {
try {
JSONObject root = new JSONObject();
root.put("red", color.getRed());
root.put("green", color.getGreen());
root.put("blue", color.getBlue());
return root;
}
catch (JSONException e) {
e.printStackTrace();
return null;
}
}
public static Color getColor(String color) {
try {
return ColorSerialization.getColor(new JSONObject(color));
}
catch (JSONException e) {
e.printStackTrace();
return null;
}
}
public static Color getColor(JSONObject color) {
try {
int r = 0;
int g = 0;
int b = 0;
if (color.has("red")) {
r = color.getInt("red");
}
if (color.has("green")) {
g = color.getInt("green");
}
if (color.has("blue")) {
b = color.getInt("blue");
}
return Color.fromRGB((int)r, (int)g, (int)b);
}
catch (JSONException e) {
e.printStackTrace();
return null;
}
}
public static String serializeColorAsString(Color color) {
return ColorSerialization.serializeColorAsString(color, false);
}
public static String serializeColorAsString(Color color, boolean pretty) {
return ColorSerialization.serializeColorAsString(color, pretty, 5);
}
public static String serializeColorAsString(Color color, boolean pretty, int indentFactor) {
try {
if (pretty) {
return ColorSerialization.serializeColor(color).toString(indentFactor);
}
return ColorSerialization.serializeColor(color).toString();
}
catch (JSONException e) {
e.printStackTrace();
return null;
}
}
}

View File

@ -0,0 +1,78 @@
package com.Geekpower14.Quake.Utils.InvSerialization;
import java.util.HashMap;
import java.util.Map;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.inventory.ItemStack;
public class EnchantmentSerialization {
protected EnchantmentSerialization() {
}
public static String serializeEnchantments(Map<Enchantment, Integer> enchantments) {
String serialized = "";
for (Enchantment e : enchantments.keySet()) {
serialized = serialized + e.getId() + ":" + enchantments.get((Object)e) + ";";
}
return serialized;
}
public static Map<Enchantment, Integer> getEnchantments(String serializedEnchants) {
HashMap<Enchantment, Integer> enchantments = new HashMap<Enchantment, Integer>();
if (serializedEnchants.isEmpty()) {
return enchantments;
}
String[] enchants = serializedEnchants.split(";");
for (int i = 0; i < enchants.length; ++i) {
String[] ench = enchants[i].split(":");
if (ench.length < 2) {
throw new IllegalArgumentException(serializedEnchants + " - Enchantment " + i + " (" + enchants[i] + "): split must at least have a length of 2");
}
if (!Util.isNum(ench[0])) {
throw new IllegalArgumentException(serializedEnchants + " - Enchantment " + i + " (" + enchants[i] + "): id is not an integer");
}
if (!Util.isNum(ench[1])) {
throw new IllegalArgumentException(serializedEnchants + " - Enchantment " + i + " (" + enchants[i] + "): level is not an integer");
}
int id = Integer.parseInt(ench[0]);
int level = Integer.parseInt(ench[1]);
Enchantment e = Enchantment.getById((int)id);
if (e == null) {
throw new IllegalArgumentException(serializedEnchants + " - Enchantment " + i + " (" + enchants[i] + "): no Enchantment with id of " + id);
}
enchantments.put(e, level);
}
return enchantments;
}
public static Map<Enchantment, Integer> getEnchantsFromOldFormat(String oldFormat) {
HashMap<Enchantment, Integer> enchants = new HashMap<Enchantment, Integer>();
if (oldFormat.length() == 0) {
return enchants;
}
String nums = "" + Long.parseLong(oldFormat, 32) + "";
System.out.println(nums);
for (int i = 0; i < nums.length(); i += 3) {
int enchantId = Integer.parseInt(nums.substring(i, i + 2));
int enchantLevel = Integer.parseInt("" + nums.charAt(i + 2) + "");
Enchantment ench = Enchantment.getById((int)enchantId);
enchants.put(ench, enchantLevel);
}
return enchants;
}
public static String convert(String oldFormat) {
Map<Enchantment, Integer> enchants = EnchantmentSerialization.getEnchantsFromOldFormat(oldFormat);
return EnchantmentSerialization.serializeEnchantments(enchants);
}
public static Map<Enchantment, Integer> convertAndGetEnchantments(String oldFormat) {
String newFormat = EnchantmentSerialization.convert(oldFormat);
return EnchantmentSerialization.getEnchantments(newFormat);
}
public static void addEnchantments(String code, ItemStack items) {
items.addUnsafeEnchantments(EnchantmentSerialization.getEnchantments(code));
}
}

View File

@ -0,0 +1,79 @@
package com.Geekpower14.Quake.Utils.InvSerialization;
import org.bukkit.Color;
import org.bukkit.FireworkEffect;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class FireworkEffectSerialization {
protected FireworkEffectSerialization() {
}
public static FireworkEffect getFireworkEffect(String json) {
return FireworkEffectSerialization.getFireworkEffect(json);
}
public static FireworkEffect getFireworkEffect(JSONObject json) {
try {
FireworkEffect.Builder builder = FireworkEffect.builder();
JSONArray colors = json.getJSONArray("colors");
for (int j = 0; j < colors.length(); ++j) {
builder.withColor(ColorSerialization.getColor(colors.getJSONObject(j)));
}
JSONArray fadeColors = json.getJSONArray("fade-colors");
for (int j2 = 0; j2 < fadeColors.length(); ++j2) {
builder.withFade(ColorSerialization.getColor(colors.getJSONObject(j2)));
}
if (json.getBoolean("flicker")) {
builder.withFlicker();
}
if (json.getBoolean("trail")) {
builder.withTrail();
}
builder.with(FireworkEffect.Type.valueOf((String)json.getString("type")));
return builder.build();
}
catch (IllegalArgumentException | JSONException e) {
e.printStackTrace();
}
return null;
}
public static JSONObject serializeFireworkEffect(FireworkEffect effect) {
try {
JSONObject root = new JSONObject();
JSONArray colors = new JSONArray();
for (Object c : effect.getColors()) {
colors.put(ColorSerialization.serializeColor((Color)c));
}
root.put("colors", colors);
JSONArray fadeColors = new JSONArray();
for (Color c2 : effect.getFadeColors()) {
fadeColors.put(ColorSerialization.serializeColor(c2));
}
root.put("fade-colors", fadeColors);
root.put("flicker", effect.hasFlicker());
root.put("trail", effect.hasTrail());
root.put("type", effect.getType().name());
return root;
}
catch (JSONException e) {
e.printStackTrace();
return null;
}
}
public static String serializeFireworkEffectAsString(FireworkEffect effect) {
return FireworkEffectSerialization.serializeFireworkEffectAsString(effect, false);
}
public static String serializeFireworkEffectAsString(FireworkEffect effect, boolean pretty) {
return FireworkEffectSerialization.serializeFireworkEffectAsString(effect, false, 5);
}
public static String serializeFireworkEffectAsString(FireworkEffect effect, boolean pretty, int indentFactor) {
return Serializer.toString(FireworkEffectSerialization.serializeFireworkEffect(effect), pretty, indentFactor);
}
}

View File

@ -0,0 +1,67 @@
package com.Geekpower14.Quake.Utils.InvSerialization;
import org.bukkit.FireworkEffect;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.FireworkMeta;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class FireworkSerialization {
protected FireworkSerialization() {
}
public static FireworkMeta getFireworkMeta(String json) {
return FireworkSerialization.getFireworkMeta(json);
}
public static FireworkMeta getFireworkMeta(JSONObject json) {
try {
FireworkMeta dummy = (FireworkMeta)new ItemStack(Material.FIREWORK).getItemMeta();
dummy.setPower(json.optInt("power", 1));
JSONArray effects = json.getJSONArray("effects");
for (int i = 0; i < effects.length(); ++i) {
JSONObject effectDto = effects.getJSONObject(i);
FireworkEffect effect = FireworkEffectSerialization.getFireworkEffect(effectDto);
if (effect == null) continue;
dummy.addEffect(effect);
}
return dummy;
}
catch (JSONException e) {
e.printStackTrace();
return null;
}
}
public static JSONObject serializeFireworkMeta(FireworkMeta meta) {
try {
JSONObject root = new JSONObject();
root.put("power", meta.getPower());
JSONArray effects = new JSONArray();
for (FireworkEffect e : meta.getEffects()) {
effects.put(FireworkEffectSerialization.serializeFireworkEffect(e));
}
root.put("effects", effects);
return root;
}
catch (JSONException e) {
e.printStackTrace();
return null;
}
}
public static String serializeFireworkMetaAsString(FireworkMeta meta) {
return FireworkSerialization.serializeFireworkMetaAsString(meta, false);
}
public static String serializeFireworkMetaAsString(FireworkMeta meta, boolean pretty) {
return FireworkSerialization.serializeFireworkMetaAsString(meta, false, 5);
}
public static String serializeFireworkMetaAsString(FireworkMeta meta, boolean pretty, int indentFactor) {
return Serializer.toString(FireworkSerialization.serializeFireworkMeta(meta), pretty, indentFactor);
}
}

View File

@ -0,0 +1,101 @@
package com.Geekpower14.Quake.Utils.InvSerialization;
import org.bukkit.Location;
import org.bukkit.entity.Horse;
import org.bukkit.entity.LivingEntity;
import org.bukkit.inventory.Inventory;
import org.json.JSONException;
import org.json.JSONObject;
public class HorseSerialization {
protected HorseSerialization() {
}
public static JSONObject serializeHorse(Horse horse) {
try {
JSONObject root = LivingEntitySerialization.serializeEntity((LivingEntity)horse);
if (HorseSerialization.shouldSerialize("color")) {
root.put("color", horse.getColor().name());
}
if (HorseSerialization.shouldSerialize("inventory")) {
root.put("inventory", InventorySerialization.serializeInventory((Inventory)horse.getInventory()));
}
if (HorseSerialization.shouldSerialize("jump-strength")) {
root.put("jump-strength", horse.getJumpStrength());
}
if (HorseSerialization.shouldSerialize("style")) {
root.put("style", (Object)horse.getStyle());
}
if (HorseSerialization.shouldSerialize("variant")) {
root.put("variant", (Object)horse.getVariant());
}
return root;
}
catch (JSONException e) {
e.printStackTrace();
return null;
}
}
public static String serializeHorseAsString(Horse horse) {
return HorseSerialization.serializeHorseAsString(horse, false);
}
public static String serializeHorseAsString(Horse horse, boolean pretty) {
return HorseSerialization.serializeHorseAsString(horse, pretty, 5);
}
public static String serializeHorseAsString(Horse horse, boolean pretty, int indentFactor) {
try {
if (pretty) {
return HorseSerialization.serializeHorse(horse).toString(indentFactor);
}
return HorseSerialization.serializeHorse(horse).toString();
}
catch (JSONException e) {
e.printStackTrace();
return null;
}
}
public static Horse spawnHorse(Location location, String stats) {
try {
return HorseSerialization.spawnHorse(location, new JSONObject(stats));
}
catch (JSONException e) {
e.printStackTrace();
return null;
}
}
public static Horse spawnHorse(Location location, JSONObject stats) {
try {
Horse horse = (Horse)LivingEntitySerialization.spawnEntity(location, stats);
if (stats.has("color")) {
horse.setColor(Horse.Color.valueOf((String)stats.getString("color")));
}
if (stats.has("jump-strength")) {
horse.setCustomName(stats.getString("name"));
}
if (stats.has("style")) {
horse.setStyle(Horse.Style.valueOf((String)stats.getString("style")));
}
if (stats.has("inventory")) {
PotionEffectSerialization.addPotionEffects(stats.getString("potion-effects"), (LivingEntity)horse);
}
if (stats.has("variant")) {
horse.setVariant(Horse.Variant.valueOf((String)stats.getString("variant")));
}
return horse;
}
catch (JSONException e) {
e.printStackTrace();
return null;
}
}
public static boolean shouldSerialize(String key) {
return SerializationConfig.getShouldSerialize("horse." + key);
}
}

View File

@ -0,0 +1,216 @@
package com.Geekpower14.Quake.Utils.InvSerialization;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class InventorySerialization {
protected InventorySerialization() {
}
public static JSONArray serializeInventory(Inventory inv) {
JSONArray inventory = new JSONArray();
for (int i = 0; i < inv.getSize(); ++i) {
JSONObject values = SingleItemSerialization.serializeItemInInventory(inv.getItem(i), i);
if (values == null)
continue;
inventory.put(values);
}
return inventory;
}
public static JSONObject serializePlayerInventory(PlayerInventory inv) {
try {
JSONObject root = new JSONObject();
JSONArray inventory = InventorySerialization.serializeInventory((Inventory)inv);
JSONArray armor = InventorySerialization.serializeInventory(inv.getArmorContents());
root.put("inventory", inventory);
root.put("armor", armor);
return root;
}
catch (JSONException e) {
e.printStackTrace();
return null;
}
}
public static String serializePlayerInventoryAsString(PlayerInventory inv) {
return InventorySerialization.serializePlayerInventoryAsString(inv, false);
}
public static String serializePlayerInventoryAsString(PlayerInventory inv, boolean pretty) {
return InventorySerialization.serializePlayerInventoryAsString(inv, pretty, 5);
}
public static String serializePlayerInventoryAsString(PlayerInventory inv, boolean pretty, int indentFactor) {
try {
if (pretty) {
return InventorySerialization.serializePlayerInventory(inv).toString(indentFactor);
}
return InventorySerialization.serializePlayerInventory(inv).toString();
}
catch (JSONException e) {
e.printStackTrace();
return null;
}
}
public static String serializeInventoryAsString(Inventory inventory) {
return InventorySerialization.serializeInventoryAsString(inventory, false);
}
public static String serializeInventoryAsString(Inventory inventory, boolean pretty) {
return InventorySerialization.serializeInventoryAsString(inventory, pretty, 5);
}
public static String serializeInventoryAsString(Inventory inventory, boolean pretty, int indentFactor) {
try {
if (pretty) {
return InventorySerialization.serializeInventory(inventory).toString(indentFactor);
}
return InventorySerialization.serializeInventory(inventory).toString();
}
catch (JSONException e) {
e.printStackTrace();
return null;
}
}
public static String serializeInventoryAsString(ItemStack[] contents) {
return InventorySerialization.serializeInventoryAsString(contents, false);
}
public static String serializeInventoryAsString(ItemStack[] contents, boolean pretty) {
return InventorySerialization.serializeInventoryAsString(contents, pretty, 5);
}
public static String serializeInventoryAsString(ItemStack[] contents, boolean pretty, int indentFactor) {
try {
if (pretty) {
return InventorySerialization.serializeInventory(contents).toString(indentFactor);
}
return InventorySerialization.serializeInventory(contents).toString();
}
catch (JSONException e) {
e.printStackTrace();
return null;
}
}
public static JSONArray serializeInventory(ItemStack[] contents) {
JSONArray inventory = new JSONArray();
for (int i = 0; i < contents.length; ++i) {
JSONObject values = SingleItemSerialization.serializeItemInInventory(contents[i], i);
if (values == null) continue;
inventory.put(values);
}
return inventory;
}
public static ItemStack[] getInventory(String json, int size) {
try {
return InventorySerialization.getInventory(new JSONArray(json), size);
}
catch (JSONException e) {
e.printStackTrace();
return null;
}
}
public static ItemStack[] getInventory(JSONArray inv, int size) {
try {
ItemStack[] contents = new ItemStack[size];
for (int i = 0; i < inv.length(); ++i) {
ItemStack stuff;
JSONObject item = inv.getJSONObject(i);
int index = item.getInt("index");
if (index > size) {
throw new IllegalArgumentException("index found is greator than expected size (" + index + ">" + size + ")");
}
if (index > contents.length || index < 0) {
throw new IllegalArgumentException("Item " + i + " - Slot " + index + " does not exist in this inventory");
}
contents[index] = stuff = SingleItemSerialization.getItem(item);
}
return contents;
}
catch (JSONException e) {
e.printStackTrace();
return null;
}
}
public static ItemStack[] getInventory(File jsonFile, int size) {
String source = "";
try {
Scanner x = new Scanner(jsonFile);
while (x.hasNextLine()) {
source = source + x.nextLine() + "\n";
}
x.close();
return InventorySerialization.getInventory(source, size);
}
catch (FileNotFoundException e) {
e.printStackTrace();
return null;
}
}
public static void setInventory(InventoryHolder holder, String inv) {
InventorySerialization.setInventory(holder.getInventory(), inv);
}
public static void setInventory(InventoryHolder holder, JSONArray inv) {
InventorySerialization.setInventory(holder.getInventory(), inv);
}
public static void setInventory(Inventory inventory, String inv) {
try {
InventorySerialization.setInventory(inventory, new JSONArray(inv));
}
catch (JSONException e) {
e.printStackTrace();
}
}
public static void setInventory(Inventory inventory, JSONArray inv) {
ItemStack[] items = InventorySerialization.getInventory(inv, inventory.getSize());
inventory.clear();
for (int i = 0; i < items.length; ++i) {
ItemStack item = items[i];
if (item == null) continue;
inventory.setItem(i, item);
}
}
public static void setPlayerInventory(Player player, String inv) {
try {
InventorySerialization.setPlayerInventory(player, new JSONObject(inv));
}
catch (JSONException e) {
e.printStackTrace();
}
}
public static void setPlayerInventory(Player player, JSONObject inv) {
try {
PlayerInventory inventory = player.getInventory();
ItemStack[] armor = InventorySerialization.getInventory(inv.getJSONArray("armor"), 4);
inventory.clear();
inventory.setArmorContents(armor);
InventorySerialization.setInventory((InventoryHolder)player, inv.getJSONArray("inventory"));
}
catch (JSONException e) {
e.printStackTrace();
}
}
}

View File

@ -0,0 +1,71 @@
package com.Geekpower14.Quake.Utils.InvSerialization;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.LeatherArmorMeta;
import org.json.JSONException;
import org.json.JSONObject;
public class LeatherArmorSerialization {
protected LeatherArmorSerialization() {
}
public static JSONObject serializeArmor(LeatherArmorMeta meta) {
try {
JSONObject root = new JSONObject();
root.put("color", ColorSerialization.serializeColor(meta.getColor()));
return root;
}
catch (JSONException e) {
e.printStackTrace();
return null;
}
}
public static String serializeArmorAsString(LeatherArmorMeta meta) {
return LeatherArmorSerialization.serializeArmorAsString(meta, false);
}
public static String serializeArmorAsString(LeatherArmorMeta meta, boolean pretty) {
return LeatherArmorSerialization.serializeArmorAsString(meta, pretty, 5);
}
public static String serializeArmorAsString(LeatherArmorMeta meta, boolean pretty, int indentFactor) {
try {
if (pretty) {
return LeatherArmorSerialization.serializeArmor(meta).toString(indentFactor);
}
return LeatherArmorSerialization.serializeArmor(meta).toString();
}
catch (JSONException e) {
e.printStackTrace();
return null;
}
}
public static LeatherArmorMeta getLeatherArmorMeta(String json) {
try {
return LeatherArmorSerialization.getLeatherArmorMeta(new JSONObject(json));
}
catch (JSONException e) {
e.printStackTrace();
return null;
}
}
public static LeatherArmorMeta getLeatherArmorMeta(JSONObject json) {
try {
ItemStack dummyItems = new ItemStack(Material.LEATHER_HELMET, 1);
LeatherArmorMeta meta = (LeatherArmorMeta)dummyItems.getItemMeta();
if (json.has("color")) {
meta.setColor(ColorSerialization.getColor(json.getJSONObject("color")));
}
return meta;
}
catch (JSONException e) {
e.printStackTrace();
return null;
}
}
}

View File

@ -0,0 +1,104 @@
package com.Geekpower14.Quake.Utils.InvSerialization;
import org.bukkit.Location;
import org.bukkit.entity.Ageable;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.json.JSONException;
import org.json.JSONObject;
public class LivingEntitySerialization {
protected LivingEntitySerialization() {
}
public static JSONObject serializeEntity(LivingEntity entity) {
if (entity instanceof Player) {
return PlayerSerialization.serializePlayer((Player)entity);
}
try {
JSONObject root = new JSONObject();
if (LivingEntitySerialization.shouldSerialize("age") && entity instanceof Ageable) {
root.put("age", ((Ageable)entity).getAge());
}
if (LivingEntitySerialization.shouldSerialize("health")) {
root.put("health", entity.getHealth());
}
if (LivingEntitySerialization.shouldSerialize("name")) {
root.put("name", entity.getCustomName());
}
if (LivingEntitySerialization.shouldSerialize("potion-effects")) {
root.put("potion-effects", PotionEffectSerialization.serializeEffects(entity.getActivePotionEffects()));
}
root.put("type", entity.getType().getTypeId());
return root;
}
catch (JSONException e) {
e.printStackTrace();
return null;
}
}
public static String serializeEntityAsString(LivingEntity entity) {
return LivingEntitySerialization.serializeEntityAsString(entity, false);
}
public static String serializeEntityAsString(LivingEntity entity, boolean pretty) {
return LivingEntitySerialization.serializeEntityAsString(entity, pretty, 5);
}
public static String serializeEntityAsString(LivingEntity entity, boolean pretty, int indentFactor) {
try {
if (pretty) {
return LivingEntitySerialization.serializeEntity(entity).toString(indentFactor);
}
return LivingEntitySerialization.serializeEntity(entity).toString();
}
catch (JSONException e) {
e.printStackTrace();
return null;
}
}
public static LivingEntity spawnEntity(Location location, String stats) {
try {
return LivingEntitySerialization.spawnEntity(location, new JSONObject(stats));
}
catch (JSONException e) {
e.printStackTrace();
return null;
}
}
public static LivingEntity spawnEntity(Location location, JSONObject stats) {
try {
if (!stats.has("type")) {
throw new IllegalArgumentException("The type of the entity cannot be determined");
}
LivingEntity entity = (LivingEntity)location.getWorld().spawnEntity(location, EntityType.fromId((int)stats.getInt("type")));
if (stats.has("age") && entity instanceof Ageable) {
((Ageable)entity).setAge(stats.getInt("age"));
}
if (stats.has("health")) {
entity.setHealth(stats.getDouble("health"));
}
if (stats.has("name")) {
entity.setCustomName(stats.getString("name"));
}
if (stats.has("potion-effects")) {
// empty if block
}
PotionEffectSerialization.addPotionEffects(stats.getString("potion-effects"), entity);
return entity;
}
catch (JSONException e) {
e.printStackTrace();
return null;
}
}
public static boolean shouldSerialize(String key) {
return SerializationConfig.getShouldSerialize("living-entity." + key);
}
}

View File

@ -0,0 +1,76 @@
package com.Geekpower14.Quake.Utils.InvSerialization;
import org.bukkit.Location;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Ocelot;
import org.json.JSONException;
import org.json.JSONObject;
public class OcelotSerialization {
protected OcelotSerialization() {
}
public static JSONObject serializeOcelot(Ocelot ocelot) {
try {
JSONObject root = LivingEntitySerialization.serializeEntity((LivingEntity)ocelot);
if (OcelotSerialization.shouldSerialize("type")) {
root.put("type", ocelot.getCatType().name());
}
return root;
}
catch (JSONException e) {
e.printStackTrace();
return null;
}
}
public static String serializeOcelotAsString(Ocelot ocelot) {
return OcelotSerialization.serializeOcelotAsString(ocelot, false);
}
public static String serializeOcelotAsString(Ocelot ocelot, boolean pretty) {
return OcelotSerialization.serializeOcelotAsString(ocelot, pretty, 5);
}
public static String serializeOcelotAsString(Ocelot ocelot, boolean pretty, int indentFactor) {
try {
if (pretty) {
return OcelotSerialization.serializeOcelot(ocelot).toString(indentFactor);
}
return OcelotSerialization.serializeOcelot(ocelot).toString();
}
catch (JSONException e) {
e.printStackTrace();
return null;
}
}
public static Ocelot spawnOcelot(Location location, String stats) {
try {
return OcelotSerialization.spawnOcelot(location, new JSONObject(stats));
}
catch (JSONException e) {
e.printStackTrace();
return null;
}
}
public static Ocelot spawnOcelot(Location location, JSONObject stats) {
try {
Ocelot ocelot = (Ocelot)LivingEntitySerialization.spawnEntity(location, stats);
if (stats.has("type")) {
ocelot.setCatType(Ocelot.Type.valueOf((String)stats.getString("type")));
}
return ocelot;
}
catch (JSONException e) {
e.printStackTrace();
return null;
}
}
public static boolean shouldSerialize(String key) {
return SerializationConfig.getShouldSerialize("ocelot." + key);
}
}

View File

@ -0,0 +1,82 @@
package com.Geekpower14.Quake.Utils.InvSerialization;
import org.bukkit.entity.Player;
import org.json.JSONException;
import org.json.JSONObject;
public class PlayerSerialization {
protected PlayerSerialization() {
}
public static JSONObject serializePlayer(Player player) {
try {
JSONObject root = new JSONObject();
if (SerializationConfig.getShouldSerialize("player-ender-chest")) {
root.put("ender-chest", InventorySerialization.serializeInventory(player.getEnderChest()));
}
if (SerializationConfig.getShouldSerialize("player.inventory")) {
root.put("inventory", InventorySerialization.serializePlayerInventory(player.getInventory()));
}
if (SerializationConfig.getShouldSerialize("player.stats")) {
root.put("stats", PlayerStatsSerialization.serializePlayerStats(player));
}
return root;
}
catch (JSONException e) {
e.printStackTrace();
return null;
}
}
public static String serializePlayerAsString(Player player) {
return PlayerSerialization.serializePlayerAsString(player, false);
}
public static String serializePlayerAsString(Player player, boolean pretty) {
return PlayerSerialization.serializePlayerAsString(player, pretty, 5);
}
public static String serializePlayerAsString(Player player, boolean pretty, int indentFactor) {
try {
if (pretty) {
return PlayerSerialization.serializePlayer(player).toString(indentFactor);
}
return PlayerSerialization.serializePlayer(player).toString();
}
catch (JSONException e) {
e.printStackTrace();
return null;
}
}
public static void setPlayer(String meta, Player player) {
try {
PlayerSerialization.setPlayer(new JSONObject(meta), player);
}
catch (JSONException e) {
e.printStackTrace();
}
}
public static void setPlayer(JSONObject meta, Player player) {
try {
if (meta.has("ender-chest")) {
InventorySerialization.setInventory(player.getEnderChest(), meta.getJSONArray("ender-chest"));
}
if (meta.has("inventory")) {
InventorySerialization.setPlayerInventory(player, meta.getJSONObject("inventory"));
}
if (meta.has("stats")) {
PlayerStatsSerialization.applyPlayerStats(player, meta.getJSONObject("stats"));
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
public static boolean shouldSerialize(String key) {
return SerializationConfig.getShouldSerialize("player." + key);
}
}

View File

@ -0,0 +1,132 @@
package com.Geekpower14.Quake.Utils.InvSerialization;
import org.bukkit.GameMode;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.json.JSONException;
import org.json.JSONObject;
public class PlayerStatsSerialization {
protected PlayerStatsSerialization() {
}
public static JSONObject serializePlayerStats(Player player) {
try {
JSONObject root = new JSONObject();
if (PlayerStatsSerialization.shouldSerialize("can-fly")) {
root.put("can-fly", player.getAllowFlight());
}
if (PlayerStatsSerialization.shouldSerialize("display-name")) {
root.put("display-name", player.getDisplayName());
}
if (PlayerStatsSerialization.shouldSerialize("exhaustion")) {
root.put("exhaustion", player.getExhaustion());
}
if (PlayerStatsSerialization.shouldSerialize("exp")) {
root.put("exp", player.getExp());
}
if (PlayerStatsSerialization.shouldSerialize("flying")) {
root.put("flying", player.isFlying());
}
if (PlayerStatsSerialization.shouldSerialize("food")) {
root.put("food", player.getFoodLevel());
}
if (PlayerStatsSerialization.shouldSerialize("gamemode")) {
root.put("gamemode", player.getGameMode().ordinal());
}
if (PlayerStatsSerialization.shouldSerialize("health")) {
root.put("health", player.getHealthScale());
}
if (PlayerStatsSerialization.shouldSerialize("level")) {
root.put("level", player.getLevel());
}
if (PlayerStatsSerialization.shouldSerialize("potion-effects")) {
root.put("potion-effects", PotionEffectSerialization.serializeEffects(player.getActivePotionEffects()));
}
if (PlayerStatsSerialization.shouldSerialize("saturation")) {
root.put("saturation", player.getSaturation());
}
return root;
}
catch (JSONException e) {
e.printStackTrace();
return null;
}
}
public static String serializePlayerStatsAsString(Player player) {
return PlayerStatsSerialization.serializePlayerStatsAsString(player, false);
}
public static String serializePlayerStatsAsString(Player player, boolean pretty) {
return PlayerStatsSerialization.serializePlayerStatsAsString(player, pretty, 5);
}
public static String serializePlayerStatsAsString(Player player, boolean pretty, int indentFactor) {
try {
if (pretty) {
return PlayerStatsSerialization.serializePlayerStats(player).toString(indentFactor);
}
return PlayerStatsSerialization.serializePlayerStats(player).toString();
}
catch (JSONException e) {
e.printStackTrace();
return null;
}
}
public static void applyPlayerStats(Player player, String stats) {
try {
PlayerStatsSerialization.applyPlayerStats(player, new JSONObject(stats));
}
catch (JSONException e) {
e.printStackTrace();
}
}
public static void applyPlayerStats(Player player, JSONObject stats) {
try {
if (stats.has("can-fly")) {
player.setAllowFlight(stats.getBoolean("can-fly"));
}
if (stats.has("display-name")) {
player.setDisplayName(stats.getString("display-name"));
}
if (stats.has("exhaustion")) {
player.setExhaustion((float)stats.getDouble("exhaustion"));
}
if (stats.has("exp")) {
player.setExp((float)stats.getDouble("exp"));
}
if (stats.has("flying")) {
player.setFlying(stats.getBoolean("flying"));
}
if (stats.has("food")) {
player.setFoodLevel(stats.getInt("food"));
}
if (stats.has("health")) {
player.setHealth(stats.getDouble("health"));
}
if (stats.has("gamemode")) {
player.setGameMode(GameMode.getByValue((int)stats.getInt("gamemode")));
}
if (stats.has("level")) {
player.setLevel(stats.getInt("level"));
}
if (stats.has("potion-effects")) {
PotionEffectSerialization.setPotionEffects(stats.getString("potion-effects"), (LivingEntity)player);
}
if (stats.has("saturation")) {
player.setSaturation((float)stats.getDouble("saturation"));
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
public static boolean shouldSerialize(String key) {
return SerializationConfig.getShouldSerialize("player-stats." + key);
}
}

View File

@ -0,0 +1,65 @@
package com.Geekpower14.Quake.Utils.InvSerialization;
import java.util.ArrayList;
import java.util.Collection;
import org.bukkit.entity.LivingEntity;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
public class PotionEffectSerialization {
protected PotionEffectSerialization() {
}
public static String serializeEffects(Collection<PotionEffect> effects) {
String serialized = "";
for (PotionEffect e : effects) {
serialized = serialized + e.getType().getId() + ":" + e.getDuration() + ":" + e.getAmplifier() + ";";
}
return serialized;
}
public static Collection<PotionEffect> getPotionEffects(String serializedEffects) {
ArrayList<PotionEffect> effects = new ArrayList<PotionEffect>();
if (serializedEffects.isEmpty()) {
return effects;
}
String[] effs = serializedEffects.split(";");
for (int i = 0; i < effs.length; ++i) {
String[] effect = effs[i].split(":");
if (effect.length < 3) {
throw new IllegalArgumentException(serializedEffects + " - PotionEffect " + i + " (" + effs[i] + "): split must at least have a length of 3");
}
if (!Util.isNum(effect[0])) {
throw new IllegalArgumentException(serializedEffects + " - PotionEffect " + i + " (" + effs[i] + "): id is not an integer");
}
if (!Util.isNum(effect[1])) {
throw new IllegalArgumentException(serializedEffects + " - PotionEffect " + i + " (" + effs[i] + "): duration is not an integer");
}
if (!Util.isNum(effect[2])) {
throw new IllegalArgumentException(serializedEffects + " - PotionEffect " + i + " (" + effs[i] + "): amplifier is not an integer");
}
int id = Integer.parseInt(effect[0]);
int duration = Integer.parseInt(effect[1]);
int amplifier = Integer.parseInt(effect[2]);
PotionEffectType effectType = PotionEffectType.getById((int)id);
if (effectType == null) {
throw new IllegalArgumentException(serializedEffects + " - PotionEffect " + i + " (" + effs[i] + "): no PotionEffectType with id of " + id);
}
PotionEffect e = new PotionEffect(effectType, duration, amplifier);
effects.add(e);
}
return effects;
}
public static void addPotionEffects(String code, LivingEntity entity) {
entity.addPotionEffects(PotionEffectSerialization.getPotionEffects(code));
}
public static void setPotionEffects(String code, LivingEntity entity) {
for (PotionEffect effect : entity.getActivePotionEffects()) {
entity.removePotionEffect(effect.getType());
}
PotionEffectSerialization.addPotionEffects(code, entity);
}
}

View File

@ -0,0 +1,85 @@
package com.Geekpower14.Quake.Utils.InvSerialization;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bukkit.Bukkit;
import org.bukkit.configuration.file.YamlConfiguration;
public class SerializationConfig {
private static YamlConfiguration config;
protected SerializationConfig() {
}
public static File getDataFolder() {
File pluginFolder = Bukkit.getServer().getPluginManager().getPlugins()[0].getDataFolder();
return new File(pluginFolder.getParentFile() + "/TacoSerialization/");
}
public static File getConfigFile() {
return new File(SerializationConfig.getDataFolder() + "/config.yml");
}
public static void reload() {
config = YamlConfiguration.loadConfiguration((File)SerializationConfig.getConfigFile());
SerializationConfig.setDefaults();
SerializationConfig.save();
Logger.getLogger("Minecraft").log(Level.INFO, "[TacoSerialization] Config reloaded");
}
public static void save() {
try {
config.save(SerializationConfig.getConfigFile());
}
catch (IOException e) {
e.printStackTrace();
}
}
private static void setDefaults() {
SerializationConfig.addDefault("horse.color", true);
SerializationConfig.addDefault("horse.inventory", true);
SerializationConfig.addDefault("horse.jump-stength", true);
SerializationConfig.addDefault("horse.style", true);
SerializationConfig.addDefault("horse.variant", true);
SerializationConfig.addDefault("living-entity.age", true);
SerializationConfig.addDefault("living-entity.health", true);
SerializationConfig.addDefault("living-entity.name", true);
SerializationConfig.addDefault("living-entity.potion-effects", true);
SerializationConfig.addDefault("ocelot.type", true);
SerializationConfig.addDefault("player.ender-chest", true);
SerializationConfig.addDefault("player.inventory", true);
SerializationConfig.addDefault("player.stats", true);
SerializationConfig.addDefault("player-stats.can-fly", true);
SerializationConfig.addDefault("player-stats.display-name", true);
SerializationConfig.addDefault("player-stats.exhaustion", true);
SerializationConfig.addDefault("player-stats.exp", true);
SerializationConfig.addDefault("player-stats.food", true);
SerializationConfig.addDefault("player-stats.flying", true);
SerializationConfig.addDefault("player-stats.health", true);
SerializationConfig.addDefault("player-stats.level", true);
SerializationConfig.addDefault("player-stats.potion-effects", true);
SerializationConfig.addDefault("player-stats.saturation", true);
SerializationConfig.addDefault("wolf.collar-color", true);
}
public static void addDefault(String path, Object value) {
if (!SerializationConfig.getConfig().contains(path)) {
SerializationConfig.getConfig().set(path, value);
}
}
private static YamlConfiguration getConfig() {
if (config == null) {
SerializationConfig.reload();
}
return config;
}
public static boolean getShouldSerialize(String path) {
return SerializationConfig.getConfig().getBoolean(path);
}
}

View File

@ -0,0 +1,55 @@
package com.Geekpower14.Quake.Utils.InvSerialization;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Scanner;
import org.json.JSONException;
import org.json.JSONObject;
public class Serializer {
public static String toString(JSONObject object) {
return Serializer.toString(object, true);
}
public static String toString(JSONObject object, boolean pretty) {
return Serializer.toString(object, pretty, 5);
}
public static String toString(JSONObject object, boolean pretty, int tabSize) {
try {
if (pretty) {
return object.toString(tabSize);
}
return object.toString();
}
catch (JSONException e) {
e.printStackTrace();
return null;
}
}
public static JSONObject getObjectFromFile(File file) throws FileNotFoundException, JSONException {
return Serializer.getObjectFromStream(new FileInputStream(file));
}
public static JSONObject getObjectFromStream(InputStream stream) throws JSONException {
return new JSONObject(Serializer.getStringFromStream(stream));
}
public static String getStringFromFile(File file) throws FileNotFoundException {
return Serializer.getStringFromStream(new FileInputStream(file));
}
public static String getStringFromStream(InputStream stream) {
Scanner x = new Scanner(stream);
String str = "";
while (x.hasNextLine()) {
str = str + x.nextLine() + "\n";
}
x.close();
return str.trim();
}
}

View File

@ -0,0 +1,245 @@
package com.Geekpower14.Quake.Utils.InvSerialization;
import java.util.ArrayList;
import java.util.Map;
import org.bukkit.Material;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.BookMeta;
import org.bukkit.inventory.meta.EnchantmentStorageMeta;
import org.bukkit.inventory.meta.FireworkMeta;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.LeatherArmorMeta;
import org.bukkit.inventory.meta.Repairable;
import org.bukkit.inventory.meta.SkullMeta;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class SingleItemSerialization {
protected SingleItemSerialization() {
}
public static JSONObject serializeItemInInventory(ItemStack items, int index) {
return SingleItemSerialization.serializeItems(items, true, index);
}
public static JSONObject serializeItem(ItemStack items) {
return SingleItemSerialization.serializeItems(items, false, 0);
}
private static JSONObject serializeItems(ItemStack items, boolean useIndex, int index) {
try {
JSONObject values = new JSONObject();
if (items == null) {
return null;
}
int amount = items.getAmount();
short data = items.getDurability();
boolean hasMeta = items.hasItemMeta();
String name = null;
String enchants = null;
String[] lore = null;
int repairPenalty = 0;
Material mat = items.getType();
JSONObject bookMeta = null;
JSONObject armorMeta = null;
JSONObject skullMeta = null;
JSONObject fwMeta = null;
if (mat == Material.BOOK_AND_QUILL || mat == Material.WRITTEN_BOOK) {
bookMeta = BookSerialization.serializeBookMeta((BookMeta)items.getItemMeta());
} else if (mat == Material.ENCHANTED_BOOK) {
bookMeta = BookSerialization.serializeEnchantedBookMeta((EnchantmentStorageMeta)items.getItemMeta());
} else if (Util.isLeatherArmor(mat)) {
armorMeta = LeatherArmorSerialization.serializeArmor((LeatherArmorMeta)items.getItemMeta());
} else if (mat == Material.SKULL_ITEM) {
skullMeta = SkullSerialization.serializeSkull((SkullMeta)items.getItemMeta());
} else if (mat == Material.FIREWORK) {
fwMeta = FireworkSerialization.serializeFireworkMeta((FireworkMeta)items.getItemMeta());
}
if (hasMeta) {
Repairable rep;
ItemMeta meta = items.getItemMeta();
if (meta.hasDisplayName()) {
name = meta.getDisplayName();
}
if (meta.hasLore()) {
lore = meta.getLore().toArray(new String[0]);
}
if (meta.hasEnchants()) {
enchants = EnchantmentSerialization.serializeEnchantments(meta.getEnchants());
}
if (meta instanceof Repairable && (rep = (Repairable)meta).hasRepairCost()) {
repairPenalty = rep.getRepairCost();
}
}
values.put("id", mat.name());
values.put("amount", amount);
values.put("data", data);
if (useIndex) {
values.put("index", index);
}
if (name != null) {
values.put("name", name);
}
if (enchants != null) {
values.put("enchantments", enchants);
}
if (lore != null) {
values.put("lore", lore);
}
if (repairPenalty != 0) {
values.put("repairPenalty", repairPenalty);
}
if (bookMeta != null && bookMeta.length() > 0) {
values.put("book-meta", bookMeta);
}
if (armorMeta != null && armorMeta.length() > 0) {
values.put("armor-meta", armorMeta);
}
if (skullMeta != null && skullMeta.length() > 0) {
values.put("skull-meta", skullMeta);
}
if (fwMeta != null && fwMeta.length() > 0) {
values.put("firework-meta", fwMeta);
}
return values;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
public static ItemStack getItem(String item) {
return SingleItemSerialization.getItem(item, 0);
}
public static ItemStack getItem(String item, int index) {
try {
return SingleItemSerialization.getItem(new JSONObject(item), index);
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
public static ItemStack getItem(JSONObject item) {
return SingleItemSerialization.getItem(item, 0);
}
public static ItemStack getItem(JSONObject item, int index) {
try{
String id = item.getString("id");
int amount = item.getInt("amount");
int data = item.getInt("data");
String name = null;
Map<Enchantment, Integer> enchants = null;
ArrayList<String> lore = null;
int repairPenalty = 0;
if (item.has("name")) {
name = item.getString("name");
}
if (item.has("enchantments")) {
enchants = EnchantmentSerialization.getEnchantments(item.getString("enchantments"));
}
if (item.has("lore")) {
JSONArray l = item.getJSONArray("lore");
lore = new ArrayList<>();
for (int j = 0; j < l.length(); ++j) {
lore.add(l.getString(j));
}
}
if (item.has("repairPenalty")) {
repairPenalty = item.getInt("repairPenalty");
}
if (!Util.isNum(id) && Material.getMaterial((String)id) == null) {
throw new IllegalArgumentException("Item " + index + " - No Material found with Material of " + id);
}
if (Util.isNum(id) && Material.getMaterial((int)Integer.parseInt(id)) == null) {
throw new IllegalArgumentException("Item " + index + " - No Material found with id of " + id);
}
Material mat = Util.isNum(id) ? Material.getMaterial((int)Integer.parseInt(id)) : Material.getMaterial((String)id);
ItemStack stuff = new ItemStack(mat, amount, (short)data);
ItemMeta meta;
if ((mat == Material.BOOK_AND_QUILL || mat == Material.WRITTEN_BOOK) && item.has("book-meta")) {
meta = BookSerialization.getBookMeta(item.getJSONObject("book-meta"));
stuff.setItemMeta((ItemMeta)meta);
} else if (mat == Material.ENCHANTED_BOOK && item.has("book-meta")) {
meta = BookSerialization.getEnchantedBookMeta(item.getJSONObject("book-meta"));
stuff.setItemMeta((ItemMeta)meta);
} else if (Util.isLeatherArmor(mat) && item.has("armor-meta")) {
meta = LeatherArmorSerialization.getLeatherArmorMeta(item.getJSONObject("armor-meta"));
stuff.setItemMeta((ItemMeta)meta);
} else if (mat == Material.SKULL_ITEM && item.has("skull-meta")) {
meta = SkullSerialization.getSkullMeta(item.getJSONObject("skull-meta"));
stuff.setItemMeta((ItemMeta)meta);
} else if (mat == Material.FIREWORK && item.has("firework-meta")) {
meta = FireworkSerialization.getFireworkMeta(item.getJSONObject("firework-meta"));
stuff.setItemMeta((ItemMeta)meta);
}
meta = stuff.getItemMeta();
if (name != null) {
meta.setDisplayName(name);
}
if (lore != null) {
meta.setLore(lore);
}
stuff.setItemMeta((ItemMeta)meta);
if (repairPenalty != 0) {
Repairable rep = (Repairable)meta;
rep.setRepairCost(repairPenalty);
stuff.setItemMeta((ItemMeta)rep);
}
if(enchants != null) {
stuff.addUnsafeEnchantments(enchants);
}
return stuff;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
public static String serializeItemInInventoryAsString(ItemStack items, int index) {
return SingleItemSerialization.serializeItemInInventoryAsString(items, index, false);
}
public static String serializeItemInInventoryAsString(ItemStack items, int index, boolean pretty) {
return SingleItemSerialization.serializeItemInInventoryAsString(items, index, pretty, 5);
}
public static String serializeItemInInventoryAsString(ItemStack items, int index, boolean pretty, int indentFactor) {
try {
if (pretty) {
return SingleItemSerialization.serializeItemInInventory(items, index).toString(indentFactor);
}
return SingleItemSerialization.serializeItemInInventory(items, index).toString();
}
catch (JSONException e) {
e.printStackTrace();
return null;
}
}
public static String serializeItemAsString(ItemStack items) {
return SingleItemSerialization.serializeItemAsString(items, false);
}
public static String serializeItemAsString(ItemStack items, boolean pretty) {
return SingleItemSerialization.serializeItemAsString(items, pretty, 5);
}
public static String serializeItemAsString(ItemStack items, boolean pretty, int indentFactor) {
try {
if (pretty) {
return SingleItemSerialization.serializeItem(items).toString(indentFactor);
}
return SingleItemSerialization.serializeItem(items).toString();
}
catch (JSONException e) {
e.printStackTrace();
return null;
}
}
}

View File

@ -0,0 +1,73 @@
package com.Geekpower14.Quake.Utils.InvSerialization;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.SkullMeta;
import org.json.JSONException;
import org.json.JSONObject;
public class SkullSerialization {
protected SkullSerialization() {
}
public static JSONObject serializeSkull(SkullMeta meta) {
try {
JSONObject root = new JSONObject();
if (meta.hasOwner()) {
root.put("owner", meta.getOwner());
}
return root;
}
catch (JSONException e) {
e.printStackTrace();
return null;
}
}
public static String serializeSkullAsString(SkullMeta meta) {
return SkullSerialization.serializeSkullAsString(meta, false);
}
public static String serializeSkullAsString(SkullMeta meta, boolean pretty) {
return SkullSerialization.serializeSkullAsString(meta, pretty, 5);
}
public static String serializeSkullAsString(SkullMeta meta, boolean pretty, int indentFactor) {
try {
if (pretty) {
return SkullSerialization.serializeSkull(meta).toString(indentFactor);
}
return SkullSerialization.serializeSkull(meta).toString();
}
catch (JSONException e) {
e.printStackTrace();
return null;
}
}
public static SkullMeta getSkullMeta(String meta) {
try {
return SkullSerialization.getSkullMeta(new JSONObject(meta));
}
catch (JSONException e) {
e.printStackTrace();
return null;
}
}
public static SkullMeta getSkullMeta(JSONObject meta) {
try {
ItemStack dummyItems = new ItemStack(Material.SKULL_ITEM);
SkullMeta dummyMeta = (SkullMeta)dummyItems.getItemMeta();
if (meta.has("owner")) {
dummyMeta.setOwner(meta.getString("owner"));
}
return dummyMeta;
}
catch (JSONException e) {
e.printStackTrace();
return null;
}
}
}

View File

@ -0,0 +1,30 @@
package com.Geekpower14.Quake.Utils.InvSerialization;
import org.bukkit.Material;
public class Util {
protected Util() {
}
public static boolean isNum(String s) {
try {
Integer.parseInt(s);
return true;
}
catch (NumberFormatException e) {
return false;
}
}
public static boolean isLeatherArmor(Material material) {
return material == Material.LEATHER_HELMET || material == Material.LEATHER_CHESTPLATE || material == Material.LEATHER_LEGGINGS || material == Material.LEATHER_BOOTS;
}
public static boolean keyFound(String[] array, String key) {
for (String s : array) {
if (!s.equalsIgnoreCase(key)) continue;
}
return false;
}
}

View File

@ -0,0 +1,78 @@
package com.Geekpower14.Quake.Utils.InvSerialization;
import org.bukkit.Color;
import org.bukkit.DyeColor;
import org.bukkit.Location;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Wolf;
import org.json.JSONException;
import org.json.JSONObject;
public class WolfSerialization {
protected WolfSerialization() {
}
public static JSONObject serializeWolf(Wolf wolf) {
try {
JSONObject root = LivingEntitySerialization.serializeEntity((LivingEntity)wolf);
if (WolfSerialization.shouldSerialize("collar-color")) {
root.put("collar-color", ColorSerialization.serializeColor(wolf.getCollarColor().getColor()));
}
return root;
}
catch (JSONException e) {
e.printStackTrace();
return null;
}
}
public static String serializeWolfAsString(Wolf wolf) {
return WolfSerialization.serializeWolfAsString(wolf, false);
}
public static String serializeWolfAsString(Wolf wolf, boolean pretty) {
return WolfSerialization.serializeWolfAsString(wolf, pretty, 5);
}
public static String serializeWolfAsString(Wolf wolf, boolean pretty, int indentFactor) {
try {
if (pretty) {
return WolfSerialization.serializeWolf(wolf).toString(indentFactor);
}
return WolfSerialization.serializeWolf(wolf).toString();
}
catch (JSONException e) {
e.printStackTrace();
return null;
}
}
public static Wolf spawnWolf(Location location, String stats) {
try {
return WolfSerialization.spawnWolf(location, new JSONObject(stats));
}
catch (JSONException e) {
e.printStackTrace();
return null;
}
}
public static Wolf spawnWolf(Location location, JSONObject stats) {
try {
Wolf wolf = (Wolf)LivingEntitySerialization.spawnEntity(location, stats);
if (stats.has("collar-color")) {
wolf.setCollarColor(DyeColor.getByColor((Color)ColorSerialization.getColor(stats.getString("collar-color"))));
}
return wolf;
}
catch (JSONException e) {
e.printStackTrace();
return null;
}
}
public static boolean shouldSerialize(String key) {
return SerializationConfig.getShouldSerialize("wolf." + key);
}
}

View File

@ -0,0 +1,661 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.Geekpower14.Quake.Utils;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Collection;
//1.8.8
//import net.minecraft.server.v1_9_R1.EnumParticle;
//1.9.2
//import net.minecraft.server.v1_9_R1.EnumParticle;
//1.9.4
//import net.minecraft.server.v1_9_R2.EnumParticle;
//1.10
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.entity.Player;
public enum ParticleEffects {
HUGE_EXPLOSION("hugeexplosion", "EXPLOSION_HUGE"),
LARGE_EXPLODE("largeexplode", "EXPLOSION_LARGE"),
BUBBLE("bubble", "WATER_BUBBLE"),
SUSPEND("suspended", "SUSPENDED"),
DEPTH_SUSPEND("depthsuspend", "SUSPENDED_DEPTH"),
MAGIC_CRIT("magicCrit", "CRIT_MAGIC"),
MOB_SPELL("mobSpell", "SPELL_MOB", true),
MOB_SPELL_AMBIENT("mobSpellAmbient", "SPELL_MOB_AMBIENT"),
INSTANT_SPELL("instantSpell", "SPELL_INSTANT"),
WITCH_MAGIC("witchMagic", "SPELL_WITCH"),
EXPLODE("explode", "EXPLOSION_NORMAL"),
SPLASH("splash", "WATER_SPLASH"),
LARGE_SMOKE("largesmoke", "SMOKE_LARGE"),
RED_DUST("reddust", "REDSTONE", true),
SNOWBALL_POOF("snowballpoof", "SNOWBALL"),
ANGRY_VILLAGER("angryVillager", "VILLAGER_ANGRY"),
HAPPY_VILLAGER("happyVillager", "VILLAGER_HAPPY"),
EXPLOSION_NORMAL(EXPLODE.getName()),
EXPLOSION_LARGE(LARGE_EXPLODE.getName()),
EXPLOSION_HUGE(HUGE_EXPLOSION.getName()),
FIREWORKS_SPARK("fireworksSpark"),
WATER_BUBBLE(BUBBLE.getName()),
WATER_SPLASH(SPLASH.getName()),
WATER_WAKE("wake"),
SUSPENDED(SUSPEND.getName()),
SUSPENDED_DEPTH(DEPTH_SUSPEND.getName()),
CRIT("crit"),
CRIT_MAGIC(MAGIC_CRIT.getName()),
SMOKE_NORMAL("smoke"),
SMOKE_LARGE(LARGE_SMOKE.getName()),
SPELL("spell"),
SPELL_INSTANT(INSTANT_SPELL.getName()),
SPELL_MOB(MOB_SPELL.getName(), true),
SPELL_MOB_AMBIENT(MOB_SPELL_AMBIENT.getName()),
SPELL_WITCH(WITCH_MAGIC.getName()),
DRIP_WATER("dripWater"),
DRIP_LAVA("dripLava"),
VILLAGER_ANGRY(ANGRY_VILLAGER.getName()),
VILLAGER_HAPPY(HAPPY_VILLAGER.getName()),
TOWN_AURA("townaura"), NOTE("note", true),
PORTAL("portal"),
ENCHANTMENT_TABLE("enchantmenttable"),
FLAME("flame"),
LAVA("lava"),
FOOTSTEP("footstep"),
CLOUD("cloud"),
REDSTONE("reddust", true),
SNOWBALL("snowballpoof"),
SNOW_SHOVEL("snowshovel"),
SLIME("slime"),
HEART("heart"),
BARRIER("barrier"),
ITEM_CRACK("iconcrack_"),
BLOCK_CRACK("blockcrack_"),
BLOCK_DUST("blockdust_"),
WATER_DROP("droplet"),
ITEM_TAKE("take"),
MOB_APPEARANCE("mobappearance");
private final String _particleName;
private final String _enumValue;
private final boolean _hasColor;
private static Class<?> _nmsPacketPlayOutParticle;
private static Class<?> _nmsEnumParticle;
private static int _particleRange;
private static Class<?> _nmsPlayerConnection;
private static Class<?> _nmsEntityPlayer;
private static Class<?> _ioNettyChannel;
private static Method _nmsNetworkGetVersion;
private static Field _nmsFieldPlayerConnection;
private static Field _nmsFieldNetworkManager;
private static Field _nmsFieldNetworkManagerI;
private static Field _nmsFieldNetworkManagerM;
private ParticleEffects(String particleName, String enumValue, boolean hasColor) {
_particleName = particleName;
_enumValue = enumValue;
_hasColor = hasColor;
}
private ParticleEffects(String particleName, String enumValue) {
_particleName = particleName;
_enumValue = enumValue;
_hasColor = false;
}
private ParticleEffects(String particleName) {
_particleName = particleName;
_enumValue = null;
_hasColor = false;
}
private ParticleEffects(String particleName, boolean hasColor) {
_particleName = particleName;
_enumValue = null;
_hasColor = hasColor;
}
public String getName() {
return _particleName;
}
public boolean hasColor() {
return _hasColor;
}
public static void setRange(int range) {
if(range < 0) {
throw new IllegalArgumentException("Range must be positive!");
}
_particleRange = range;
}
public static int getRange() {
return _particleRange;
}
private void sendToPlayer(Player player, Location location, float offsetX, float offsetY, float offsetZ, float speed, int count, int... extra) throws Exception {
sendToPlayer(player, location, offsetX, offsetY, offsetZ, speed, count, false, extra);
}
private void sendToPlayer(Player player, Location location, float offsetX, float offsetY, float offsetZ, float speed, int count, boolean force, int... extra) throws Exception {
if((!force) && (!isPlayerInRange(player, location))) {
return;
}
//if(ReflectionUtilities.getVersion().contains("v1_8")) {
try {
if(_nmsEnumParticle == null)
_nmsEnumParticle = ReflectionUtilities.getNMSClass("EnumParticle");
if(this == BLOCK_CRACK) {
int id = 0;
int data = 0;
if (extra.length > 0) {
id = extra[0];
}
if (extra.length > 1) {
data = extra[1];
}
extra = new int[] { id, id | data << 12 };
}
Object packet = _nmsPacketPlayOutParticle.getConstructor(new Class[] { _nmsEnumParticle, Boolean.TYPE, Float.TYPE, Float.TYPE, Float.TYPE, Float.TYPE, Float.TYPE, Float.TYPE, Float.TYPE, Integer.TYPE, int[].class }).newInstance(new Object[] { getEnum(_nmsEnumParticle.getName() + "." + (_enumValue != null ? _enumValue : name().toUpperCase())), true, (float)location.getX(), (float)location.getY(), (float)location.getZ(), offsetX, offsetY, offsetZ, speed, count, extra });
Object handle = ReflectionUtilities.getHandle(player);
Object connection = ReflectionUtilities.getField(handle.getClass(), "playerConnection").get(handle);
ReflectionUtilities.getMethod(connection.getClass(), "sendPacket", new Class[0]).invoke(connection, new Object[] { packet });
} catch (Exception e) {
throw e;
}
/*} else {
try {
if(_particleName == null)
_particleName = name().toLowerCase();
String name = _particleName;
if((this == BLOCK_CRACK) || (this == ITEM_CRACK) || (this == BLOCK_DUST)) {
int id = 0;
int data = 0;
if(extra.length > 0)
id = extra[0];
if(extra.length > 1)
data = extra[1];
name = name + id + "_" + data;
}
Object packet = _nmsPacketPlayOutParticle.getConstructor(new Class[] { String.class, Float.TYPE, Float.TYPE, Float.TYPE, Float.TYPE, Float.TYPE, Float.TYPE, Float.TYPE, Integer.TYPE }).newInstance(new Object[] { name, (float)location.getX(), (float)location.getY(), (float)location.getZ(), offsetX, offsetY, offsetZ, speed, count});
Object handle = ReflectionUtilities.getHandle(player);
Object connection = ReflectionUtilities.getField(handle.getClass(), "playerConnection").get(handle);
ReflectionUtilities.getMethod(connection.getClass(), "sendPacket", new Class[0]).invoke(connection, new Object[] { packet });
} catch (Exception e) {
throw e;
}
}*/
}
public void sendToPlayer(Player player, Location location, float offsetX, float offsetY, float offsetZ, float speed, int count, boolean force) throws Exception {
sendToPlayer(player, location, offsetX, offsetY, offsetZ, speed, count, force, new int[0]);
}
public void sendToPlayer(Player player, Location location, float offsetX, float offsetY, float offsetZ, float speed, int count) throws Exception {
sendToPlayer(player, location, offsetX, offsetY, offsetZ, speed, count, false);
}
public void sendToPlayers(Collection<? extends Player> players, Location location, float offsetX, float offsetY, float offsetZ, float speed, int count) throws Exception {
for(Player p : players)
sendToPlayer(p, location, offsetX, offsetY, offsetZ, speed, count);
}
public void sendToPlayers(Collection<? extends Player> players, Location location, float offsetX, float offsetY, float offsetZ, float speed, int count, boolean force) throws Exception {
for(Player p : players)
sendToPlayer(p, location, offsetX, offsetY, offsetZ, speed, count, force);
}
public void sendToPlayers(Player[] players, Location location, float offsetX, float offsetY, float offsetZ, float speed, int count) throws Exception {
for (Player p : players)
sendToPlayer(p, location, offsetX, offsetY, offsetZ, speed, count);
}
public void sendColor(Player p, Location location, org.bukkit.Color color) throws Exception {
if(!_hasColor)
return;
sendToPlayer(p, location, getColor(color.getRed()), getColor(color.getGreen()), getColor(color.getBlue()), 1.0F, 0);
}
public void sendColor(Player p, Location location, org.bukkit.Color color, boolean force) throws Exception {
if(!_hasColor)
return;
sendToPlayer(p, location, getColor(color.getRed()), getColor(color.getGreen()), getColor(color.getBlue()), 1.0F, 0, force);
}
@Deprecated
public void sendColor(Player p, Location location, java.awt.Color color) throws Exception {
if(!_hasColor)
return;
sendToPlayer(p, location, getColor(color.getRed()), getColor(color.getGreen()), getColor(color.getBlue()), 1.0F, 0);
}
public void sendColor(Player p, Location location, java.awt.Color color, boolean force) throws Exception {
if(!_hasColor)
return;
sendToPlayer(p, location, getColor(color.getRed()), getColor(color.getGreen()), getColor(color.getBlue()), 1.0F, 0, force);
}
@Deprecated
public void sendColor(Collection<? extends Player> players, Location location, java.awt.Color color) throws Exception {
if(!_hasColor)
return;
for(Player p : players)
sendColor(p, location, color);
}
public void sendColor(Collection<? extends Player> players, Location location, java.awt.Color color, boolean force) throws Exception {
if(!_hasColor)
return;
for(Player p : players)
sendColor(p, location, color, force);
}
public void sendColor(Collection<? extends Player> players, Location location, org.bukkit.Color color) throws Exception {
if(!_hasColor)
return;
for(Player p : players)
sendColor(p, location, color);
}
@Deprecated
public void sendColor(Collection<? extends Player> players, Location location, org.bukkit.Color color, boolean force) throws Exception {
if(!_hasColor)
return;
for(Player p : players)
sendColor(p, location, color, force);
}
@Deprecated
public void sendColor(Player[] players, Location location, org.bukkit.Color color) throws Exception {
if(!_hasColor)
return;
for(Player p : players)
sendColor(p, location, color);
}
@Deprecated
public void sendColor(Player[] players, Location location, java.awt.Color color) throws Exception {
if(!_hasColor)
return;
for(Player p : players)
sendColor(p, location, color);
}
protected float getColor(float value) {
if(value <= 0.0F)
value = -1.0F;
return value / 255.0F;
}
public static void sendPacket(Object packet, Player player) {
try {
Object nms_player = _nmsNetworkGetVersion.invoke(player, new Object[0]);
Object nms_connection = _nmsFieldPlayerConnection.get(nms_player);
_nmsNetworkGetVersion.invoke(nms_connection, packet);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
e.printStackTrace();
}
}
@Deprecated
public void sendBlockCrack(Player player, Location location, int id, byte data, float offsetX, float offsetY, float offsetZ, float speed, int count)
throws Exception
{
if (this != BLOCK_CRACK) {
throw new IllegalArgumentException("This method is only available for BLOCK_CRACK!");
}
sendToPlayer(player, location, offsetX, offsetY, offsetZ, speed, count, new int[] { id, data });
}
public void sendBlockCrack(Player player, Location location, int id, byte data, float offsetX, float offsetY, float offsetZ, float speed, int count, boolean force)
throws Exception
{
if (this != BLOCK_CRACK) {
throw new IllegalArgumentException("This method is only available for BLOCK_CRACK!");
}
sendToPlayer(player, location, offsetX, offsetY, offsetZ, speed, count, force, new int[] { id, data });
}
@Deprecated
public void sendBlockCrack(Collection<? extends Player> players, Location location, int id, byte data, float offsetX, float offsetY, float offsetZ, float speed, int count)
throws Exception
{
if (this != BLOCK_CRACK) {
throw new IllegalArgumentException("This method is only available for BLOCK_CRACK!");
}
for (Player p : players) {
sendBlockCrack(p, location, id, data, offsetX, offsetY, offsetZ, speed, count);
}
}
public void sendBlockCrack(Collection<? extends Player> players, Location location, int id, byte data, float offsetX, float offsetY, float offsetZ, float speed, int count, boolean force)
throws Exception
{
if (this != BLOCK_CRACK) {
throw new IllegalArgumentException("This method is only available for BLOCK_CRACK!");
}
for (Player p : players) {
sendBlockCrack(p, location, id, data, offsetX, offsetY, offsetZ, speed, count, force);
}
}
@Deprecated
public void sendBlockCrack(Player[] players, Location location, int id, byte data, float offsetX, float offsetY, float offsetZ, float speed, int count)
throws Exception
{
if (this != BLOCK_CRACK) {
throw new IllegalArgumentException("This method is only available for BLOCK_CRACK!");
}
for (Player p : players) {
sendBlockCrack(p, location, id, data, offsetX, offsetY, offsetZ, speed, count);
}
}
@Deprecated
public void sendItemCrack(Player player, Location location, int id, byte data, float offsetX, float offsetY, float offsetZ, float speed, int count)
throws Exception
{
if (this != ITEM_CRACK) {
throw new IllegalArgumentException("This method is only available for ITEM_CRACK!");
}
sendToPlayer(player, location, offsetX, offsetY, offsetZ, speed, count, new int[] { id, data });
}
public void sendItemCrack(Player player, Location location, int id, byte data, float offsetX, float offsetY, float offsetZ, float speed, int count, boolean force)
throws Exception
{
if (this != ITEM_CRACK) {
throw new IllegalArgumentException("This method is only available for ITEM_CRACK!");
}
sendToPlayer(player, location, offsetX, offsetY, offsetZ, speed, count, force, new int[] { id, data });
}
@Deprecated
public void sendItemCrack(Collection<? extends Player> players, Location location, int id, byte data, float offsetX, float offsetY, float offsetZ, float speed, int count)
throws Exception
{
if (this != ITEM_CRACK) {
throw new IllegalArgumentException("This method is only available for ITEM_CRACK!");
}
for (Player p : players) {
sendItemCrack(p, location, id, data, offsetX, offsetY, offsetZ, speed, count);
}
}
public void sendItemCrack(Collection<? extends Player> players, Location location, int id, byte data, float offsetX, float offsetY, float offsetZ, float speed, int count, boolean force)
throws Exception
{
if (this != ITEM_CRACK) {
throw new IllegalArgumentException("This method is only available for ITEM_CRACK!");
}
for (Player p : players) {
sendItemCrack(p, location, id, data, offsetX, offsetY, offsetZ, speed, count, force);
}
}
@Deprecated
public void sendItemCrack(Player[] players, Location location, int id, byte data, float offsetX, float offsetY, float offsetZ, float speed, int count)
throws Exception
{
if (this != ITEM_CRACK) {
throw new IllegalArgumentException("This method is only available for ITEM_CRACK!");
}
for (Player p : players) {
sendItemCrack(p, location, id, data, offsetX, offsetY, offsetZ, speed, count);
}
}
@Deprecated
public void sendBlockDust(Player p, Location location, int id, float offsetX, float offsetY, float offsetZ, float speed, int count)
throws Exception
{
if (this != BLOCK_DUST) {
throw new IllegalArgumentException("This method is only available for BLOCK_DUST!");
}
sendToPlayer(p, location, offsetX, offsetY, offsetZ, speed, count, new int[] { id });
}
public void sendBlockDust(Player p, Location location, int id, float offsetX, float offsetY, float offsetZ, float speed, int count, boolean force)
throws Exception
{
if (this != BLOCK_DUST) {
throw new IllegalArgumentException("This method is only available for BLOCK_DUST!");
}
sendToPlayer(p, location, offsetX, offsetY, offsetZ, speed, count, force, new int[] { id });
}
@Deprecated
public void sendBlockDust(Collection<? extends Player> players, Location location, int id, float offsetX, float offsetY, float offsetZ, float speed, int count)
throws Exception
{
if (this != BLOCK_DUST) {
throw new IllegalArgumentException("This method is only available for BLOCK_DUST!");
}
for (Player p : players) {
sendBlockDust(p, location, id, offsetX, offsetY, offsetZ, speed, count);
}
}
public void sendBlockDust(Collection<? extends Player> players, Location location, int id, float offsetX, float offsetY, float offsetZ, float speed, int count, boolean force)
throws Exception
{
if (this != BLOCK_DUST) {
throw new IllegalArgumentException("This method is only available for BLOCK_DUST!");
}
for (Player p : players) {
sendBlockDust(p, location, id, offsetX, offsetY, offsetZ, speed, count, force);
}
}
@Deprecated
public void sendBlockDust(Player[] players, Location location, int id, float offsetX, float offsetY, float offsetZ, float speed, int count)
throws Exception
{
if (this != BLOCK_DUST) {
throw new IllegalArgumentException("This method is only available for BLOCK_DUST!");
}
for (Player p : players) {
sendBlockDust(p, location, id, offsetX, offsetY, offsetZ, speed, count);
}
}
protected static int getVersion(Player p)
{
try
{
Object handle = ReflectionUtilities.getHandle(p);
Object connection = _nmsFieldPlayerConnection.get(handle);
Object network = _nmsFieldNetworkManager.get(connection);
Object channel;
if (ReflectionUtilities.getVersion().contains("1_7")) {
channel = _nmsFieldNetworkManagerM.get(network);
} else {
channel = _nmsFieldNetworkManagerI.get(network);
}
Object version = ReflectionUtilities.getVersion().contains("1_7") ? _nmsNetworkGetVersion.invoke(network, new Object[] { channel }) : Integer.valueOf(47);
return ((Integer)version).intValue();
}
catch (Exception e)
{
e.printStackTrace();
}
return 0;
}
static
{
_nmsPacketPlayOutParticle = ReflectionUtilities.getNMSClass("PacketPlayOutWorldParticles");
_particleRange = 25;
String ver = ReflectionUtilities.getVersion();
try
{
_nmsPlayerConnection = ReflectionUtilities.getNMSClass("PlayerConnection");
_nmsEntityPlayer = ReflectionUtilities.getNMSClass("EntityPlayer");
_ioNettyChannel = ver.contains("1_7") ? Class.forName("net.minecraft.util.io.netty.channel.Channel") : Class.forName("io.netty.channel.Channel");
_nmsFieldPlayerConnection = ReflectionUtilities.getField(_nmsEntityPlayer, "playerConnection");
_nmsFieldNetworkManager = ReflectionUtilities.getField(_nmsPlayerConnection, "networkManager");
_nmsFieldNetworkManagerI = ReflectionUtilities.getField(_nmsFieldNetworkManager.getType(), "i");
_nmsFieldNetworkManagerM = ReflectionUtilities.getField(_nmsFieldNetworkManager.getType(), "m");
_nmsNetworkGetVersion = ReflectionUtilities.getMethod(_nmsFieldNetworkManager.getType(), "getVersion", new Class[] { _ioNettyChannel });
}
catch (Exception e)
{
System.err.println("[ParticleLIB] Error while loading: " + e.getMessage());
e.printStackTrace(System.err);
Bukkit.getPluginManager().disablePlugin(Bukkit.getPluginManager().getPlugin("ParticleLIB"));
}
}
private static Enum<?> getEnum(String enumFullName) {
String[] x = enumFullName.split("\\.(?=[^\\.]+$)");
if (x.length == 2)
{
String enumClassName = x[0];
String enumName = x[1];
try {
Class<Enum> cl = (Class<Enum>)Class.forName(enumClassName);
return Enum.valueOf(cl, enumName);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
return null;
}
public static boolean isPlayerInRange(Player p, Location center)
{
double distance = 0.0D;
if (!p.getLocation().getWorld().equals(center.getWorld())) {
return false;
}
if ((distance = center.distanceSquared(p.getLocation())) > Double.MAX_VALUE) {
return false;
}
return distance < _particleRange * _particleRange;
}
public static class ReflectionUtilities
{
public static void setValue(Object instance, String fieldName, Object value)
throws Exception
{
Field field = instance.getClass().getDeclaredField(fieldName);
field.setAccessible(true);
field.set(instance, value);
}
public static Object getValue(Object instance, String fieldName)
throws Exception
{
Field field = instance.getClass().getDeclaredField(fieldName);
field.setAccessible(true);
return field.get(instance);
}
public static String getVersion()
{
String name = Bukkit.getServer().getClass().getPackage().getName();
String version = name.substring(name.lastIndexOf('.') + 1) + ".";
return version;
}
public static Class<?> getNMSClass(String className)
{
String fullName = "net.minecraft.server." + getVersion() + className;
Class<?> clazz = null;
try
{
clazz = Class.forName(fullName);
}
catch (Exception e)
{
e.printStackTrace();
}
return clazz;
}
public static Class<?> getOBCClass(String className)
{
String fullName = "org.bukkit.craftbukkit." + getVersion() + className;
Class<?> clazz = null;
try
{
clazz = Class.forName(fullName);
}
catch (Exception e)
{
e.printStackTrace();
}
return clazz;
}
public static Object getHandle(Object obj)
{
try
{
return getMethod(obj.getClass(), "getHandle", new Class[0]).invoke(obj, new Object[0]);
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
public static Field getField(Class<?> clazz, String name)
{
try
{
Field field = clazz.getDeclaredField(name);
field.setAccessible(true);
return field;
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
public static Method getMethod(Class<?> clazz, String name, Class<?>... args)
{
for (Method m : clazz.getMethods()) {
if ((m.getName().equals(name)) && ((args.length == 0) || (ClassListEqual(args, m.getParameterTypes()))))
{
m.setAccessible(true);
return m;
}
}
return null;
}
public static boolean ClassListEqual(Class<?>[] l1, Class<?>[] l2)
{
boolean equal = true;
if (l1.length != l2.length) {
return false;
}
for (int i = 0; i < l1.length; i++) {
if (l1[i] != l2[i])
{
equal = false;
break;
}
}
return equal;
}
}
}

View File

@ -0,0 +1,133 @@
package com.Geekpower14.Quake.Utils;
import com.Geekpower14.Quake.Quake;
import java.io.File;
import org.bukkit.GameMode;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
public class PlayerSerializer {
public static FileConfiguration PlayerToConfig(Player p) {
YamlConfiguration config = YamlConfiguration.loadConfiguration((File)new File(""));
config.set("Name", p.getName());
config.set("Health", p.getHealth());
config.set("Food", p.getFoodLevel());
config.set("Saturation", p.getSaturation());
config.set("Exhaustion", p.getExhaustion());
config.set("XP-Level", p.getLevel());
config.set("Exp", p.getExp());
config.set("GameMode", p.getGameMode().name());
PlayerSerializer.ItemStackToConfig((FileConfiguration)config, "Armor", p.getInventory().getArmorContents());
PlayerSerializer.ItemStackToConfig((FileConfiguration)config, "Inventaire", p.getInventory().getContents());
return config;
}
public static Boolean RetorePlayer(Player p) {
File f = new File(Quake.getPlugin().getDataFolder() + "/Save_Players/" + p.getName() + ".yml");
YamlConfiguration config = YamlConfiguration.loadConfiguration((File)f);
PlayerSerializer.ConfigToPlayer(p, (FileConfiguration)config);
f.delete();
return true;
}
public static Boolean ConfigToPlayer(Player p, FileConfiguration config) {
if (!config.contains("Name") || !config.getString("Name").equals(p.getName())) {
return false;
}
p.setHealth(config.getDouble("Health"));
p.setFoodLevel(config.getInt("Food"));
p.setSaturation((float)config.getDouble("Saturation"));
p.setExhaustion((float)config.getDouble("Exhaustion"));
p.setLevel(config.getInt("XP-Level"));
p.setExp((float)config.getDouble("Exp"));
try {
p.setGameMode(GameMode.valueOf(config.getString("GameMode")));
} catch (Exception var2_2) {
// empty catch block
}
p.getInventory().clear();
p.getInventory().setArmorContents(PlayerSerializer.ConfigToItemStack(config, "Armor"));
p.getInventory().setContents(PlayerSerializer.ConfigToItemStack(config, "Inventaire"));
try {
p.updateInventory();
} catch (Exception var2_3) {
// empty catch block
}
return true;
}
public static ItemStack[] ConfigToItemStack(FileConfiguration config, String path) {
int nb = config.getInt(String.valueOf(path) + ".Item-Nb");
ItemStack[] item = new ItemStack[nb];
int i = 0;
while (i < nb) {
item[i] = config.getItemStack(String.valueOf(path) + ".Item" + i);
++i;
}
return item;
}
public static FileConfiguration ItemStackToConfig(FileConfiguration config, String path, ItemStack[] items) {
if (config == null) {
return null;
}
config.set(String.valueOf(path) + ".Item-Nb", items.length);
int i = 0;
ItemStack[] arritemStack = items;
int n = arritemStack.length;
int n2 = 0;
while (n2 < n) {
ItemStack it = arritemStack[n2];
config.set(String.valueOf(path) + ".Item" + i, it);
++i;
++n2;
}
return config;
}
/*public static String InventoryToString(Inventory inv) {
if(inv instanceof PlayerInventory)
return InventorySerialization.serializePlayerInventoryAsString((PlayerInventory)inv);
else
return InventorySerialization.serializeInventoryAsString(inv);
}*/
/*public static Inventory StringToInventory(String invString) {
return InventorySerialization.
String[] serializedBlocks = invString.split(";");
String invInfo = serializedBlocks[0];
Inventory deserializedInventory = Bukkit.getServer().createInventory(null, Integer.valueOf(invInfo));
return
int i = 1;
while (i < serializedBlocks.length) {
String[] serializedBlock = serializedBlocks[i].split("#");
int stackPosition = Integer.valueOf(serializedBlock[0]);
if(stackPosition < deserializedInventory.getSize()) {
ItemStack is = null;
String[] arrstring = serializedBlock[1].split(":");
int n = arrstring.length;
int n2 = 0;
while(n2 < n) {
String itemInfo = arrstring[n2];
String[] itemAttribute = itemInfo.split("@");
if (itemAttribute[0].equals("t")) {
is = new ItemStack(Material.getMaterial(itemAttribute[1]));
} else if (itemAttribute[0].equals("d") && is != null) {
is.setDurability(Short.valueOf(itemAttribute[1]));
} else if (itemAttribute[0].equals("a") && is != null) {
is.setAmount(Integer.valueOf(itemAttribute[1]));
} else if (itemAttribute[0].equals("e") && is != null) {
is.addEnchantment(Enchantment.getByName(itemAttribute[1]), Integer.valueOf(itemAttribute[2]));
}
n2++;
}
deserializedInventory.setItem(stackPosition, is);
}
i++;
}
return deserializedInventory;
}*/
}

View File

@ -0,0 +1,114 @@
/*
* Decompiled with CFR 0_114.
*
* Could not load the following classes:
* org.bukkit.Bukkit
*/
package com.Geekpower14.Quake.Utils;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import org.bukkit.Bukkit;
public class Reflection {
public static String getVersion() {
String name = Bukkit.getServer().getClass().getPackage().getName();
String version = String.valueOf(name.substring(name.lastIndexOf(46) + 1)) + ".";
return version;
}
public static Class<?> getNMSClass(String className) {
String fullName = "net.minecraft.server." + Reflection.getVersion() + className;
Class clazz = null;
try {
clazz = Class.forName(fullName);
}
catch (Exception e) {
e.printStackTrace();
}
return clazz;
}
public static Enum<?> getNMSEnum(String className) {
String enumFullName = "net.minecraft.server." + Reflection.getVersion() + className;
String[] x = enumFullName.split("\\.(?=[^\\.]+$)");
if (x.length == 2) {
String enumClassName = x[0];
String enumName = x[1];
try {
Class cl = Class.forName(enumClassName);
return Enum.valueOf(cl, enumName);
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
return null;
}
public static Class<?> getOBCClass(String className) {
String fullName = "org.bukkit.craftbukkit." + Reflection.getVersion() + className;
Class clazz = null;
try {
clazz = Class.forName(fullName);
}
catch (Exception e) {
e.printStackTrace();
}
return clazz;
}
public static Object getHandle(Object obj) {
try {
return Reflection.getMethod(obj.getClass(), "getHandle", new Class[0]).invoke(obj, new Object[0]);
}
catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static Field getField(Class<?> clazz, String name) {
try {
Field field = clazz.getDeclaredField(name);
field.setAccessible(true);
return field;
}
catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static Method getMethod(Class<?> clazz, String name, Class<?> ... args) {
Method[] arrmethod = clazz.getMethods();
int n = arrmethod.length;
int n2 = 0;
while (n2 < n) {
Method m = arrmethod[n2];
if (m.getName().equals(name) && (args.length == 0 || Reflection.ClassListEqual(args, m.getParameterTypes()))) {
m.setAccessible(true);
return m;
}
++n2;
}
return null;
}
public static boolean ClassListEqual(Class<?>[] l1, Class<?>[] l2) {
boolean equal = true;
if (l1.length != l2.length) {
return false;
}
int i = 0;
while (i < l1.length) {
if (l1[i] != l2[i]) {
equal = false;
break;
}
++i;
}
return equal;
}
}

View File

@ -0,0 +1,75 @@
package com.Geekpower14.Quake.Utils;
import com.Geekpower14.Quake.Quake;
import com.Geekpower14.Quake.Trans.Score;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.scoreboard.DisplaySlot;
import org.bukkit.scoreboard.Objective;
import org.bukkit.scoreboard.Scoreboard;
public final class ScoreB {
public Quake _plugin;
public int _Money = 0;
public int _Kills = 0;
public int _Deaths = 0;
public int _Shots = 0;
public int _Wins = 0;
public Player _player;
public Objective _objective;
public Scoreboard _board;
public ScoreB(Quake pl, Player p) {
_plugin = pl;
_player = p;
_Kills = _plugin._eco.getScore(p, Score.Type.Kill);
_Deaths = _plugin._eco.getScore(p, Score.Type.Death);
_Shots = _plugin._eco.getScore(p, Score.Type.Shot);
_Wins = _plugin._eco.getScore(p, Score.Type.Win);
_Money = _plugin._eco.getPlayerMoney(p);
_board = Bukkit.getScoreboardManager().getNewScoreboard();
_objective = _board.registerNewObjective("Score", "dummy");
_objective.setDisplaySlot(DisplaySlot.SIDEBAR);
_objective.setDisplayName(_plugin._trad.get("ScoreBoard.name"));
_objective.getScore(_plugin._trad.get("Shop.Coins.name")).setScore(_Money);
_objective.getScore(_plugin._trad.get("ScoreBoard.Kills.name")).setScore(_Kills);
_objective.getScore(_plugin._trad.get("ScoreBoard.Deaths.name")).setScore(_Deaths);
_objective.getScore(_plugin._trad.get("ScoreBoard.Shots.name")).setScore(_Shots);
_objective.getScore(_plugin._trad.get("ScoreBoard.Wins.name")).setScore(_Wins);
if (isScoreWorld(_player.getWorld().getName())) {
_player.setScoreboard(_board);
} else if (!isScoreWorld(_player.getWorld().getName())) {
_player.setScoreboard(Bukkit.getScoreboardManager().getNewScoreboard());
}
}
public void updateScore() {
if (_Shots == _plugin._eco.getScore(_player, Score.Type.Shot) && _Deaths == _plugin._eco.getScore(_player, Score.Type.Death) && _Money == _plugin._eco.getPlayerMoney(_player)) {
return;
}
_Kills = _plugin._eco.getScore(_player, Score.Type.Kill);
_Deaths = _plugin._eco.getScore(_player, Score.Type.Death);
_Shots = _plugin._eco.getScore(_player, Score.Type.Shot);
_Wins = _plugin._eco.getScore(_player, Score.Type.Win);
_Money = _plugin._eco.getPlayerMoney(_player);
_objective.getScore(_plugin._trad.get("Shop.Coins.name")).setScore(_Money);
_objective.getScore(_plugin._trad.get("ScoreBoard.Kills.name")).setScore(_Kills);
_objective.getScore(_plugin._trad.get("ScoreBoard.Deaths.name")).setScore(_Deaths);
_objective.getScore(_plugin._trad.get("ScoreBoard.Shots.name")).setScore(_Shots);
_objective.getScore(_plugin._trad.get("ScoreBoard.Wins.name")).setScore(_Wins);
if (isScoreWorld(_player.getWorld().getName())) {
_player.setScoreboard(_board);
} else {
_player.setScoreboard(Bukkit.getScoreboardManager().getNewScoreboard());
}
}
public Scoreboard getScoreBoard() {
return _board;
}
public Boolean isScoreWorld(String name) {
return _plugin._ScoreWorlds.contains(name);
}
}

View File

@ -0,0 +1,57 @@
package com.Geekpower14.Quake.Utils;
public class Version implements Comparable<Version> {
private String _version;
public final String get() {
return _version;
}
public Version(String version) {
if (version == null) {
throw new IllegalArgumentException("Version can not be null");
}
if (!version.matches("[0-9]+(\\.[0-9]+)*")) {
throw new IllegalArgumentException("Invalid version format");
}
_version = version;
}
@Override
public int compareTo(Version that) {
if (that == null) {
return 1;
}
String[] thisParts = get().split("\\.");
String[] thatParts = that.get().split("\\.");
int length = Math.max(thisParts.length, thatParts.length);
int i = 0;
while (i < length) {
int thatPart;
int thisPart = i < thisParts.length ? Integer.parseInt(thisParts[i]) : 0;
int n = thatPart = i < thatParts.length ? Integer.parseInt(thatParts[i]) : 0;
if (thisPart < thatPart) {
return -1;
}
if (thisPart > thatPart) {
return 1;
}
++i;
}
return 0;
}
@Override
public boolean equals(Object that) {
if (this == that) {
return true;
}
if (that == null) {
return false;
}
if (getClass() != that.getClass()) {
return false;
}
return compareTo((Version)that) == 0;
}
}

279
src/org/json/CDL.java Normal file
View File

@ -0,0 +1,279 @@
package org.json;
/*
Copyright (c) 2002 JSON.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
The Software shall be used for Good, not Evil.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/**
* This provides static methods to convert comma delimited text into a
* JSONArray, and to covert a JSONArray into comma delimited text. Comma
* delimited text is a very popular format for data interchange. It is
* understood by most database, spreadsheet, and organizer programs.
* <p>
* Each row of text represents a row in a table or a data record. Each row
* ends with a NEWLINE character. Each row contains one or more values.
* Values are separated by commas. A value can contain any character except
* for comma, unless is is wrapped in single quotes or double quotes.
* <p>
* The first row usually contains the names of the columns.
* <p>
* A comma delimited list can be converted into a JSONArray of JSONObjects.
* The names for the elements in the JSONObjects can be taken from the names
* in the first row.
* @author JSON.org
* @version 2012-11-13
*/
public class CDL {
/**
* Get the next value. The value can be wrapped in quotes. The value can
* be empty.
* @param x A JSONTokener of the source text.
* @return The value string, or null if empty.
* @throws JSONException if the quoted string is badly formed.
*/
private static String getValue(JSONTokener x) throws JSONException {
char c;
char q;
StringBuffer sb;
do {
c = x.next();
} while (c == ' ' || c == '\t');
switch (c) {
case 0:
return null;
case '"':
case '\'':
q = c;
sb = new StringBuffer();
for (;;) {
c = x.next();
if (c == q) {
break;
}
if (c == 0 || c == '\n' || c == '\r') {
throw x.syntaxError("Missing close quote '" + q + "'.");
}
sb.append(c);
}
return sb.toString();
case ',':
x.back();
return "";
default:
x.back();
return x.nextTo(',');
}
}
/**
* Produce a JSONArray of strings from a row of comma delimited values.
* @param x A JSONTokener of the source text.
* @return A JSONArray of strings.
* @throws JSONException
*/
public static JSONArray rowToJSONArray(JSONTokener x) throws JSONException {
JSONArray ja = new JSONArray();
for (;;) {
String value = getValue(x);
char c = x.next();
if (value == null ||
(ja.length() == 0 && value.length() == 0 && c != ',')) {
return null;
}
ja.put(value);
for (;;) {
if (c == ',') {
break;
}
if (c != ' ') {
if (c == '\n' || c == '\r' || c == 0) {
return ja;
}
throw x.syntaxError("Bad character '" + c + "' (" +
(int)c + ").");
}
c = x.next();
}
}
}
/**
* Produce a JSONObject from a row of comma delimited text, using a
* parallel JSONArray of strings to provides the names of the elements.
* @param names A JSONArray of names. This is commonly obtained from the
* first row of a comma delimited text file using the rowToJSONArray
* method.
* @param x A JSONTokener of the source text.
* @return A JSONObject combining the names and values.
* @throws JSONException
*/
public static JSONObject rowToJSONObject(JSONArray names, JSONTokener x)
throws JSONException {
JSONArray ja = rowToJSONArray(x);
return ja != null ? ja.toJSONObject(names) : null;
}
/**
* Produce a comma delimited text row from a JSONArray. Values containing
* the comma character will be quoted. Troublesome characters may be
* removed.
* @param ja A JSONArray of strings.
* @return A string ending in NEWLINE.
*/
public static String rowToString(JSONArray ja) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < ja.length(); i += 1) {
if (i > 0) {
sb.append(',');
}
Object object = ja.opt(i);
if (object != null) {
String string = object.toString();
if (string.length() > 0 && (string.indexOf(',') >= 0 ||
string.indexOf('\n') >= 0 || string.indexOf('\r') >= 0 ||
string.indexOf(0) >= 0 || string.charAt(0) == '"')) {
sb.append('"');
int length = string.length();
for (int j = 0; j < length; j += 1) {
char c = string.charAt(j);
if (c >= ' ' && c != '"') {
sb.append(c);
}
}
sb.append('"');
} else {
sb.append(string);
}
}
}
sb.append('\n');
return sb.toString();
}
/**
* Produce a JSONArray of JSONObjects from a comma delimited text string,
* using the first row as a source of names.
* @param string The comma delimited text.
* @return A JSONArray of JSONObjects.
* @throws JSONException
*/
public static JSONArray toJSONArray(String string) throws JSONException {
return toJSONArray(new JSONTokener(string));
}
/**
* Produce a JSONArray of JSONObjects from a comma delimited text string,
* using the first row as a source of names.
* @param x The JSONTokener containing the comma delimited text.
* @return A JSONArray of JSONObjects.
* @throws JSONException
*/
public static JSONArray toJSONArray(JSONTokener x) throws JSONException {
return toJSONArray(rowToJSONArray(x), x);
}
/**
* Produce a JSONArray of JSONObjects from a comma delimited text string
* using a supplied JSONArray as the source of element names.
* @param names A JSONArray of strings.
* @param string The comma delimited text.
* @return A JSONArray of JSONObjects.
* @throws JSONException
*/
public static JSONArray toJSONArray(JSONArray names, String string)
throws JSONException {
return toJSONArray(names, new JSONTokener(string));
}
/**
* Produce a JSONArray of JSONObjects from a comma delimited text string
* using a supplied JSONArray as the source of element names.
* @param names A JSONArray of strings.
* @param x A JSONTokener of the source text.
* @return A JSONArray of JSONObjects.
* @throws JSONException
*/
public static JSONArray toJSONArray(JSONArray names, JSONTokener x)
throws JSONException {
if (names == null || names.length() == 0) {
return null;
}
JSONArray ja = new JSONArray();
for (;;) {
JSONObject jo = rowToJSONObject(names, x);
if (jo == null) {
break;
}
ja.put(jo);
}
if (ja.length() == 0) {
return null;
}
return ja;
}
/**
* Produce a comma delimited text from a JSONArray of JSONObjects. The
* first row will be a list of names obtained by inspecting the first
* JSONObject.
* @param ja A JSONArray of JSONObjects.
* @return A comma delimited text.
* @throws JSONException
*/
public static String toString(JSONArray ja) throws JSONException {
JSONObject jo = ja.optJSONObject(0);
if (jo != null) {
JSONArray names = jo.names();
if (names != null) {
return rowToString(names) + toString(names, ja);
}
}
return null;
}
/**
* Produce a comma delimited text from a JSONArray of JSONObjects using
* a provided list of names. The list of names is not included in the
* output.
* @param names A JSONArray of strings.
* @param ja A JSONArray of JSONObjects.
* @return A comma delimited text.
* @throws JSONException
*/
public static String toString(JSONArray names, JSONArray ja)
throws JSONException {
if (names == null || names.length() == 0) {
return null;
}
StringBuffer sb = new StringBuffer();
for (int i = 0; i < ja.length(); i += 1) {
JSONObject jo = ja.optJSONObject(i);
if (jo != null) {
sb.append(rowToString(jo.toJSONArray(names)));
}
}
return sb.toString();
}
}

169
src/org/json/Cookie.java Normal file
View File

@ -0,0 +1,169 @@
package org.json;
/*
Copyright (c) 2002 JSON.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
The Software shall be used for Good, not Evil.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/**
* Convert a web browser cookie specification to a JSONObject and back.
* JSON and Cookies are both notations for name/value pairs.
* @author JSON.org
* @version 2010-12-24
*/
public class Cookie {
/**
* Produce a copy of a string in which the characters '+', '%', '=', ';'
* and control characters are replaced with "%hh". This is a gentle form
* of URL encoding, attempting to cause as little distortion to the
* string as possible. The characters '=' and ';' are meta characters in
* cookies. By convention, they are escaped using the URL-encoding. This is
* only a convention, not a standard. Often, cookies are expected to have
* encoded values. We encode '=' and ';' because we must. We encode '%' and
* '+' because they are meta characters in URL encoding.
* @param string The source string.
* @return The escaped result.
*/
public static String escape(String string) {
char c;
String s = string.trim();
StringBuffer sb = new StringBuffer();
int length = s.length();
for (int i = 0; i < length; i += 1) {
c = s.charAt(i);
if (c < ' ' || c == '+' || c == '%' || c == '=' || c == ';') {
sb.append('%');
sb.append(Character.forDigit((char)((c >>> 4) & 0x0f), 16));
sb.append(Character.forDigit((char)(c & 0x0f), 16));
} else {
sb.append(c);
}
}
return sb.toString();
}
/**
* Convert a cookie specification string into a JSONObject. The string
* will contain a name value pair separated by '='. The name and the value
* will be unescaped, possibly converting '+' and '%' sequences. The
* cookie properties may follow, separated by ';', also represented as
* name=value (except the secure property, which does not have a value).
* The name will be stored under the key "name", and the value will be
* stored under the key "value". This method does not do checking or
* validation of the parameters. It only converts the cookie string into
* a JSONObject.
* @param string The cookie specification string.
* @return A JSONObject containing "name", "value", and possibly other
* members.
* @throws JSONException
*/
public static JSONObject toJSONObject(String string) throws JSONException {
String name;
JSONObject jo = new JSONObject();
Object value;
JSONTokener x = new JSONTokener(string);
jo.put("name", x.nextTo('='));
x.next('=');
jo.put("value", x.nextTo(';'));
x.next();
while (x.more()) {
name = unescape(x.nextTo("=;"));
if (x.next() != '=') {
if (name.equals("secure")) {
value = Boolean.TRUE;
} else {
throw x.syntaxError("Missing '=' in cookie parameter.");
}
} else {
value = unescape(x.nextTo(';'));
x.next();
}
jo.put(name, value);
}
return jo;
}
/**
* Convert a JSONObject into a cookie specification string. The JSONObject
* must contain "name" and "value" members.
* If the JSONObject contains "expires", "domain", "path", or "secure"
* members, they will be appended to the cookie specification string.
* All other members are ignored.
* @param jo A JSONObject
* @return A cookie specification string
* @throws JSONException
*/
public static String toString(JSONObject jo) throws JSONException {
StringBuffer sb = new StringBuffer();
sb.append(escape(jo.getString("name")));
sb.append("=");
sb.append(escape(jo.getString("value")));
if (jo.has("expires")) {
sb.append(";expires=");
sb.append(jo.getString("expires"));
}
if (jo.has("domain")) {
sb.append(";domain=");
sb.append(escape(jo.getString("domain")));
}
if (jo.has("path")) {
sb.append(";path=");
sb.append(escape(jo.getString("path")));
}
if (jo.optBoolean("secure")) {
sb.append(";secure");
}
return sb.toString();
}
/**
* Convert <code>%</code><i>hh</i> sequences to single characters, and
* convert plus to space.
* @param string A string that may contain
* <code>+</code>&nbsp;<small>(plus)</small> and
* <code>%</code><i>hh</i> sequences.
* @return The unescaped string.
*/
public static String unescape(String string) {
int length = string.length();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < length; ++i) {
char c = string.charAt(i);
if (c == '+') {
c = ' ';
} else if (c == '%' && i + 2 < length) {
int d = JSONTokener.dehexchar(string.charAt(i + 1));
int e = JSONTokener.dehexchar(string.charAt(i + 2));
if (d >= 0 && e >= 0) {
c = (char)(d * 16 + e);
i += 2;
}
}
sb.append(c);
}
return sb.toString();
}
}

View File

@ -0,0 +1,90 @@
package org.json;
/*
Copyright (c) 2002 JSON.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
The Software shall be used for Good, not Evil.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import java.util.Iterator;
/**
* Convert a web browser cookie list string to a JSONObject and back.
* @author JSON.org
* @version 2010-12-24
*/
public class CookieList {
/**
* Convert a cookie list into a JSONObject. A cookie list is a sequence
* of name/value pairs. The names are separated from the values by '='.
* The pairs are separated by ';'. The names and the values
* will be unescaped, possibly converting '+' and '%' sequences.
*
* To add a cookie to a cooklist,
* cookielistJSONObject.put(cookieJSONObject.getString("name"),
* cookieJSONObject.getString("value"));
* @param string A cookie list string
* @return A JSONObject
* @throws JSONException
*/
public static JSONObject toJSONObject(String string) throws JSONException {
JSONObject jo = new JSONObject();
JSONTokener x = new JSONTokener(string);
while (x.more()) {
String name = Cookie.unescape(x.nextTo('='));
x.next('=');
jo.put(name, Cookie.unescape(x.nextTo(';')));
x.next();
}
return jo;
}
/**
* Convert a JSONObject into a cookie list. A cookie list is a sequence
* of name/value pairs. The names are separated from the values by '='.
* The pairs are separated by ';'. The characters '%', '+', '=', and ';'
* in the names and values are replaced by "%hh".
* @param jo A JSONObject
* @return A cookie list string
* @throws JSONException
*/
public static String toString(JSONObject jo) throws JSONException {
boolean b = false;
Iterator keys = jo.keys();
String string;
StringBuffer sb = new StringBuffer();
while (keys.hasNext()) {
string = keys.next().toString();
if (!jo.isNull(string)) {
if (b) {
sb.append(';');
}
sb.append(Cookie.escape(string));
sb.append("=");
sb.append(Cookie.escape(jo.getString(string)));
b = true;
}
}
return sb.toString();
}
}

163
src/org/json/HTTP.java Normal file
View File

@ -0,0 +1,163 @@
package org.json;
/*
Copyright (c) 2002 JSON.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
The Software shall be used for Good, not Evil.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import java.util.Iterator;
/**
* Convert an HTTP header to a JSONObject and back.
* @author JSON.org
* @version 2010-12-24
*/
public class HTTP {
/** Carriage return/line feed. */
public static final String CRLF = "\r\n";
/**
* Convert an HTTP header string into a JSONObject. It can be a request
* header or a response header. A request header will contain
* <pre>{
* Method: "POST" (for example),
* "Request-URI": "/" (for example),
* "HTTP-Version": "HTTP/1.1" (for example)
* }</pre>
* A response header will contain
* <pre>{
* "HTTP-Version": "HTTP/1.1" (for example),
* "Status-Code": "200" (for example),
* "Reason-Phrase": "OK" (for example)
* }</pre>
* In addition, the other parameters in the header will be captured, using
* the HTTP field names as JSON names, so that <pre>
* Date: Sun, 26 May 2002 18:06:04 GMT
* Cookie: Q=q2=PPEAsg--; B=677gi6ouf29bn&b=2&f=s
* Cache-Control: no-cache</pre>
* become
* <pre>{...
* Date: "Sun, 26 May 2002 18:06:04 GMT",
* Cookie: "Q=q2=PPEAsg--; B=677gi6ouf29bn&b=2&f=s",
* "Cache-Control": "no-cache",
* ...}</pre>
* It does no further checking or conversion. It does not parse dates.
* It does not do '%' transforms on URLs.
* @param string An HTTP header string.
* @return A JSONObject containing the elements and attributes
* of the XML string.
* @throws JSONException
*/
public static JSONObject toJSONObject(String string) throws JSONException {
JSONObject jo = new JSONObject();
HTTPTokener x = new HTTPTokener(string);
String token;
token = x.nextToken();
if (token.toUpperCase().startsWith("HTTP")) {
// Response
jo.put("HTTP-Version", token);
jo.put("Status-Code", x.nextToken());
jo.put("Reason-Phrase", x.nextTo('\0'));
x.next();
} else {
// Request
jo.put("Method", token);
jo.put("Request-URI", x.nextToken());
jo.put("HTTP-Version", x.nextToken());
}
// Fields
while (x.more()) {
String name = x.nextTo(':');
x.next(':');
jo.put(name, x.nextTo('\0'));
x.next();
}
return jo;
}
/**
* Convert a JSONObject into an HTTP header. A request header must contain
* <pre>{
* Method: "POST" (for example),
* "Request-URI": "/" (for example),
* "HTTP-Version": "HTTP/1.1" (for example)
* }</pre>
* A response header must contain
* <pre>{
* "HTTP-Version": "HTTP/1.1" (for example),
* "Status-Code": "200" (for example),
* "Reason-Phrase": "OK" (for example)
* }</pre>
* Any other members of the JSONObject will be output as HTTP fields.
* The result will end with two CRLF pairs.
* @param jo A JSONObject
* @return An HTTP header string.
* @throws JSONException if the object does not contain enough
* information.
*/
public static String toString(JSONObject jo) throws JSONException {
Iterator keys = jo.keys();
String string;
StringBuffer sb = new StringBuffer();
if (jo.has("Status-Code") && jo.has("Reason-Phrase")) {
sb.append(jo.getString("HTTP-Version"));
sb.append(' ');
sb.append(jo.getString("Status-Code"));
sb.append(' ');
sb.append(jo.getString("Reason-Phrase"));
} else if (jo.has("Method") && jo.has("Request-URI")) {
sb.append(jo.getString("Method"));
sb.append(' ');
sb.append('"');
sb.append(jo.getString("Request-URI"));
sb.append('"');
sb.append(' ');
sb.append(jo.getString("HTTP-Version"));
} else {
throw new JSONException("Not enough material for an HTTP header.");
}
sb.append(CRLF);
while (keys.hasNext()) {
string = keys.next().toString();
if (!"HTTP-Version".equals(string) && !"Status-Code".equals(string) &&
!"Reason-Phrase".equals(string) && !"Method".equals(string) &&
!"Request-URI".equals(string) && !jo.isNull(string)) {
sb.append(string);
sb.append(": ");
sb.append(jo.getString(string));
sb.append(CRLF);
}
}
sb.append(CRLF);
return sb.toString();
}
}

View File

@ -0,0 +1,77 @@
package org.json;
/*
Copyright (c) 2002 JSON.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
The Software shall be used for Good, not Evil.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/**
* The HTTPTokener extends the JSONTokener to provide additional methods
* for the parsing of HTTP headers.
* @author JSON.org
* @version 2012-11-13
*/
public class HTTPTokener extends JSONTokener {
/**
* Construct an HTTPTokener from a string.
* @param string A source string.
*/
public HTTPTokener(String string) {
super(string);
}
/**
* Get the next token or string. This is used in parsing HTTP headers.
* @throws JSONException
* @return A String.
*/
public String nextToken() throws JSONException {
char c;
char q;
StringBuffer sb = new StringBuffer();
do {
c = next();
} while (Character.isWhitespace(c));
if (c == '"' || c == '\'') {
q = c;
for (;;) {
c = next();
if (c < ' ') {
throw syntaxError("Unterminated string.");
}
if (c == q) {
return sb.toString();
}
sb.append(c);
}
}
for (;;) {
if (c == 0 || Character.isWhitespace(c)) {
return sb.toString();
}
sb.append(c);
c = next();
}
}
}

906
src/org/json/JSONArray.java Normal file
View File

@ -0,0 +1,906 @@
package org.json;
/*
Copyright (c) 2002 JSON.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
The Software shall be used for Good, not Evil.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
/**
* A JSONArray is an ordered sequence of values. Its external text form is a
* string wrapped in square brackets with commas separating the values. The
* internal form is an object having <code>get</code> and <code>opt</code>
* methods for accessing the values by index, and <code>put</code> methods for
* adding or replacing values. The values can be any of these types:
* <code>Boolean</code>, <code>JSONArray</code>, <code>JSONObject</code>,
* <code>Number</code>, <code>String</code>, or the
* <code>JSONObject.NULL object</code>.
* <p>
* The constructor can convert a JSON text into a Java object. The
* <code>toString</code> method converts to JSON text.
* <p>
* A <code>get</code> method returns a value if one can be found, and throws an
* exception if one cannot be found. An <code>opt</code> method returns a
* default value instead of throwing an exception, and so is useful for
* obtaining optional values.
* <p>
* The generic <code>get()</code> and <code>opt()</code> methods return an
* object which you can cast or query for type. There are also typed
* <code>get</code> and <code>opt</code> methods that do type checking and type
* coercion for you.
* <p>
* The texts produced by the <code>toString</code> methods strictly conform to
* JSON syntax rules. The constructors are more forgiving in the texts they will
* accept:
* <ul>
* <li>An extra <code>,</code>&nbsp;<small>(comma)</small> may appear just
* before the closing bracket.</li>
* <li>The <code>null</code> value will be inserted when there is <code>,</code>
* &nbsp;<small>(comma)</small> elision.</li>
* <li>Strings may be quoted with <code>'</code>&nbsp;<small>(single
* quote)</small>.</li>
* <li>Strings do not need to be quoted at all if they do not begin with a quote
* or single quote, and if they do not contain leading or trailing spaces, and
* if they do not contain any of these characters:
* <code>{ } [ ] / \ : , = ; #</code> and if they do not look like numbers and
* if they are not the reserved words <code>true</code>, <code>false</code>, or
* <code>null</code>.</li>
* <li>Values can be separated by <code>;</code> <small>(semicolon)</small> as
* well as by <code>,</code> <small>(comma)</small>.</li>
* </ul>
*
* @author JSON.org
* @version 2012-11-13
*/
public class JSONArray {
/**
* The arrayList where the JSONArray's properties are kept.
*/
private final ArrayList myArrayList;
/**
* Construct an empty JSONArray.
*/
public JSONArray() {
this.myArrayList = new ArrayList();
}
/**
* Construct a JSONArray from a JSONTokener.
* @param x A JSONTokener
* @throws JSONException If there is a syntax error.
*/
public JSONArray(JSONTokener x) throws JSONException {
this();
if (x.nextClean() != '[') {
throw x.syntaxError("A JSONArray text must start with '['");
}
if (x.nextClean() != ']') {
x.back();
for (;;) {
if (x.nextClean() == ',') {
x.back();
this.myArrayList.add(JSONObject.NULL);
} else {
x.back();
this.myArrayList.add(x.nextValue());
}
switch (x.nextClean()) {
case ';':
case ',':
if (x.nextClean() == ']') {
return;
}
x.back();
break;
case ']':
return;
default:
throw x.syntaxError("Expected a ',' or ']'");
}
}
}
}
/**
* Construct a JSONArray from a source JSON text.
* @param source A string that begins with
* <code>[</code>&nbsp;<small>(left bracket)</small>
* and ends with <code>]</code>&nbsp;<small>(right bracket)</small>.
* @throws JSONException If there is a syntax error.
*/
public JSONArray(String source) throws JSONException {
this(new JSONTokener(source));
}
/**
* Construct a JSONArray from a Collection.
* @param collection A Collection.
*/
public JSONArray(Collection collection) {
this.myArrayList = new ArrayList();
if (collection != null) {
Iterator iter = collection.iterator();
while (iter.hasNext()) {
this.myArrayList.add(JSONObject.wrap(iter.next()));
}
}
}
/**
* Construct a JSONArray from an array
* @throws JSONException If not an array.
*/
public JSONArray(Object array) throws JSONException {
this();
if (array.getClass().isArray()) {
int length = Array.getLength(array);
for (int i = 0; i < length; i += 1) {
this.put(JSONObject.wrap(Array.get(array, i)));
}
} else {
throw new JSONException(
"JSONArray initial value should be a string or collection or array.");
}
}
/**
* Get the object value associated with an index.
* @param index
* The index must be between 0 and length() - 1.
* @return An object value.
* @throws JSONException If there is no value for the index.
*/
public Object get(int index) throws JSONException {
Object object = this.opt(index);
if (object == null) {
throw new JSONException("JSONArray[" + index + "] not found.");
}
return object;
}
/**
* Get the boolean value associated with an index.
* The string values "true" and "false" are converted to boolean.
*
* @param index The index must be between 0 and length() - 1.
* @return The truth.
* @throws JSONException If there is no value for the index or if the
* value is not convertible to boolean.
*/
public boolean getBoolean(int index) throws JSONException {
Object object = this.get(index);
if (object.equals(Boolean.FALSE) ||
(object instanceof String &&
((String)object).equalsIgnoreCase("false"))) {
return false;
} else if (object.equals(Boolean.TRUE) ||
(object instanceof String &&
((String)object).equalsIgnoreCase("true"))) {
return true;
}
throw new JSONException("JSONArray[" + index + "] is not a boolean.");
}
/**
* Get the double value associated with an index.
*
* @param index The index must be between 0 and length() - 1.
* @return The value.
* @throws JSONException If the key is not found or if the value cannot
* be converted to a number.
*/
public double getDouble(int index) throws JSONException {
Object object = this.get(index);
try {
return object instanceof Number
? ((Number)object).doubleValue()
: Double.parseDouble((String)object);
} catch (Exception e) {
throw new JSONException("JSONArray[" + index +
"] is not a number.");
}
}
/**
* Get the int value associated with an index.
*
* @param index The index must be between 0 and length() - 1.
* @return The value.
* @throws JSONException If the key is not found or if the value is not a number.
*/
public int getInt(int index) throws JSONException {
Object object = this.get(index);
try {
return object instanceof Number
? ((Number)object).intValue()
: Integer.parseInt((String)object);
} catch (Exception e) {
throw new JSONException("JSONArray[" + index +
"] is not a number.");
}
}
/**
* Get the JSONArray associated with an index.
* @param index The index must be between 0 and length() - 1.
* @return A JSONArray value.
* @throws JSONException If there is no value for the index. or if the
* value is not a JSONArray
*/
public JSONArray getJSONArray(int index) throws JSONException {
Object object = this.get(index);
if (object instanceof JSONArray) {
return (JSONArray)object;
}
throw new JSONException("JSONArray[" + index +
"] is not a JSONArray.");
}
/**
* Get the JSONObject associated with an index.
* @param index subscript
* @return A JSONObject value.
* @throws JSONException If there is no value for the index or if the
* value is not a JSONObject
*/
public JSONObject getJSONObject(int index) throws JSONException {
Object object = this.get(index);
if (object instanceof JSONObject) {
return (JSONObject)object;
}
throw new JSONException("JSONArray[" + index +
"] is not a JSONObject.");
}
/**
* Get the long value associated with an index.
*
* @param index The index must be between 0 and length() - 1.
* @return The value.
* @throws JSONException If the key is not found or if the value cannot
* be converted to a number.
*/
public long getLong(int index) throws JSONException {
Object object = this.get(index);
try {
return object instanceof Number
? ((Number)object).longValue()
: Long.parseLong((String)object);
} catch (Exception e) {
throw new JSONException("JSONArray[" + index +
"] is not a number.");
}
}
/**
* Get the string associated with an index.
* @param index The index must be between 0 and length() - 1.
* @return A string value.
* @throws JSONException If there is no string value for the index.
*/
public String getString(int index) throws JSONException {
Object object = this.get(index);
if (object instanceof String) {
return (String)object;
}
throw new JSONException("JSONArray[" + index + "] not a string.");
}
/**
* Determine if the value is null.
* @param index The index must be between 0 and length() - 1.
* @return true if the value at the index is null, or if there is no value.
*/
public boolean isNull(int index) {
return JSONObject.NULL.equals(this.opt(index));
}
/**
* Make a string from the contents of this JSONArray. The
* <code>separator</code> string is inserted between each element.
* Warning: This method assumes that the data structure is acyclical.
* @param separator A string that will be inserted between the elements.
* @return a string.
* @throws JSONException If the array contains an invalid number.
*/
public String join(String separator) throws JSONException {
int len = this.length();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < len; i += 1) {
if (i > 0) {
sb.append(separator);
}
sb.append(JSONObject.valueToString(this.myArrayList.get(i)));
}
return sb.toString();
}
/**
* Get the number of elements in the JSONArray, included nulls.
*
* @return The length (or size).
*/
public int length() {
return this.myArrayList.size();
}
/**
* Get the optional object value associated with an index.
* @param index The index must be between 0 and length() - 1.
* @return An object value, or null if there is no
* object at that index.
*/
public Object opt(int index) {
return (index < 0 || index >= this.length())
? null
: this.myArrayList.get(index);
}
/**
* Get the optional boolean value associated with an index.
* It returns false if there is no value at that index,
* or if the value is not Boolean.TRUE or the String "true".
*
* @param index The index must be between 0 and length() - 1.
* @return The truth.
*/
public boolean optBoolean(int index) {
return this.optBoolean(index, false);
}
/**
* Get the optional boolean value associated with an index.
* It returns the defaultValue if there is no value at that index or if
* it is not a Boolean or the String "true" or "false" (case insensitive).
*
* @param index The index must be between 0 and length() - 1.
* @param defaultValue A boolean default.
* @return The truth.
*/
public boolean optBoolean(int index, boolean defaultValue) {
try {
return this.getBoolean(index);
} catch (Exception e) {
return defaultValue;
}
}
/**
* Get the optional double value associated with an index.
* NaN is returned if there is no value for the index,
* or if the value is not a number and cannot be converted to a number.
*
* @param index The index must be between 0 and length() - 1.
* @return The value.
*/
public double optDouble(int index) {
return this.optDouble(index, Double.NaN);
}
/**
* Get the optional double value associated with an index.
* The defaultValue is returned if there is no value for the index,
* or if the value is not a number and cannot be converted to a number.
*
* @param index subscript
* @param defaultValue The default value.
* @return The value.
*/
public double optDouble(int index, double defaultValue) {
try {
return this.getDouble(index);
} catch (Exception e) {
return defaultValue;
}
}
/**
* Get the optional int value associated with an index.
* Zero is returned if there is no value for the index,
* or if the value is not a number and cannot be converted to a number.
*
* @param index The index must be between 0 and length() - 1.
* @return The value.
*/
public int optInt(int index) {
return this.optInt(index, 0);
}
/**
* Get the optional int value associated with an index.
* The defaultValue is returned if there is no value for the index,
* or if the value is not a number and cannot be converted to a number.
* @param index The index must be between 0 and length() - 1.
* @param defaultValue The default value.
* @return The value.
*/
public int optInt(int index, int defaultValue) {
try {
return this.getInt(index);
} catch (Exception e) {
return defaultValue;
}
}
/**
* Get the optional JSONArray associated with an index.
* @param index subscript
* @return A JSONArray value, or null if the index has no value,
* or if the value is not a JSONArray.
*/
public JSONArray optJSONArray(int index) {
Object o = this.opt(index);
return o instanceof JSONArray ? (JSONArray)o : null;
}
/**
* Get the optional JSONObject associated with an index.
* Null is returned if the key is not found, or null if the index has
* no value, or if the value is not a JSONObject.
*
* @param index The index must be between 0 and length() - 1.
* @return A JSONObject value.
*/
public JSONObject optJSONObject(int index) {
Object o = this.opt(index);
return o instanceof JSONObject ? (JSONObject)o : null;
}
/**
* Get the optional long value associated with an index.
* Zero is returned if there is no value for the index,
* or if the value is not a number and cannot be converted to a number.
*
* @param index The index must be between 0 and length() - 1.
* @return The value.
*/
public long optLong(int index) {
return this.optLong(index, 0);
}
/**
* Get the optional long value associated with an index.
* The defaultValue is returned if there is no value for the index,
* or if the value is not a number and cannot be converted to a number.
* @param index The index must be between 0 and length() - 1.
* @param defaultValue The default value.
* @return The value.
*/
public long optLong(int index, long defaultValue) {
try {
return this.getLong(index);
} catch (Exception e) {
return defaultValue;
}
}
/**
* Get the optional string value associated with an index. It returns an
* empty string if there is no value at that index. If the value
* is not a string and is not null, then it is coverted to a string.
*
* @param index The index must be between 0 and length() - 1.
* @return A String value.
*/
public String optString(int index) {
return this.optString(index, "");
}
/**
* Get the optional string associated with an index.
* The defaultValue is returned if the key is not found.
*
* @param index The index must be between 0 and length() - 1.
* @param defaultValue The default value.
* @return A String value.
*/
public String optString(int index, String defaultValue) {
Object object = this.opt(index);
return JSONObject.NULL.equals(object)
? defaultValue
: object.toString();
}
/**
* Append a boolean value. This increases the array's length by one.
*
* @param value A boolean value.
* @return this.
*/
public JSONArray put(boolean value) {
this.put(value ? Boolean.TRUE : Boolean.FALSE);
return this;
}
/**
* Put a value in the JSONArray, where the value will be a
* JSONArray which is produced from a Collection.
* @param value A Collection value.
* @return this.
*/
public JSONArray put(Collection value) {
this.put(new JSONArray(value));
return this;
}
/**
* Append a double value. This increases the array's length by one.
*
* @param value A double value.
* @throws JSONException if the value is not finite.
* @return this.
*/
public JSONArray put(double value) throws JSONException {
Double d = new Double(value);
JSONObject.testValidity(d);
this.put(d);
return this;
}
/**
* Append an int value. This increases the array's length by one.
*
* @param value An int value.
* @return this.
*/
public JSONArray put(int value) {
this.put(new Integer(value));
return this;
}
/**
* Append an long value. This increases the array's length by one.
*
* @param value A long value.
* @return this.
*/
public JSONArray put(long value) {
this.put(new Long(value));
return this;
}
/**
* Put a value in the JSONArray, where the value will be a
* JSONObject which is produced from a Map.
* @param value A Map value.
* @return this.
*/
public JSONArray put(Map value) {
this.put(new JSONObject(value));
return this;
}
/**
* Append an object value. This increases the array's length by one.
* @param value An object value. The value should be a
* Boolean, Double, Integer, JSONArray, JSONObject, Long, or String, or the
* JSONObject.NULL object.
* @return this.
*/
public JSONArray put(Object value) {
this.myArrayList.add(value);
return this;
}
/**
* Put or replace a boolean value in the JSONArray. If the index is greater
* than the length of the JSONArray, then null elements will be added as
* necessary to pad it out.
* @param index The subscript.
* @param value A boolean value.
* @return this.
* @throws JSONException If the index is negative.
*/
public JSONArray put(int index, boolean value) throws JSONException {
this.put(index, value ? Boolean.TRUE : Boolean.FALSE);
return this;
}
/**
* Put a value in the JSONArray, where the value will be a
* JSONArray which is produced from a Collection.
* @param index The subscript.
* @param value A Collection value.
* @return this.
* @throws JSONException If the index is negative or if the value is
* not finite.
*/
public JSONArray put(int index, Collection value) throws JSONException {
this.put(index, new JSONArray(value));
return this;
}
/**
* Put or replace a double value. If the index is greater than the length of
* the JSONArray, then null elements will be added as necessary to pad
* it out.
* @param index The subscript.
* @param value A double value.
* @return this.
* @throws JSONException If the index is negative or if the value is
* not finite.
*/
public JSONArray put(int index, double value) throws JSONException {
this.put(index, new Double(value));
return this;
}
/**
* Put or replace an int value. If the index is greater than the length of
* the JSONArray, then null elements will be added as necessary to pad
* it out.
* @param index The subscript.
* @param value An int value.
* @return this.
* @throws JSONException If the index is negative.
*/
public JSONArray put(int index, int value) throws JSONException {
this.put(index, new Integer(value));
return this;
}
/**
* Put or replace a long value. If the index is greater than the length of
* the JSONArray, then null elements will be added as necessary to pad
* it out.
* @param index The subscript.
* @param value A long value.
* @return this.
* @throws JSONException If the index is negative.
*/
public JSONArray put(int index, long value) throws JSONException {
this.put(index, new Long(value));
return this;
}
/**
* Put a value in the JSONArray, where the value will be a
* JSONObject that is produced from a Map.
* @param index The subscript.
* @param value The Map value.
* @return this.
* @throws JSONException If the index is negative or if the the value is
* an invalid number.
*/
public JSONArray put(int index, Map value) throws JSONException {
this.put(index, new JSONObject(value));
return this;
}
/**
* Put or replace an object value in the JSONArray. If the index is greater
* than the length of the JSONArray, then null elements will be added as
* necessary to pad it out.
* @param index The subscript.
* @param value The value to put into the array. The value should be a
* Boolean, Double, Integer, JSONArray, JSONObject, Long, or String, or the
* JSONObject.NULL object.
* @return this.
* @throws JSONException If the index is negative or if the the value is
* an invalid number.
*/
public JSONArray put(int index, Object value) throws JSONException {
JSONObject.testValidity(value);
if (index < 0) {
throw new JSONException("JSONArray[" + index + "] not found.");
}
if (index < this.length()) {
this.myArrayList.set(index, value);
} else {
while (index != this.length()) {
this.put(JSONObject.NULL);
}
this.put(value);
}
return this;
}
/**
* Remove an index and close the hole.
* @param index The index of the element to be removed.
* @return The value that was associated with the index,
* or null if there was no value.
*/
public Object remove(int index) {
Object o = this.opt(index);
this.myArrayList.remove(index);
return o;
}
/**
* Produce a JSONObject by combining a JSONArray of names with the values
* of this JSONArray.
* @param names A JSONArray containing a list of key strings. These will be
* paired with the values.
* @return A JSONObject, or null if there are no names or if this JSONArray
* has no values.
* @throws JSONException If any of the names are null.
*/
public JSONObject toJSONObject(JSONArray names) throws JSONException {
if (names == null || names.length() == 0 || this.length() == 0) {
return null;
}
JSONObject jo = new JSONObject();
for (int i = 0; i < names.length(); i += 1) {
jo.put(names.getString(i), this.opt(i));
}
return jo;
}
/**
* Make a JSON text of this JSONArray. For compactness, no
* unnecessary whitespace is added. If it is not possible to produce a
* syntactically correct JSON text then null will be returned instead. This
* could occur if the array contains an invalid number.
* <p>
* Warning: This method assumes that the data structure is acyclical.
*
* @return a printable, displayable, transmittable
* representation of the array.
*/
public String toString() {
try {
return this.toString(0);
} catch (Exception e) {
return null;
}
}
/**
* Make a prettyprinted JSON text of this JSONArray.
* Warning: This method assumes that the data structure is acyclical.
* @param indentFactor The number of spaces to add to each level of
* indentation.
* @return a printable, displayable, transmittable
* representation of the object, beginning
* with <code>[</code>&nbsp;<small>(left bracket)</small> and ending
* with <code>]</code>&nbsp;<small>(right bracket)</small>.
* @throws JSONException
*/
public String toString(int indentFactor) throws JSONException {
StringWriter sw = new StringWriter();
synchronized (sw.getBuffer()) {
return this.write(sw, indentFactor, 0).toString();
}
}
/**
* Write the contents of the JSONArray as JSON text to a writer. For
* compactness, no whitespace is added.
* <p>
* Warning: This method assumes that the data structure is acyclical.
*
* @return The writer.
* @throws JSONException
*/
public Writer write(Writer writer) throws JSONException {
return this.write(writer, 0, 0);
}
/**
* Write the contents of the JSONArray as JSON text to a writer. For
* compactness, no whitespace is added.
* <p>
* Warning: This method assumes that the data structure is acyclical.
*
* @param indentFactor
* The number of spaces to add to each level of indentation.
* @param indent
* The indention of the top level.
* @return The writer.
* @throws JSONException
*/
Writer write(Writer writer, int indentFactor, int indent)
throws JSONException {
try {
boolean commanate = false;
int length = this.length();
writer.write('[');
if (length == 1) {
JSONObject.writeValue(writer, this.myArrayList.get(0),
indentFactor, indent);
} else if (length != 0) {
final int newindent = indent + indentFactor;
for (int i = 0; i < length; i += 1) {
if (commanate) {
writer.write(',');
}
if (indentFactor > 0) {
writer.write('\n');
}
JSONObject.indent(writer, newindent);
JSONObject.writeValue(writer, this.myArrayList.get(i),
indentFactor, newindent);
commanate = true;
}
if (indentFactor > 0) {
writer.write('\n');
}
JSONObject.indent(writer, indent);
}
writer.write(']');
return writer;
} catch (IOException e) {
throw new JSONException(e);
}
}
}

View File

@ -0,0 +1,28 @@
package org.json;
/**
* The JSONException is thrown by the JSON.org classes when things are amiss.
* @author JSON.org
* @version 2010-12-24
*/
public class JSONException extends Exception {
private static final long serialVersionUID = 0;
private Throwable cause;
/**
* Constructs a JSONException with an explanatory message.
* @param message Detail about the reason for the exception.
*/
public JSONException(String message) {
super(message);
}
public JSONException(Throwable cause) {
super(cause.getMessage());
this.cause = cause;
}
public Throwable getCause() {
return this.cause;
}
}

467
src/org/json/JSONML.java Normal file
View File

@ -0,0 +1,467 @@
package org.json;
/*
Copyright (c) 2008 JSON.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
The Software shall be used for Good, not Evil.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import java.util.Iterator;
/**
* This provides static methods to convert an XML text into a JSONArray or
* JSONObject, and to covert a JSONArray or JSONObject into an XML text using
* the JsonML transform.
*
* @author JSON.org
* @version 2012-03-28
*/
public class JSONML {
/**
* Parse XML values and store them in a JSONArray.
* @param x The XMLTokener containing the source string.
* @param arrayForm true if array form, false if object form.
* @param ja The JSONArray that is containing the current tag or null
* if we are at the outermost level.
* @return A JSONArray if the value is the outermost tag, otherwise null.
* @throws JSONException
*/
private static Object parse(
XMLTokener x,
boolean arrayForm,
JSONArray ja
) throws JSONException {
String attribute;
char c;
String closeTag = null;
int i;
JSONArray newja = null;
JSONObject newjo = null;
Object token;
String tagName = null;
// Test for and skip past these forms:
// <!-- ... -->
// <![ ... ]]>
// <! ... >
// <? ... ?>
while (true) {
if (!x.more()) {
throw x.syntaxError("Bad XML");
}
token = x.nextContent();
if (token == XML.LT) {
token = x.nextToken();
if (token instanceof Character) {
if (token == XML.SLASH) {
// Close tag </
token = x.nextToken();
if (!(token instanceof String)) {
throw new JSONException(
"Expected a closing name instead of '" +
token + "'.");
}
if (x.nextToken() != XML.GT) {
throw x.syntaxError("Misshaped close tag");
}
return token;
} else if (token == XML.BANG) {
// <!
c = x.next();
if (c == '-') {
if (x.next() == '-') {
x.skipPast("-->");
} else {
x.back();
}
} else if (c == '[') {
token = x.nextToken();
if (token.equals("CDATA") && x.next() == '[') {
if (ja != null) {
ja.put(x.nextCDATA());
}
} else {
throw x.syntaxError("Expected 'CDATA['");
}
} else {
i = 1;
do {
token = x.nextMeta();
if (token == null) {
throw x.syntaxError("Missing '>' after '<!'.");
} else if (token == XML.LT) {
i += 1;
} else if (token == XML.GT) {
i -= 1;
}
} while (i > 0);
}
} else if (token == XML.QUEST) {
// <?
x.skipPast("?>");
} else {
throw x.syntaxError("Misshaped tag");
}
// Open tag <
} else {
if (!(token instanceof String)) {
throw x.syntaxError("Bad tagName '" + token + "'.");
}
tagName = (String)token;
newja = new JSONArray();
newjo = new JSONObject();
if (arrayForm) {
newja.put(tagName);
if (ja != null) {
ja.put(newja);
}
} else {
newjo.put("tagName", tagName);
if (ja != null) {
ja.put(newjo);
}
}
token = null;
for (;;) {
if (token == null) {
token = x.nextToken();
}
if (token == null) {
throw x.syntaxError("Misshaped tag");
}
if (!(token instanceof String)) {
break;
}
// attribute = value
attribute = (String)token;
if (!arrayForm && ("tagName".equals(attribute) || "childNode".equals(attribute))) {
throw x.syntaxError("Reserved attribute.");
}
token = x.nextToken();
if (token == XML.EQ) {
token = x.nextToken();
if (!(token instanceof String)) {
throw x.syntaxError("Missing value");
}
newjo.accumulate(attribute, XML.stringToValue((String)token));
token = null;
} else {
newjo.accumulate(attribute, "");
}
}
if (arrayForm && newjo.length() > 0) {
newja.put(newjo);
}
// Empty tag <.../>
if (token == XML.SLASH) {
if (x.nextToken() != XML.GT) {
throw x.syntaxError("Misshaped tag");
}
if (ja == null) {
if (arrayForm) {
return newja;
} else {
return newjo;
}
}
// Content, between <...> and </...>
} else {
if (token != XML.GT) {
throw x.syntaxError("Misshaped tag");
}
closeTag = (String)parse(x, arrayForm, newja);
if (closeTag != null) {
if (!closeTag.equals(tagName)) {
throw x.syntaxError("Mismatched '" + tagName +
"' and '" + closeTag + "'");
}
tagName = null;
if (!arrayForm && newja.length() > 0) {
newjo.put("childNodes", newja);
}
if (ja == null) {
if (arrayForm) {
return newja;
} else {
return newjo;
}
}
}
}
}
} else {
if (ja != null) {
ja.put(token instanceof String
? XML.stringToValue((String)token)
: token);
}
}
}
}
/**
* Convert a well-formed (but not necessarily valid) XML string into a
* JSONArray using the JsonML transform. Each XML tag is represented as
* a JSONArray in which the first element is the tag name. If the tag has
* attributes, then the second element will be JSONObject containing the
* name/value pairs. If the tag contains children, then strings and
* JSONArrays will represent the child tags.
* Comments, prologs, DTDs, and <code>&lt;[ [ ]]></code> are ignored.
* @param string The source string.
* @return A JSONArray containing the structured data from the XML string.
* @throws JSONException
*/
public static JSONArray toJSONArray(String string) throws JSONException {
return toJSONArray(new XMLTokener(string));
}
/**
* Convert a well-formed (but not necessarily valid) XML string into a
* JSONArray using the JsonML transform. Each XML tag is represented as
* a JSONArray in which the first element is the tag name. If the tag has
* attributes, then the second element will be JSONObject containing the
* name/value pairs. If the tag contains children, then strings and
* JSONArrays will represent the child content and tags.
* Comments, prologs, DTDs, and <code>&lt;[ [ ]]></code> are ignored.
* @param x An XMLTokener.
* @return A JSONArray containing the structured data from the XML string.
* @throws JSONException
*/
public static JSONArray toJSONArray(XMLTokener x) throws JSONException {
return (JSONArray)parse(x, true, null);
}
/**
* Convert a well-formed (but not necessarily valid) XML string into a
* JSONObject using the JsonML transform. Each XML tag is represented as
* a JSONObject with a "tagName" property. If the tag has attributes, then
* the attributes will be in the JSONObject as properties. If the tag
* contains children, the object will have a "childNodes" property which
* will be an array of strings and JsonML JSONObjects.
* Comments, prologs, DTDs, and <code>&lt;[ [ ]]></code> are ignored.
* @param x An XMLTokener of the XML source text.
* @return A JSONObject containing the structured data from the XML string.
* @throws JSONException
*/
public static JSONObject toJSONObject(XMLTokener x) throws JSONException {
return (JSONObject)parse(x, false, null);
}
/**
* Convert a well-formed (but not necessarily valid) XML string into a
* JSONObject using the JsonML transform. Each XML tag is represented as
* a JSONObject with a "tagName" property. If the tag has attributes, then
* the attributes will be in the JSONObject as properties. If the tag
* contains children, the object will have a "childNodes" property which
* will be an array of strings and JsonML JSONObjects.
* Comments, prologs, DTDs, and <code>&lt;[ [ ]]></code> are ignored.
* @param string The XML source text.
* @return A JSONObject containing the structured data from the XML string.
* @throws JSONException
*/
public static JSONObject toJSONObject(String string) throws JSONException {
return toJSONObject(new XMLTokener(string));
}
/**
* Reverse the JSONML transformation, making an XML text from a JSONArray.
* @param ja A JSONArray.
* @return An XML string.
* @throws JSONException
*/
public static String toString(JSONArray ja) throws JSONException {
int i;
JSONObject jo;
String key;
Iterator keys;
int length;
Object object;
StringBuffer sb = new StringBuffer();
String tagName;
String value;
// Emit <tagName
tagName = ja.getString(0);
XML.noSpace(tagName);
tagName = XML.escape(tagName);
sb.append('<');
sb.append(tagName);
object = ja.opt(1);
if (object instanceof JSONObject) {
i = 2;
jo = (JSONObject)object;
// Emit the attributes
keys = jo.keys();
while (keys.hasNext()) {
key = keys.next().toString();
XML.noSpace(key);
value = jo.optString(key);
if (value != null) {
sb.append(' ');
sb.append(XML.escape(key));
sb.append('=');
sb.append('"');
sb.append(XML.escape(value));
sb.append('"');
}
}
} else {
i = 1;
}
//Emit content in body
length = ja.length();
if (i >= length) {
sb.append('/');
sb.append('>');
} else {
sb.append('>');
do {
object = ja.get(i);
i += 1;
if (object != null) {
if (object instanceof String) {
sb.append(XML.escape(object.toString()));
} else if (object instanceof JSONObject) {
sb.append(toString((JSONObject)object));
} else if (object instanceof JSONArray) {
sb.append(toString((JSONArray)object));
}
}
} while (i < length);
sb.append('<');
sb.append('/');
sb.append(tagName);
sb.append('>');
}
return sb.toString();
}
/**
* Reverse the JSONML transformation, making an XML text from a JSONObject.
* The JSONObject must contain a "tagName" property. If it has children,
* then it must have a "childNodes" property containing an array of objects.
* The other properties are attributes with string values.
* @param jo A JSONObject.
* @return An XML string.
* @throws JSONException
*/
public static String toString(JSONObject jo) throws JSONException {
StringBuffer sb = new StringBuffer();
int i;
JSONArray ja;
String key;
Iterator keys;
int length;
Object object;
String tagName;
String value;
//Emit <tagName
tagName = jo.optString("tagName");
if (tagName == null) {
return XML.escape(jo.toString());
}
XML.noSpace(tagName);
tagName = XML.escape(tagName);
sb.append('<');
sb.append(tagName);
//Emit the attributes
keys = jo.keys();
while (keys.hasNext()) {
key = keys.next().toString();
if (!"tagName".equals(key) && !"childNodes".equals(key)) {
XML.noSpace(key);
value = jo.optString(key);
if (value != null) {
sb.append(' ');
sb.append(XML.escape(key));
sb.append('=');
sb.append('"');
sb.append(XML.escape(value));
sb.append('"');
}
}
}
//Emit content in body
ja = jo.optJSONArray("childNodes");
if (ja == null) {
sb.append('/');
sb.append('>');
} else {
sb.append('>');
length = ja.length();
for (i = 0; i < length; i += 1) {
object = ja.get(i);
if (object != null) {
if (object instanceof String) {
sb.append(XML.escape(object.toString()));
} else if (object instanceof JSONObject) {
sb.append(toString((JSONObject)object));
} else if (object instanceof JSONArray) {
sb.append(toString((JSONArray)object));
} else {
sb.append(object.toString());
}
}
}
sb.append('<');
sb.append('/');
sb.append(tagName);
sb.append('>');
}
return sb.toString();
}
}

Some files were not shown because too many files have changed in this diff Show More