commit f039a6f534b48b79498d2565c94f440ec6103443 Author: Ajneb97 Date: Mon Oct 4 18:04:17 2021 -0300 Initial commit diff --git a/.classpath b/.classpath new file mode 100644 index 0000000..4a9eb40 --- /dev/null +++ b/.classpath @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..dfe0770 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +# Auto detect text files and perform LF normalization +* text=auto diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..a1c2a23 --- /dev/null +++ b/.gitignore @@ -0,0 +1,23 @@ +# Compiled class file +*.class + +# Log file +*.log + +# BlueJ files +*.ctxt + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.nar +*.ear +*.zip +*.tar.gz +*.rar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* diff --git a/.project b/.project new file mode 100644 index 0000000..c8c3cba --- /dev/null +++ b/.project @@ -0,0 +1,17 @@ + + + MineChess + + + + + + org.eclipse.jdt.core.javabuilder + + + + + + org.eclipse.jdt.core.javanature + + diff --git a/.settings/org.eclipse.jdt.core.prefs b/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000..a698e59 --- /dev/null +++ b/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,12 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.methodParameters=do not generate +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 +org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve +org.eclipse.jdt.core.compiler.compliance=1.8 +org.eclipse.jdt.core.compiler.debug.lineNumber=generate +org.eclipse.jdt.core.compiler.debug.localVariable=generate +org.eclipse.jdt.core.compiler.debug.sourceFile=generate +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.source=1.8 diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..5fa2724 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021 Ajneb97 + +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 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. diff --git a/README.md b/README.md new file mode 100644 index 0000000..fd3d8e9 --- /dev/null +++ b/README.md @@ -0,0 +1,2 @@ +# MineChess + https://www.spigotmc.org/resources/74178/ diff --git a/arenas.yml b/arenas.yml new file mode 100644 index 0000000..66ec3f4 --- /dev/null +++ b/arenas.yml @@ -0,0 +1 @@ +Arenas: diff --git a/config.yml b/config.yml new file mode 100644 index 0000000..15b93fb --- /dev/null +++ b/config.yml @@ -0,0 +1,160 @@ +Messages: + prefix: "&7[&2&lChess&7] " + configReloaded: "&aConfig Reloaded!" + noPermissions: "&cYou don't have permissions." + commandCreateErrorUse: "&cYou need to use &7/chess create " + arenaAlreadyExists: "&cThat arena already exists." + arenaCreated: "&aArena created! Use &7/chess build %arena% &ato automatically construct the arena in your position." + arenaDoesNotExists: "&cThat arena doesn't exists." + commandBuildErrorUse: "&cYou need to use &7/chess build " + arenaBuilt: "&aThe arena was built correctly!" + commandSetSpawnErrorUse: "&cYou need to use &7/chess setspawn " + spawnSet: "&aSpawn set for arena &e%arena%&a." + mainLobbyDefined: "&aMain Lobby defined correctly." + commandJoinErrorUse: "&cYou need to use &7/chess join " + playerJoin: "&7%player% &ehas joined the game (&b%current_players%&8/&b2&e)" + playerLeave: "&7%player% &ehas left the game (&b%current_players%&8/&b2&e)" + arenaStartingMessage: "&eThe game starts in &7%time% &eseconds!" + gameStartingCancelled: "&7There are not enough players to start the game." + gameStarted: "&aGame started!" + blackPiecesInfo: "&eYou are the &0&lBLACK &epieces." + whitePiecesInfo: "&eYou are the &f&lWHITE &epieces." + gameFinished: + - "&e&m " + - "&6%player% &ewon the game with &9%points% Points&e!" + - "&e&m " + gameFinishedTie: + - "&e&m " + - "&e There was a tie!" + - "&e&m " + arenaDisabledError: "&cThe arena is disabled." + alreadyInArena: "&cYou are already in an arena." + arenaAlreadyStarted: "&cThe arena already started." + arenaIsFull: "&cThe arena is full." + notInAGame: "&cYou are not in a game." + commandEnableErrorUse: "&cYou need to use: &7/chess enable " + arenaAlreadyEnabled: "&cThe arena is already enabled." + enableArenaBuildError: "&cYou need to build the arena first by using &7/chess build " + enableArenaSpawnError: "&cYou need to set the arena spawn first by using &7/chess setspawn " + arenaEnabled: "&aArena &e%arena% &aenabled." + commandDisableErrorUse: "&cYou need to use: &7/chess disable " + arenaAlreadyDisabled: "&cThe arena is already disabled." + arenaDisabled: "&aArena &e%arena% &adisabled." + noMainLobby: "&cBefore creating an arena you need to set the Main Lobby with: &7/chess setmainlobby" + commandDeleteErrorUse: "&cYou need to use: &7/chess delete " + arenaDeleted: "&aArena &e%arena% &adeleted." + notYourTurn: "&cIs not your turn!" + notYourPiece: "&cThat is not your piece!" + pieceSelected: "&7&l%piece% &eselected." + piecePawn: "&aPawn" + pieceRook: "&aRook" + pieceKnight: "&aKnight" + pieceBishop: "&aBishop" + pieceQueen: "&aQueen" + pieceKing: "&aKing" + changeTurn: "&6➤ &eIt's &a%player% &eTurn." + pieceMove: "&6➤ &a%player% &emoved &a%piece% &eto &7[%coords%]&e." + pieceCaptured: "&6➤ &a%player% &emoved &a%piece% &eto &7[%coords%] &eand captured &c%player2%'s %player2_piece%&e." + castling: "&6➤ &a%player% &ecastled his King to &7[%coords%]&e." + promotion: "&6➤ &a%player% &epromoted his Pawn to &a%piece%&e." + check: "&6➤ &a%player%'s &cKing is in check!" + checkmate: "&6➤ &a%player%'s &cKing is in checkmate!" + actionbarPlayerTurn: "&9It's &e%player% &9Turn. &8(&6%time%&8)" + actionbarYourTurn: "&9It's your Turn. &8(&6%time%&8)" + gameScoreboardTitle: "&bMineChess" + gameScoreboardBody: + - "&1" + - "&cStatus:" + - "&e%status%" + - "&2" + - "&a&l%player_1% &cPoints: &a%player_1_points%" + - "&a&l%player_2% &cPoints: &a%player_2_points%" + - "&3" + - "&cmc.server.com" + statusWaiting: "&eWAITING" + statusStarting: "&eSTARTING IN &a%time%" + statusIngame: "&eENDS IN &a%time%" + statusFinishing: "&eFINISHING IN &a%time%" + gameScoreboardWaitingPlayer: "Player" + pawnPromotionInventoryTitle: "&cPawn Promotion" + promoteItemName: "&ePromote to: &a%piece%" + signFormat: + - "&8[&2Chess&8]" + - "&9%arena%" + - "%status%" + - "&a%current_players%&8/&a%max_players%" + signStatusWaiting: "&1WAITING" + signStatusStarting: "&6STARTING" + signStatusIngame: "&cINGAME" + signStatusDisabled: "&8DISABLED" + signStatusFinishing: "&4FINISHING" + titleKingInCheck: "&a%player%'s &cKing is in check!" + titleKingInCheckmate: "&a%player%'s &cKing is in checkmate!" + commandSpectateErrorUse: "&cYou need to use &7/chess spectate /" + commandSpectateAllError: "&cThe arena doesn't exists or that player is not playing on it." + arenaMustHaveStarted: "&cThe arena must have started to spectate it!" + errorPlayerNotExists: "&7Player &e%player% &7doesn't have any stored stats." + commandPlayerStats: + - "&9&lStats of &e%player%" + - "&7Wins: &e%wins%" + - "&7Ties: &e%ties%" + - "&7Loses: &e%loses%" + - "&7Time Played: &d%time%" + noArenasAvailable: "&cThere are no arenas available." + errorClearInventory: "&c&lERROR! &7To join an arena clear your inventory first." +Config: + arena_starting_cooldown: 10 + arena_ending_phase_cooldown: 10 + arena_time: 1200 + piece_holograms_enabled: true + teleport_last_location: false + empty_inventory_to_join: false + click_distance: 15 + time_in_each_turn: + enabled: true + time: 60 + action_when_time_runs_out: move + leave_item_enabled: true + leave_item: + item: IRON_DOOR + name: "&7[&c&lLeave&7]" + lore: + - "&7Right Click to leave the game." + select_item: + item: NAME_TAG + name: "&7[&a&lSelect and Move&7]" + lore: + - "&eLeft Click &7to select a piece." + - "&eRight Click &7to move a selected piece." + commands_whitelist: + - "/chess leave" + - "/help" + per_arena_chat: true + soundCapturePiece: "BLOCK_NOTE_BLOCK_PLING;10;2" + soundLosePiece: "BLOCK_NOTE_BLOCK_PLING;10;0.1" + soundMovePiece: "BLOCK_STONE_STEP;10;1" + soundCastling: "BLOCK_PISTON_EXTEND;10;1.5" + soundSelectPiece: "UI_BUTTON_CLICK;10;1" + soundPromotion: "ENTITY_PLAYER_LEVELUP;10;2" + soundCheck: "ENTITY_BLAZE_DEATH;10;0.5" + pointsPawn: 1 + pointsRook: 3 + pointsKnight: 3 + pointsBishop: 3 + pointsQueen: 10 + pointsKing: 20 + winners_command_rewards: + - "msg %player% &aHere, take a reward!" + - "eco give %player% %random_5*points-10*points%" + losers_command_rewards: + - "msg %player% &aYou've lost! Here, take this compensation reward." + - "eco give %player% %random_2*points-3*points%" + minimum_time_for_rewards: 240 + rewards_executed_after_teleport: true + mysql_database: + enabled: false + host: localhost + port: 3306 + username: root + password: root + database: database \ No newline at end of file diff --git a/players.yml b/players.yml new file mode 100644 index 0000000..882d0c4 --- /dev/null +++ b/players.yml @@ -0,0 +1 @@ +Players: diff --git a/plugin.yml b/plugin.yml new file mode 100644 index 0000000..28121ef --- /dev/null +++ b/plugin.yml @@ -0,0 +1,9 @@ +main: mc.ajneb97.MineChess +version: 1.12.1 +name: MineChess +api-version: 1.13 +softdepend: [Multiverse-Core,HolographicDisplays,PlaceholderAPI] + +commands: + chess: + description: Main command of MineChess \ No newline at end of file diff --git a/signs.yml b/signs.yml new file mode 100644 index 0000000..097d0ca --- /dev/null +++ b/signs.yml @@ -0,0 +1 @@ +Signs: \ No newline at end of file diff --git a/src/mc/ajneb97/Comando.java b/src/mc/ajneb97/Comando.java new file mode 100644 index 0000000..4bdee2f --- /dev/null +++ b/src/mc/ajneb97/Comando.java @@ -0,0 +1,392 @@ +package mc.ajneb97; + + + + +import java.util.List; + +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.entity.Player; + +import mc.ajneb97.juego.Estado; +import mc.ajneb97.juego.Jugador; +import mc.ajneb97.juego.Partida; +import mc.ajneb97.juego.Tablero; +import mc.ajneb97.managers.PartidaManager; +import mc.ajneb97.mysql.MySQL; +import mc.ajneb97.mysql.MySQLJugadorCallback; +import mc.ajneb97.otros.Utilidades; +import net.md_5.bungee.api.ChatColor; + + + +public class Comando implements CommandExecutor { + + private MineChess plugin; + public Comando(MineChess plugin) { + this.plugin = plugin; + } + + public boolean onCommand(CommandSender sender, Command command, String label, String[] args){ + if (!(sender instanceof Player)){ + FileConfiguration config = plugin.getConfig(); + String prefix = ChatColor.translateAlternateColorCodes('&', config.getString("Messages.prefix")); + if(args.length > 0) { + if(args[0].equalsIgnoreCase("reload")) { + plugin.reloadConfig(); + sender.sendMessage(prefix+ChatColor.translateAlternateColorCodes('&', config.getString("Messages.configReloaded"))); + } + } + + return false; + } + Player jugador = (Player)sender; + FileConfiguration config = plugin.getConfig(); + String prefix = ChatColor.translateAlternateColorCodes('&', config.getString("Messages.prefix")); + if(args.length > 0) { + if(args[0].equalsIgnoreCase("create")) { + // /chess create + if(jugador.isOp() || jugador.hasPermission("chess.admin")) { + if(args.length >= 2) { + if(plugin.getPartida(args[1]) == null) { + if(!config.contains("MainLobby")) { + jugador.sendMessage(prefix+ChatColor.translateAlternateColorCodes('&', config.getString("Messages.noMainLobby"))); + return true; + } + + Partida partida = new Partida(args[1]); + plugin.agregarPartida(partida); + jugador.sendMessage(prefix+ChatColor.translateAlternateColorCodes('&', config.getString("Messages.arenaCreated").replace("%arena%", args[1]))); + }else { + jugador.sendMessage(prefix+ChatColor.translateAlternateColorCodes('&', config.getString("Messages.arenaAlreadyExists"))); + } + }else { + jugador.sendMessage(prefix+ChatColor.translateAlternateColorCodes('&', config.getString("Messages.commandCreateErrorUse"))); + } + }else { + jugador.sendMessage(prefix+ChatColor.translateAlternateColorCodes('&', config.getString("Messages.noPermissions"))); + } + }else if(args[0].equalsIgnoreCase("build")) { + // /chess build + if(jugador.isOp() || jugador.hasPermission("chess.admin")) { + if(args.length >= 2) { + Partida partida = plugin.getPartida(args[1]); + if(partida != null) { + //161 8 9 -> 184 8 32 + Tablero.construirTablero(jugador.getLocation()); + Location esquina1 = jugador.getLocation().clone().add(0,-1,0); + Tablero.crearPiezas(esquina1); + partida.setEsquina1(new Location(esquina1.getWorld(),esquina1.getBlockX(),esquina1.getBlockY(),esquina1.getBlockZ())); + + jugador.sendMessage(prefix+ChatColor.translateAlternateColorCodes('&', config.getString("Messages.arenaBuilt"))); + }else { + jugador.sendMessage(prefix+ChatColor.translateAlternateColorCodes('&', config.getString("Messages.arenaDoesNotExists"))); + } + }else { + jugador.sendMessage(prefix+ChatColor.translateAlternateColorCodes('&', config.getString("Messages.commandBuildErrorUse"))); + } + }else { + jugador.sendMessage(prefix+ChatColor.translateAlternateColorCodes('&', config.getString("Messages.noPermissions"))); + } + }else if(args[0].equalsIgnoreCase("setspawn")) { + // /chess setspawn + if(jugador.isOp() || jugador.hasPermission("chess.admin")) { + if(args.length >= 2) { + Partida partida = plugin.getPartida(args[1]); + if(partida != null) { + partida.setSpawn(jugador.getLocation().clone()); + jugador.sendMessage(prefix+ChatColor.translateAlternateColorCodes('&', config.getString("Messages.spawnSet").replace("%arena%", args[1]))); + }else { + jugador.sendMessage(prefix+ChatColor.translateAlternateColorCodes('&', config.getString("Messages.arenaDoesNotExists"))); + } + }else { + jugador.sendMessage(prefix+ChatColor.translateAlternateColorCodes('&', config.getString("Messages.commandSetSpawnErrorUse"))); + } + }else { + jugador.sendMessage(prefix+ChatColor.translateAlternateColorCodes('&', config.getString("Messages.noPermissions"))); + } + }else if(args[0].equalsIgnoreCase("setmainlobby")) { + // /chess setmainlobby + if(jugador.isOp() || jugador.hasPermission("chess.admin")) { + Location l = jugador.getLocation(); + config.set("MainLobby.x", l.getX()+""); + config.set("MainLobby.y", l.getY()+""); + config.set("MainLobby.z", l.getZ()+""); + config.set("MainLobby.world", l.getWorld().getName()); + config.set("MainLobby.pitch", l.getPitch()); + config.set("MainLobby.yaw", l.getYaw()); + plugin.saveConfig(); + jugador.sendMessage(prefix+ChatColor.translateAlternateColorCodes('&', config.getString("Messages.mainLobbyDefined"))); + }else { + jugador.sendMessage(prefix+ChatColor.translateAlternateColorCodes('&', config.getString("Messages.noPermissions"))); + } + }else if(args[0].equalsIgnoreCase("spectate")) { + // /chess spectate o + if(args.length >= 2) { + Partida partida = plugin.getPartida(args[1]); + if(partida == null) { + partida = plugin.getPartidaJugador(args[1]); + if(partida == null) { + jugador.sendMessage(prefix+ChatColor.translateAlternateColorCodes('&', config.getString("Messages.commandSpectateAllError"))); + return true; + } + } + if(partida.estaActivada()) { + if(plugin.getPartidaJugador(jugador.getName()) == null) { + if(partida.estaIniciada()) { + PartidaManager.espectadorEntra(partida, jugador, plugin); + }else { + jugador.sendMessage(prefix+ChatColor.translateAlternateColorCodes('&', config.getString("Messages.arenaMustHaveStarted"))); + } + }else { + jugador.sendMessage(prefix+ChatColor.translateAlternateColorCodes('&', config.getString("Messages.alreadyInArena"))); + } + }else { + jugador.sendMessage(prefix+ChatColor.translateAlternateColorCodes('&', config.getString("Messages.arenaDisabledError"))); + } + + }else { + jugador.sendMessage(prefix+ChatColor.translateAlternateColorCodes('&', config.getString("Messages.commandSpectateErrorUse"))); + } + } + else if(args[0].equalsIgnoreCase("join")) { + // /chess join + if(args.length >= 2) { + Partida partida = plugin.getPartida(args[1]); + if(partida != null) { + if(partida.estaActivada()) { + if(plugin.getPartidaJugador(jugador.getName()) == null) { + if(!partida.estaIniciada()) { + if(!partida.estaLlena()) { + if(!Utilidades.pasaConfigInventario(jugador, config)) { + jugador.sendMessage(prefix+ChatColor.translateAlternateColorCodes('&', config.getString("Messages.errorClearInventory"))); + return true; + } + PartidaManager.jugadorEntra(partida, jugador,plugin); + }else { + jugador.sendMessage(prefix+ChatColor.translateAlternateColorCodes('&', config.getString("Messages.arenaIsFull"))); + } + }else { + jugador.sendMessage(prefix+ChatColor.translateAlternateColorCodes('&', config.getString("Messages.arenaAlreadyStarted"))); + } + }else { + jugador.sendMessage(prefix+ChatColor.translateAlternateColorCodes('&', config.getString("Messages.alreadyInArena"))); + } + }else { + jugador.sendMessage(prefix+ChatColor.translateAlternateColorCodes('&', config.getString("Messages.arenaDisabledError"))); + } + }else { + jugador.sendMessage(prefix+ChatColor.translateAlternateColorCodes('&', config.getString("Messages.arenaDoesNotExists"))); + } + }else { + jugador.sendMessage(prefix+ChatColor.translateAlternateColorCodes('&', config.getString("Messages.commandJoinErrorUse"))); + } + }else if(args[0].equalsIgnoreCase("joinrandom")) { + // /chess joinrandom + Partida partidaNueva = PartidaManager.getPartidaDisponible(plugin); + if(partidaNueva == null) { + jugador.sendMessage(prefix+ChatColor.translateAlternateColorCodes('&', config.getString("Messages.noArenasAvailable"))); + }else { + if(plugin.getPartidaJugador(jugador.getName()) == null) { + PartidaManager.jugadorEntra(partidaNueva, jugador,plugin); + }else { + jugador.sendMessage(prefix+ChatColor.translateAlternateColorCodes('&', config.getString("Messages.alreadyInArena"))); + } + } + + } + else if(args[0].equalsIgnoreCase("leave")) { + // /chess leave + Partida partida = plugin.getPartidaJugador(jugador.getName()); + if(partida != null) { + Jugador j = partida.getJugador(jugador.getName()); + if(j.esEspectador()) { + PartidaManager.espectadorSale(partida, jugador, plugin); + }else { + PartidaManager.jugadorSale(partida, jugador, false, plugin, false); + } + }else { + jugador.sendMessage(prefix+ChatColor.translateAlternateColorCodes('&', config.getString("Messages.notInAGame"))); + } + }else if(args[0].equalsIgnoreCase("enable")) { + // /chess enable + //Para activar una arena todo debe estar definido + if(jugador.isOp() || jugador.hasPermission("chess.admin")) { + if(args.length >= 2) { + Partida partida = plugin.getPartida(args[1]); + if(partida != null) { + if(partida.estaActivada()) { + jugador.sendMessage(prefix+ChatColor.translateAlternateColorCodes('&', config.getString("Messages.arenaAlreadyEnabled"))); + }else { + if(partida.getEsquina1() == null) { + jugador.sendMessage(prefix+ChatColor.translateAlternateColorCodes('&', config.getString("Messages.enableArenaBuildError"))); + return true; + } + if(partida.getSpawn() == null) { + jugador.sendMessage(prefix+ChatColor.translateAlternateColorCodes('&', config.getString("Messages.enableArenaSpawnError"))); + return true; + } + + partida.setEstado(Estado.ESPERANDO); + jugador.sendMessage(prefix+ChatColor.translateAlternateColorCodes('&', config.getString("Messages.arenaEnabled").replace("%arena%", args[1]))); + } + }else { + jugador.sendMessage(prefix+ChatColor.translateAlternateColorCodes('&', config.getString("Messages.arenaDoesNotExists"))); + } + }else { + jugador.sendMessage(prefix+ChatColor.translateAlternateColorCodes('&', config.getString("Messages.commandEnableErrorUse"))); + } + }else { + jugador.sendMessage(prefix+ChatColor.translateAlternateColorCodes('&', config.getString("Messages.noPermissions"))); + } + }else if(args[0].equalsIgnoreCase("disable")) { + // /chess disable + if(jugador.isOp() || jugador.hasPermission("chess.admin")) { + if(args.length >= 2) { + Partida partida = plugin.getPartida(args[1]); + if(partida != null) { + if(!partida.estaActivada()) { + jugador.sendMessage(prefix+ChatColor.translateAlternateColorCodes('&', config.getString("Messages.arenaAlreadyDisabled"))); + }else { + partida.setEstado(Estado.DESACTIVADA); + jugador.sendMessage(prefix+ChatColor.translateAlternateColorCodes('&', config.getString("Messages.arenaDisabled").replace("%arena%", args[1]))); + } + }else { + jugador.sendMessage(prefix+ChatColor.translateAlternateColorCodes('&', config.getString("Messages.arenaDoesNotExists"))); + } + }else { + jugador.sendMessage(prefix+ChatColor.translateAlternateColorCodes('&', config.getString("Messages.commandDisableErrorUse"))); + } + }else { + jugador.sendMessage(prefix+ChatColor.translateAlternateColorCodes('&', config.getString("Messages.noPermissions"))); + } + }else if(args[0].equalsIgnoreCase("delete")) { + // /chess delete + if(jugador.isOp() || jugador.hasPermission("chess.admin")) { + if(args.length >= 2) { + Partida partida = plugin.getPartida(args[1]); + if(partida != null) { + Location l = partida.getEsquina1(); + Location l2 = l.clone().add(24,5,24); + for(int x=l.getBlockX();x Stats del jugador + // /chess stats -> Stats de ese usuario + JugadorDatos j = null; + String nombreJugador = ""; + if (args.length == 1) { + if (jugador.isOp() || jugador.hasPermission("chess.stats")) { + nombreJugador = jugador.getName(); + j = plugin.getJugador(nombreJugador); + } else { + jugador.sendMessage(prefix + + ChatColor.translateAlternateColorCodes('&', config.getString("Messages.noPermissions"))); + return; + } + } else { + if (jugador.isOp() || jugador.hasPermission("chess.stats.others")) { + nombreJugador = args[1]; + j = plugin.getJugador(nombreJugador); + } else { + jugador.sendMessage(prefix + + ChatColor.translateAlternateColorCodes('&', config.getString("Messages.noPermissions"))); + return; + } + } + + if (j != null) { + List msg = config.getStringList("Messages.commandPlayerStats"); + for (int i = 0; i < msg.size(); i++) { + jugador.sendMessage(ChatColor.translateAlternateColorCodes('&', + msg.get(i).replace("%player%", j.getPlayer()).replace("%wins%", j.getWins() + "") + .replace("%ties%", j.getTies() + "").replace("%loses%", j.getLoses() + "") + .replace("%time%", Utilidades.getTiempoJugado(j.getMillisJugados())))); + } + } else { + jugador.sendMessage(prefix + ChatColor.translateAlternateColorCodes('&', + config.getString("Messages.errorPlayerNotExists").replace("%player%", nombreJugador))); + } + } + + public void enviarAyuda(Player jugador) { + jugador.sendMessage(ChatColor.translateAlternateColorCodes('&',"&7[ [ &8[&9MineChess&8] &7] ]")); + jugador.sendMessage(ChatColor.translateAlternateColorCodes('&',"")); + jugador.sendMessage(ChatColor.translateAlternateColorCodes('&',"&6/chess create &8Creates a new arena.")); + jugador.sendMessage(ChatColor.translateAlternateColorCodes('&',"&6/chess delete &8Deletes an arena.")); + jugador.sendMessage(ChatColor.translateAlternateColorCodes('&',"&6/chess join &8Joins an arena.")); + jugador.sendMessage(ChatColor.translateAlternateColorCodes('&',"&6/chess joinrandom &8Joins a random arena.")); + jugador.sendMessage(ChatColor.translateAlternateColorCodes('&',"&6/chess leave &8Leaves from the arena.")); + jugador.sendMessage(ChatColor.translateAlternateColorCodes('&',"&6/chess spectate / &8Spectates an arena or player.")); + jugador.sendMessage(ChatColor.translateAlternateColorCodes('&',"&6/chess setmainlobby &8Defines the minigame main lobby.")); + jugador.sendMessage(ChatColor.translateAlternateColorCodes('&',"&6/chess enable &8Enables an arena.")); + jugador.sendMessage(ChatColor.translateAlternateColorCodes('&',"&6/chess disable &8Disables an arena.")); + jugador.sendMessage(ChatColor.translateAlternateColorCodes('&',"&6/chess build &8Builds the arena in your current position.")); + jugador.sendMessage(ChatColor.translateAlternateColorCodes('&',"&6/chess setspawn &8Sets the arena spawn.")); + jugador.sendMessage(ChatColor.translateAlternateColorCodes('&',"&6/chess reload &8Reloads the configuration files.")); + jugador.sendMessage(ChatColor.translateAlternateColorCodes('&',"&6/chess stats &8Check stats of player.")); + jugador.sendMessage(ChatColor.translateAlternateColorCodes('&',"")); + jugador.sendMessage(ChatColor.translateAlternateColorCodes('&',"&7[ [ &8[&9MineChess&8] &7] ]")); + } +} diff --git a/src/mc/ajneb97/JugadorDatos.java b/src/mc/ajneb97/JugadorDatos.java new file mode 100644 index 0000000..581ed8e --- /dev/null +++ b/src/mc/ajneb97/JugadorDatos.java @@ -0,0 +1,79 @@ +package mc.ajneb97; + +import java.util.ArrayList; + +import org.bukkit.configuration.file.FileConfiguration; + +import mc.ajneb97.mysql.MySQL; + +public class JugadorDatos { + + private String player; + private String uuid; + private int wins; + private int loses; + private int ties; + private long millisJugados; + + public JugadorDatos(String player, String uuid,int wins,int loses,int ties,long millisJugados) { + this.uuid = uuid; + this.player = player; + this.wins = wins; + this.loses = loses; + this.ties = ties; + this.millisJugados = millisJugados; + } + + public void aumentarMillisJugados(long millis,FileConfiguration config,MineChess plugin) { + this.millisJugados = this.millisJugados+millis; + if(MySQL.isEnabled(config)) { + MySQL.modificarJugador(plugin, this); + } + } + + public long getMillisJugados() { + return this.millisJugados; + } + + public String getUUID() { + return uuid; + } + + public String getPlayer() { + return player; + } + + public int getWins() { + return wins; + } + + public int getLoses() { + return loses; + } + + public int getTies() { + return ties; + } + + public void aumentarWins(FileConfiguration config,MineChess plugin) { + this.wins++; + if(MySQL.isEnabled(config)) { + MySQL.modificarJugador(plugin, this); + } + } + + public void aumentarLoses(FileConfiguration config,MineChess plugin) { + this.loses++; + if(MySQL.isEnabled(config)) { + MySQL.modificarJugador(plugin, this); + } + } + + public void aumentarTies(FileConfiguration config,MineChess plugin) { + this.ties++; + if(MySQL.isEnabled(config)) { + MySQL.modificarJugador(plugin, this); + } + } + +} diff --git a/src/mc/ajneb97/MineChess.java b/src/mc/ajneb97/MineChess.java new file mode 100644 index 0000000..7886d35 --- /dev/null +++ b/src/mc/ajneb97/MineChess.java @@ -0,0 +1,561 @@ +package mc.ajneb97; + + +import java.io.BufferedReader; +import java.io.File; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.Reader; +import java.io.UnsupportedEncodingException; +import java.net.HttpURLConnection; +import java.net.URL; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.sql.Connection; +import java.util.ArrayList; +import java.util.List; + +import org.apache.logging.log4j.LogManager; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.plugin.PluginDescriptionFile; +import org.bukkit.plugin.PluginManager; +import org.bukkit.plugin.java.JavaPlugin; + +import mc.ajneb97.api.ChessAPI; +import mc.ajneb97.api.ExpansionMineChess; +import mc.ajneb97.juego.Estado; +import mc.ajneb97.juego.Jugador; +import mc.ajneb97.juego.Partida; +import mc.ajneb97.managers.CartelesListener; +import mc.ajneb97.managers.Entrar; +import mc.ajneb97.managers.InventarioCoronacion; +import mc.ajneb97.managers.PartidaListener; +import mc.ajneb97.managers.PartidaManager; +import mc.ajneb97.managers.ScoreboardAdmin; +import mc.ajneb97.managers.SignAdmin; +import mc.ajneb97.mysql.ConexionMySQL; +import mc.ajneb97.mysql.MySQL; + +//JAQUE: Al realizar un movimiento, comprobar por todas las piezas del jugador en su turno y ver si alguna posicion +// coincide con la del rey contrario. +//JAQUE: Si el rey esta en jaque, en su turno solo mostrar los movimientos posibles para salir de jaque. +// Para esto hay que obtener TODOS los movimientos posibles del rey, y por cada uno de ellos comprobar si +// el rey ya no esta en jaque. Los movimientos validos que permiten al rey salir de jaque seran los movimientos +// finales. +//JAQUE: Si el rey esta en jaque, al seleccionar una pieza comprobar por cada movimiento posible si ese movimiento +// saca del jaque al rey, y agregarlo a la lista. Para ver si el movimiento saca del jaque al rey, hay +// que comprobar por todas las piezas contrarias si pueden comer al rey o no +//JAQUE: Eliminar los movimientos que harian que tu rey este en jaque + +public class MineChess extends JavaPlugin { + + PluginDescriptionFile pdfFile = getDescription(); + public String version = pdfFile.getVersion(); + public String latestversion; + private ArrayList partidas; + private FileConfiguration arenas = null; + private File arenasFile = null; + private FileConfiguration signs = null; + private File signsFile = null; + private FileConfiguration players = null; + private File playersFile = null; + private ArrayList jugadores; + public String rutaConfig; + public static String prefix = ChatColor.translateAlternateColorCodes('&', "&8[&2&lMineChess&8] "); + + private ConexionMySQL conexionDatabase; + + public void onEnable(){ + partidas = new ArrayList(); + jugadores = new ArrayList(); + registerEvents(); + registerCommands(); + registerConfig(); + registerArenas(); + registerPlayers(); + cargarPartidas(); + if(MySQL.isEnabled(getConfig())) { + conexionDatabase = new ConexionMySQL(); + conexionDatabase.setupMySql(this, getConfig()); + } + cargarJugadores(); + + SignAdmin signs = new SignAdmin(this); + signs.actualizarSigns(); + ScoreboardAdmin scoreboards = new ScoreboardAdmin(this); + scoreboards.crearScoreboards(); + + ChessAPI api = new ChessAPI(this); + if(Bukkit.getPluginManager().getPlugin("PlaceholderAPI") != null){ + new ExpansionMineChess(this).register(); + } + checkMessagesUpdate(); + + + Bukkit.getConsoleSender().sendMessage(prefix+ChatColor.YELLOW + "Has been enabled! " + ChatColor.WHITE + "Version: " + version); + Bukkit.getConsoleSender().sendMessage(prefix+ChatColor.YELLOW + "Thanks for using my plugin! " + ChatColor.WHITE + "~Ajneb97"); + updateChecker(); + } + + public void onDisable(){ + if(partidas != null) { + for(int i=0;i jugadores = partidas.get(i).getJugadores(); + for(int c=0;c getPartidas() { + return this.partidas; + } + + public Partida getPartida(String nombre) { + for(int i=0;i(); + FileConfiguration arenas = getArenas(); + if(arenas.contains("Arenas")) { + for(String key : arenas.getConfigurationSection("Arenas").getKeys(false)) { + Location lSpawn = null; + if(arenas.contains("Arenas."+key+".Spawn")) { + double xSpawn = Double.valueOf(arenas.getString("Arenas."+key+".Spawn.x")); + double ySpawn = Double.valueOf(arenas.getString("Arenas."+key+".Spawn.y")); + double zSpawn = Double.valueOf(arenas.getString("Arenas."+key+".Spawn.z")); + String worldSpawn = arenas.getString("Arenas."+key+".Spawn.world"); + float pitchSpawn = Float.valueOf(arenas.getString("Arenas."+key+".Spawn.pitch")); + float yawSpawn = Float.valueOf(arenas.getString("Arenas."+key+".Spawn.yaw")); + lSpawn = new Location(Bukkit.getWorld(worldSpawn),xSpawn,ySpawn,zSpawn,yawSpawn,pitchSpawn); + } + Location lLocation = null; + if(arenas.contains("Arenas."+key+".Location")) { + double xLocation = Double.valueOf(arenas.getString("Arenas."+key+".Location.x")); + double yLocation = Double.valueOf(arenas.getString("Arenas."+key+".Location.y")); + double zLocation = Double.valueOf(arenas.getString("Arenas."+key+".Location.z")); + String worldLocation = arenas.getString("Arenas."+key+".Location.world"); + lLocation = new Location(Bukkit.getWorld(worldLocation),xLocation,yLocation,zLocation); + } + + Partida partida = new Partida(key); + partida.setSpawn(lSpawn); + partida.setEsquina1(lLocation); + String enabled = arenas.getString("Arenas."+key+".enabled"); + if(enabled.equals("true")) { + partida.setEstado(Estado.ESPERANDO); + }else { + partida.setEstado(Estado.DESACTIVADA); + } + + this.partidas.add(partida); + } + } + + } + + public void guardarPartidas() { + FileConfiguration arenas = getArenas(); + arenas.set("Arenas", null); + for(Partida p : this.partidas) { + String nombre = p.getNombre(); + Location lSpawn = p.getSpawn(); + if(lSpawn != null) { + arenas.set("Arenas."+nombre+".Spawn.x", lSpawn.getX()+""); + arenas.set("Arenas."+nombre+".Spawn.y", lSpawn.getY()+""); + arenas.set("Arenas."+nombre+".Spawn.z", lSpawn.getZ()+""); + arenas.set("Arenas."+nombre+".Spawn.world", lSpawn.getWorld().getName()); + arenas.set("Arenas."+nombre+".Spawn.pitch", lSpawn.getPitch()); + arenas.set("Arenas."+nombre+".Spawn.yaw", lSpawn.getYaw()); + } + + Location lEsquina = p.getEsquina1(); + if(lEsquina != null) { + arenas.set("Arenas."+nombre+".Location.x", lEsquina.getX()+""); + arenas.set("Arenas."+nombre+".Location.y", lEsquina.getY()+""); + arenas.set("Arenas."+nombre+".Location.z", lEsquina.getZ()+""); + arenas.set("Arenas."+nombre+".Location.world", lEsquina.getWorld().getName()); + } + + if(p.getEstado().equals(Estado.DESACTIVADA)) { + arenas.set("Arenas."+nombre+".enabled", "false"); + }else { + arenas.set("Arenas."+nombre+".enabled", "true"); + } + } + this.saveArenas(); + } + + public void registerSigns(){ + signsFile = new File(this.getDataFolder(), "signs.yml"); + if(!signsFile.exists()){ + this.getSigns().options().copyDefaults(true); + saveSigns(); + } + } + public void saveSigns() { + try { + signs.save(signsFile); + } catch (IOException e) { + e.printStackTrace(); + } + } + + public FileConfiguration getSigns() { + if (signs == null) { + reloadSigns(); + } + return signs; + } + + public void reloadSigns() { + if (signs == null) { + signsFile = new File(getDataFolder(), "signs.yml"); + } + signs = YamlConfiguration.loadConfiguration(signsFile); + + Reader defConfigStream; + try { + defConfigStream = new InputStreamReader(this.getResource("signs.yml"), "UTF8"); + if (defConfigStream != null) { + YamlConfiguration defConfig = YamlConfiguration.loadConfiguration(defConfigStream); + signs.setDefaults(defConfig); + } + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } + } + + public void cargarJugadores() { + if(MySQL.isEnabled(getConfig())) { + this.jugadores = MySQL.getJugadores(this); + return; + } + FileConfiguration config = getPlayers(); + if(config.contains("Players")) { + for(String key : config.getConfigurationSection("Players").getKeys(false)) { + String player = config.getString("Players."+key+".name"); + int wins = 0; + int loses = 0; + int ties = 0; + long millis = 0; + if(config.contains("Players."+key+".wins")){ + wins = Integer.valueOf(config.getString("Players."+key+".wins")); + } + if(config.contains("Players."+key+".loses")){ + loses = Integer.valueOf(config.getString("Players."+key+".loses")); + } + if(config.contains("Players."+key+".ties")){ + ties = Integer.valueOf(config.getString("Players."+key+".ties")); + } + if(config.contains("Players."+key+".played_time")) { + millis = Long.valueOf(config.getString("Players."+key+".played_time")); + } + agregarJugadorDatos(new JugadorDatos(player,key,wins,loses,ties,millis)); + } + } + } + + public void guardarJugadores() { + if(MySQL.isEnabled(getConfig())) { + return; + } + FileConfiguration players = getPlayers(); + for(JugadorDatos j : jugadores) { + String uuid = j.getUUID(); + String name = j.getPlayer(); + int wins = j.getWins(); + int loses = j.getLoses(); + int ties = j.getTies(); + players.set("Players."+uuid+".name", name); + players.set("Players."+uuid+".wins", wins); + players.set("Players."+uuid+".loses", loses); + players.set("Players."+uuid+".ties", ties); + players.set("Players."+uuid+".played_time", j.getMillisJugados()); + } + savePlayers(); + } + + public void agregarJugadorDatos(JugadorDatos jugador) { + jugadores.add(jugador); + } + + public void removerJugadorDatos(String jugador) { + for(int i=0;i getJugadores(){ + return this.jugadores; + } + + public void updateChecker(){ + + try { + HttpURLConnection con = (HttpURLConnection) new URL( + "https://api.spigotmc.org/legacy/update.php?resource=74178").openConnection(); + int timed_out = 1250; + con.setConnectTimeout(timed_out); + con.setReadTimeout(timed_out); + latestversion = new BufferedReader(new InputStreamReader(con.getInputStream())).readLine(); + if (latestversion.length() <= 7) { + if(!version.equals(latestversion)){ + Bukkit.getConsoleSender().sendMessage(ChatColor.RED +"There is a new version available. "+ChatColor.YELLOW+ + "("+ChatColor.GRAY+latestversion+ChatColor.YELLOW+")"); + Bukkit.getConsoleSender().sendMessage(ChatColor.RED+"You can download it at: "+ChatColor.WHITE+"https://www.spigotmc.org/resources/74178/"); + } + } + } catch (Exception ex) { + Bukkit.getConsoleSender().sendMessage(prefix + ChatColor.RED +"Error while checking update."); + } + } + + public void registerPlayers(){ + playersFile = new File(this.getDataFolder(), "players.yml"); + if(!playersFile.exists()){ + this.getPlayers().options().copyDefaults(true); + savePlayers(); + } + } + public void savePlayers() { + try { + players.save(playersFile); + } catch (IOException e) { + e.printStackTrace(); + } + } + + public FileConfiguration getPlayers() { + if (players == null) { + reloadPlayers(); + } + return players; + } + + + public void reloadPlayers() { + if (players == null) { + playersFile = new File(getDataFolder(), "players.yml"); + } + players = YamlConfiguration.loadConfiguration(playersFile); + + Reader defConfigStream; + try { + + defConfigStream = new InputStreamReader(this.getResource("players.yml"), "UTF8"); + if (defConfigStream != null) { + YamlConfiguration defConfig = YamlConfiguration.loadConfiguration(defConfigStream); + players.setDefaults(defConfig); + } + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } + } + + public void checkMessagesUpdate(){ + Path archivo = Paths.get(rutaConfig); + try{ + String texto = new String(Files.readAllBytes(archivo)); + if(!texto.contains("click_distance:")){ + getConfig().set("Config.click_distance", 15); + saveConfig(); + } + if(!texto.contains("mysql_database:")){ + getConfig().set("Config.mysql_database.enabled", false); + getConfig().set("Config.mysql_database.host", "localhost"); + getConfig().set("Config.mysql_database.port", 3306); + getConfig().set("Config.mysql_database.username", "root"); + getConfig().set("Config.mysql_database.password", "root"); + getConfig().set("Config.mysql_database.database", "database"); + saveConfig(); + } + if(!texto.contains("errorClearInventory:")){ + getConfig().set("Messages.errorClearInventory", "&c&lERROR! &7To join an arena clear your inventory first."); + getConfig().set("Config.empty_inventory_to_join", false); + saveConfig(); + } + if(!texto.contains("noArenasAvailable:")){ + getConfig().set("Messages.noArenasAvailable", "&cThere are no arenas available."); + saveConfig(); + } + if(!texto.contains("losers_command_rewards:")){ + List lista = new ArrayList(); + lista.add("msg %player% &aYou've lost! Here, take this compensation reward."); + lista.add("eco give %player% %random_2*points-3*points%"); + getConfig().set("Config.losers_command_rewards", lista); + saveConfig(); + } + if(!texto.contains("minimum_time_for_rewards:")){ + + getConfig().set("Config.minimum_time_for_rewards", 240); + saveConfig(); + } + if(!texto.contains("teleport_last_location:")){ + getConfig().set("Config.teleport_last_location", false); + saveConfig(); + } + if(!texto.contains("rewards_executed_after_teleport:")){ + getConfig().set("Config.rewards_executed_after_teleport", true); + saveConfig(); + } + if(!texto.contains("time_in_each_turn:")){ + getConfig().set("Config.time_in_each_turn.enabled", true); + getConfig().set("Config.time_in_each_turn.time", 60); + getConfig().set("Config.time_in_each_turn.action_when_time_runs_out", "move"); + saveConfig(); + } + if(!texto.contains("errorPlayerNotExists:")){ + getConfig().set("Messages.errorPlayerNotExists", "&7Player &e%player% &7doesn't have any stored stats."); + List lista = new ArrayList(); + lista.add("&9&lStats of &e%player%"); + lista.add("&7Wins: &e%wins%"); + lista.add("&7Ties: &e%ties%"); + lista.add("&7Loses: &e%loses%"); + getConfig().set("Messages.commandPlayerStats", lista); + saveConfig(); + } + if(!texto.contains("commandSpectateErrorUse:")){ + getConfig().set("Messages.commandSpectateErrorUse", "&cYou need to use &7/chess spectate "); + getConfig().set("Messages.arenaMustHaveStarted", "&cThe arena must have started to spectate it!"); + saveConfig(); + } + if(!texto.contains("titleKingInCheck:")){ + getConfig().set("Messages.titleKingInCheck", "&a%player%'s &cKing is in check!"); + getConfig().set("Messages.check", "&6➤ &a%player%'s &cKing is in check!"); + getConfig().set("Messages.titleKingInCheckmate", "&a%player%'s &cKing is in checkmate!"); + getConfig().set("Messages.checkmate", "&6➤ &a%player%'s &cKing is in checkmate!"); + getConfig().set("Config.soundCheck", "ENTITY_BLAZE_DEATH;10;0.5"); + saveConfig(); + } + if(!texto.contains("per_arena_chat:")){ + getConfig().set("Config.per_arena_chat", true); + saveConfig(); + } + if(!texto.contains("piece_holograms_enabled:")){ + getConfig().set("Config.piece_holograms_enabled", true); + saveConfig(); + } + }catch(IOException e){ + e.printStackTrace(); + } + } + + public Connection getConnection() { + return this.conexionDatabase.getConnection(); + } + + public void crearJugadorDatosSQL(String nombre,String uuid) { + MySQL.crearJugador(this, nombre, uuid); + } +} diff --git a/src/mc/ajneb97/api/ChessAPI.java b/src/mc/ajneb97/api/ChessAPI.java new file mode 100644 index 0000000..7e02b4d --- /dev/null +++ b/src/mc/ajneb97/api/ChessAPI.java @@ -0,0 +1,106 @@ +package mc.ajneb97.api; + +import java.util.ArrayList; + +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.entity.Player; + +import mc.ajneb97.JugadorDatos; +import mc.ajneb97.MineChess; +import mc.ajneb97.juego.Estado; +import mc.ajneb97.juego.Partida; +import mc.ajneb97.otros.Utilidades; + +public class ChessAPI { + + private static MineChess plugin; + + public ChessAPI(MineChess plugin) { + this.plugin = plugin; + } + + public static int getWins(String player) { + JugadorDatos jugador = plugin.getJugador(player); + if(jugador != null) { + return jugador.getWins(); + }else { + return 0; + } + } + + public static int getLoses(String player) { + JugadorDatos jugador = plugin.getJugador(player); + if(jugador != null) { + return jugador.getLoses(); + }else { + return 0; + } + } + + public static int getTies(String player) { + JugadorDatos jugador = plugin.getJugador(player); + if(jugador != null) { + return jugador.getTies(); + }else { + return 0; + } + } + + public static long getPlayedTime(String player) { + JugadorDatos jugador = plugin.getJugador(player); + if(jugador != null) { + return jugador.getMillisJugados(); + }else { + return 0; + } + } + + public static String getPlayedTimeFormatted(String player) { + JugadorDatos jugador = plugin.getJugador(player); + if(jugador != null) { + long millis = jugador.getMillisJugados(); + String formatted = Utilidades.getTiempoJugado(millis); + return formatted; + }else { + return "00:00"; + } + } + + public static int getPlayersArena(String arena) { + Partida partida = plugin.getPartida(arena); + if(partida != null) { + return partida.getCantidadActualJugadores(); + }else { + return 0; + } + } + + public static String getStatusArena(String arena) { + Partida partida = plugin.getPartida(arena); + FileConfiguration config = plugin.getConfig(); + if(partida != null) { + if(partida.getEstado().equals(Estado.COMENZANDO)) { + return config.getString("Messages.signStatusStarting"); + }else if(partida.getEstado().equals(Estado.DESACTIVADA)) { + return config.getString("Messages.signStatusDisabled"); + }else if(partida.getEstado().equals(Estado.ESPERANDO)) { + return config.getString("Messages.signStatusWaiting"); + }else if(partida.getEstado().equals(Estado.JUGANDO)) { + return config.getString("Messages.signStatusIngame"); + }else { + return config.getString("Messages.signStatusFinishing"); + } + }else { + return null; + } + } + + public static ArrayList getPlayerData(){ + ArrayList jugadores = plugin.getJugadores(); + ArrayList players = new ArrayList(); + for(JugadorDatos j : jugadores) { + players.add(new ChessPlayer(j.getPlayer(),j.getWins(),j.getLoses(),j.getTies(),j.getMillisJugados())); + } + return players; + } +} diff --git a/src/mc/ajneb97/api/ChessArenaStatus.java b/src/mc/ajneb97/api/ChessArenaStatus.java new file mode 100644 index 0000000..d557e86 --- /dev/null +++ b/src/mc/ajneb97/api/ChessArenaStatus.java @@ -0,0 +1,10 @@ +package mc.ajneb97.api; + +public enum ChessArenaStatus { + + WAITING, + STARTING, + INGAME, + FINISHING, + DISABLED; +} diff --git a/src/mc/ajneb97/api/ChessPlayer.java b/src/mc/ajneb97/api/ChessPlayer.java new file mode 100644 index 0000000..e48839f --- /dev/null +++ b/src/mc/ajneb97/api/ChessPlayer.java @@ -0,0 +1,40 @@ +package mc.ajneb97.api; + +public class ChessPlayer { + + private String player; + private int wins; + private int loses; + private int ties; + private long playedTime; + + public ChessPlayer(String player,int wins,int loses,int ties,long playedTime) { + this.player = player; + this.wins = wins; + this.loses = loses; + this.ties = ties; + this.playedTime = playedTime; + } + + public String getPlayer() { + return player; + } + + public int getWins() { + return wins; + } + + public int getLoses() { + return loses; + } + + public int getTies() { + return ties; + } + + public long getPlayedTime() { + return playedTime; + } + + +} diff --git a/src/mc/ajneb97/api/ExpansionMineChess.java b/src/mc/ajneb97/api/ExpansionMineChess.java new file mode 100644 index 0000000..6bb7693 --- /dev/null +++ b/src/mc/ajneb97/api/ExpansionMineChess.java @@ -0,0 +1,135 @@ +package mc.ajneb97.api; + +import org.bukkit.Bukkit; +import org.bukkit.OfflinePlayer; +import org.bukkit.entity.Player; + +import mc.ajneb97.MineChess; +import mc.ajneb97.api.ChessAPI; +import me.clip.placeholderapi.expansion.PlaceholderExpansion; +/** + * This class will automatically register as a placeholder expansion + * when a jar including this class is added to the directory + * {@code /plugins/PlaceholderAPI/expansions} on your server. + *
+ *
If you create such a class inside your own plugin, you have to + * register it manually in your plugins {@code onEbale()} by using + * {@code new YourExpansionClass().register();} + */ +public class ExpansionMineChess extends PlaceholderExpansion { + + // We get an instance of the plugin later. + private MineChess plugin; + + public ExpansionMineChess(MineChess plugin) { + this.plugin = plugin; + } + + /** + * Because this is an internal class, + * you must override this method to let PlaceholderAPI know to not unregister your expansion class when + * PlaceholderAPI is reloaded + * + * @return true to persist through reloads + */ + @Override + public boolean persist(){ + return true; + } + /** + * Since this expansion requires api access to the plugin "SomePlugin" + * we must check if said plugin is on the server or not. + * + * @return true or false depending on if the required plugin is installed. + */ + @Override + public boolean canRegister(){ + return true; + } + + /** + * The name of the person who created this expansion should go here. + * + * @return The name of the author as a String. + */ + @Override + public String getAuthor(){ + return "Ajneb97"; + } + + /** + * The placeholder identifier should go here. + *
This is what tells PlaceholderAPI to call our onRequest + * method to obtain a value if a placeholder starts with our + * identifier. + *
This must be unique and can not contain % or _ + * + * @return The identifier in {@code %_%} as String. + */ + @Override + public String getIdentifier(){ + return "minechess"; + } + + /** + * This is the version of this expansion. + *
You don't have to use numbers, since it is set as a String. + * + * @return The version as a String. + */ + @Override + public String getVersion(){ + return plugin.getDescription().getVersion(); + } + + /** + * This is the method called when a placeholder with our identifier + * is found and needs a value. + *
We specify the value identifier in this method. + *
Since version 2.9.1 can you use OfflinePlayers in your requests. + * + * @param player + * A {@link org.bukkit.Player Player}. + * @param identifier + * A String containing the identifier/value. + * + * @return possibly-null String of the requested identifier. + */ + @Override + public String onPlaceholderRequest(Player player, String identifier){ + + if(player == null){ + return ""; + } + + if(identifier.equals("wins")){ + return ChessAPI.getWins(player.getName())+""; + } + + if(identifier.equals("loses")){ + return ChessAPI.getLoses(player.getName())+""; + } + + if(identifier.equals("ties")){ + return ChessAPI.getTies(player.getName())+""; + } + + if(identifier.equals("played_time")){ + return ChessAPI.getPlayedTimeFormatted(player.getName())+""; + } + + if(identifier.startsWith("arenaplayers_count_")){ + String arena = identifier.replace("arenaplayers_count_", ""); + return ChessAPI.getPlayersArena(arena)+""; + } + + if(identifier.startsWith("arena_status_")){ + String arena = identifier.replace("arena_status_", ""); + return ChessAPI.getStatusArena(arena)+""; + } + + // We return null if an invalid placeholder (f.e. %someplugin_placeholder3%) + // was provided + return null; + } +} diff --git a/src/mc/ajneb97/juego/Ajedrez.java b/src/mc/ajneb97/juego/Ajedrez.java new file mode 100644 index 0000000..e362e81 --- /dev/null +++ b/src/mc/ajneb97/juego/Ajedrez.java @@ -0,0 +1,598 @@ +package mc.ajneb97.juego; + +import java.util.ArrayList; + +import org.bukkit.Bukkit; +import org.bukkit.Location; + +public class Ajedrez { + + public static ArrayList getMovimientosPosibles(Partida partida,Pieza[][] tablero,int x,int y,boolean enroqueBloqueado){ + Pieza pieza = tablero[y][x]; + if(pieza.getTipo().equals("caballo")) { + return getMovimientosPosiblesCaballo(partida,tablero,x,y); + }else if(pieza.getTipo().equals("peon")) { + return getMovimientosPosiblesPeon(partida,tablero,x,y); + }else if(pieza.getTipo().equals("torre")) { + return getMovimientosPosiblesTorre(partida,tablero,x,y); + }else if(pieza.getTipo().equals("alfil")) { + return getMovimientosPosiblesAlfil(partida,tablero,x,y); + }else if(pieza.getTipo().equals("rey")) { + return getMovimientosPosiblesRey(partida,tablero,x,y,enroqueBloqueado); + }else if(pieza.getTipo().equals("reina")) { + return getMovimientosPosiblesReina(partida,tablero,x,y); + } + else { + return null; + } + } + + public static ArrayList getMovimientosPosiblesCaballo(Partida partida,Pieza[][] tablero,int x,int y){ + ArrayList locations = new ArrayList(); + Pieza piezaOriginal = tablero[y][x]; + int xNueva = x+1; + int yNueva = y+2; + if(xNueva <= tablero.length-1 && yNueva <= tablero.length-1 && xNueva >= 0 && yNueva >= 0) { + Pieza posicionNueva = tablero[yNueva][xNueva]; + if(posicionNueva == null || !posicionNueva.getColor().equals(piezaOriginal.getColor())) { + locations.add(new MovimientoPosible(partida.getLocationDesdeTablero(xNueva, yNueva),piezaOriginal)); + } + } + + xNueva = x-1; + yNueva = y+2; + if(xNueva <= tablero.length-1 && yNueva <= tablero.length-1 && xNueva >= 0 && yNueva >= 0) { + Pieza posicionNueva = tablero[yNueva][xNueva]; + if(posicionNueva == null || !posicionNueva.getColor().equals(piezaOriginal.getColor())) { + locations.add(new MovimientoPosible(partida.getLocationDesdeTablero(xNueva, yNueva),piezaOriginal)); + } + } + + xNueva = x+2; + yNueva = y+1; + if(xNueva <= tablero.length-1 && yNueva <= tablero.length-1 && xNueva >= 0 && yNueva >= 0) { + Pieza posicionNueva = tablero[yNueva][xNueva]; + if(posicionNueva == null || !posicionNueva.getColor().equals(piezaOriginal.getColor())) { + locations.add(new MovimientoPosible(partida.getLocationDesdeTablero(xNueva, yNueva),piezaOriginal)); + } + } + + xNueva = x+2; + yNueva = y-1; + if(xNueva <= tablero.length-1 && yNueva <= tablero.length-1 && xNueva >= 0 && yNueva >= 0) { + Pieza posicionNueva = tablero[yNueva][xNueva]; + if(posicionNueva == null || !posicionNueva.getColor().equals(piezaOriginal.getColor())) { + locations.add(new MovimientoPosible(partida.getLocationDesdeTablero(xNueva, yNueva),piezaOriginal)); + } + } + + xNueva = x-2; + yNueva = y+1; + if(xNueva <= tablero.length-1 && yNueva <= tablero.length-1 && xNueva >= 0 && yNueva >= 0) { + Pieza posicionNueva = tablero[yNueva][xNueva]; + if(posicionNueva == null || !posicionNueva.getColor().equals(piezaOriginal.getColor())) { + locations.add(new MovimientoPosible(partida.getLocationDesdeTablero(xNueva, yNueva),piezaOriginal)); + } + } + + xNueva = x-2; + yNueva = y-1; + if(xNueva <= tablero.length-1 && yNueva <= tablero.length-1 && xNueva >= 0 && yNueva >= 0) { + Pieza posicionNueva = tablero[yNueva][xNueva]; + if(posicionNueva == null || !posicionNueva.getColor().equals(piezaOriginal.getColor())) { + locations.add(new MovimientoPosible(partida.getLocationDesdeTablero(xNueva, yNueva),piezaOriginal)); + } + } + + xNueva = x-1; + yNueva = y-2; + if(xNueva <= tablero.length-1 && yNueva <= tablero.length-1 && xNueva >= 0 && yNueva >= 0) { + Pieza posicionNueva = tablero[yNueva][xNueva]; + if(posicionNueva == null || !posicionNueva.getColor().equals(piezaOriginal.getColor())) { + locations.add(new MovimientoPosible(partida.getLocationDesdeTablero(xNueva, yNueva),piezaOriginal)); + } + } + + xNueva = x+1; + yNueva = y-2; + if(xNueva <= tablero.length-1 && yNueva <= tablero.length-1 && xNueva >= 0 && yNueva >= 0) { + Pieza posicionNueva = tablero[yNueva][xNueva]; + if(posicionNueva == null || !posicionNueva.getColor().equals(piezaOriginal.getColor())) { + locations.add(new MovimientoPosible(partida.getLocationDesdeTablero(xNueva, yNueva),piezaOriginal)); + } + } + + return locations; + } + + public static ArrayList getMovimientosPosiblesPeon(Partida partida,Pieza[][] tablero,int x,int y){ + ArrayList locations = new ArrayList(); + Pieza piezaOriginal = tablero[y][x]; + if(piezaOriginal.getColor().equals("b")) { + //En-passant (comprueba a los lados) + int xNueva = x-1; + int yNueva = y; + if(xNueva <= tablero.length-1 && yNueva <= tablero.length-1 && xNueva >= 0 && yNueva >= 0) { + Pieza posicionNueva = tablero[yNueva][xNueva]; + if(posicionNueva != null && posicionNueva.getTipo().equals("peon") && !posicionNueva.getColor().equals(piezaOriginal.getColor()) + && posicionNueva.isEnPassant()) { + locations.add(new MovimientoPosible(partida.getLocationDesdeTablero(xNueva, yNueva+1),piezaOriginal)); + } + } + xNueva = x+1; + yNueva = y; + if(xNueva <= tablero.length-1 && yNueva <= tablero.length-1 && xNueva >= 0 && yNueva >= 0) { + Pieza posicionNueva = tablero[yNueva][xNueva]; + if(posicionNueva != null && posicionNueva.getTipo().equals("peon") && !posicionNueva.getColor().equals(piezaOriginal.getColor()) + && posicionNueva.isEnPassant()) { + locations.add(new MovimientoPosible(partida.getLocationDesdeTablero(xNueva, yNueva+1),piezaOriginal)); + } + } + + + xNueva = x; + yNueva = y+1; + boolean bloqueadoAdelante = false; + + if(xNueva <= tablero.length-1 && yNueva <= tablero.length-1 && xNueva >= 0 && yNueva >= 0) { + Pieza posicionNueva = tablero[yNueva][xNueva]; + if(posicionNueva == null) { + locations.add(new MovimientoPosible(partida.getLocationDesdeTablero(xNueva, yNueva),piezaOriginal)); + }else { + bloqueadoAdelante = true; + } + } + if(!bloqueadoAdelante) { + xNueva = x; + yNueva = y+2; + if(y == 1 && xNueva <= tablero.length-1 && yNueva <= tablero.length-1 && xNueva >= 0 && yNueva >= 0) { + Pieza posicionNueva = tablero[yNueva][xNueva]; + if(posicionNueva == null) { + locations.add(new MovimientoPosible(partida.getLocationDesdeTablero(xNueva, yNueva),piezaOriginal)); + } + } + } + + xNueva = x+1; + yNueva = y+1; + if(xNueva <= tablero.length-1 && yNueva <= tablero.length-1 && xNueva >= 0 && yNueva >= 0) { + Pieza posicionNueva = tablero[yNueva][xNueva]; + if(posicionNueva != null && !posicionNueva.getColor().equals(piezaOriginal.getColor())) { + locations.add(new MovimientoPosible(partida.getLocationDesdeTablero(xNueva, yNueva),piezaOriginal)); + } + } + xNueva = x-1; + yNueva = y+1; + if(xNueva <= tablero.length-1 && yNueva <= tablero.length-1 && xNueva >= 0 && yNueva >= 0) { + Pieza posicionNueva = tablero[yNueva][xNueva]; + if(posicionNueva != null && !posicionNueva.getColor().equals(piezaOriginal.getColor())) { + locations.add(new MovimientoPosible(partida.getLocationDesdeTablero(xNueva, yNueva),piezaOriginal)); + } + } + }else { + //En-passant (comprueba a los lados) + int xNueva = x-1; + int yNueva = y; + if(xNueva <= tablero.length-1 && yNueva <= tablero.length-1 && xNueva >= 0 && yNueva >= 0) { + Pieza posicionNueva = tablero[yNueva][xNueva]; + if(posicionNueva != null && posicionNueva.getTipo().equals("peon") && !posicionNueva.getColor().equals(piezaOriginal.getColor()) + && posicionNueva.isEnPassant()) { + locations.add(new MovimientoPosible(partida.getLocationDesdeTablero(xNueva, yNueva-1),piezaOriginal)); + } + } + xNueva = x+1; + yNueva = y; + if(xNueva <= tablero.length-1 && yNueva <= tablero.length-1 && xNueva >= 0 && yNueva >= 0) { + Pieza posicionNueva = tablero[yNueva][xNueva]; + if(posicionNueva != null && posicionNueva.getTipo().equals("peon") && !posicionNueva.getColor().equals(piezaOriginal.getColor()) + && posicionNueva.isEnPassant()) { + locations.add(new MovimientoPosible(partida.getLocationDesdeTablero(xNueva, yNueva-1),piezaOriginal)); + } + } + + xNueva = x; + yNueva = y-1; + boolean bloqueadoAdelante = false; + if(xNueva <= tablero.length-1 && yNueva <= tablero.length-1 && xNueva >= 0 && yNueva >= 0) { + Pieza posicionNueva = tablero[yNueva][xNueva]; + if(posicionNueva == null) { + locations.add(new MovimientoPosible(partida.getLocationDesdeTablero(xNueva, yNueva),piezaOriginal)); + }else { + bloqueadoAdelante = true; + } + } + if(!bloqueadoAdelante) { + xNueva = x; + yNueva = y-2; + if(y == 6 && xNueva <= tablero.length-1 && yNueva <= tablero.length-1 && xNueva >= 0 && yNueva >= 0) { + Pieza posicionNueva = tablero[yNueva][xNueva]; + if(posicionNueva == null) { + locations.add(new MovimientoPosible(partida.getLocationDesdeTablero(xNueva, yNueva),piezaOriginal)); + } + } + } + xNueva = x+1; + yNueva = y-1; + if(xNueva <= tablero.length-1 && yNueva <= tablero.length-1 && xNueva >= 0 && yNueva >= 0) { + Pieza posicionNueva = tablero[yNueva][xNueva]; + if(posicionNueva != null && !posicionNueva.getColor().equals(piezaOriginal.getColor())) { + locations.add(new MovimientoPosible(partida.getLocationDesdeTablero(xNueva, yNueva),piezaOriginal)); + } + } + xNueva = x-1; + yNueva = y-1; + if(xNueva <= tablero.length-1 && yNueva <= tablero.length-1 && xNueva >= 0 && yNueva >= 0) { + Pieza posicionNueva = tablero[yNueva][xNueva]; + if(posicionNueva != null && !posicionNueva.getColor().equals(piezaOriginal.getColor())) { + locations.add(new MovimientoPosible(partida.getLocationDesdeTablero(xNueva, yNueva),piezaOriginal)); + } + } + } + return locations; + } + + public static ArrayList getMovimientosPosiblesTorre(Partida partida,Pieza[][] tablero,int x,int y){ + ArrayList locations = new ArrayList(); + Pieza piezaOriginal = tablero[y][x]; + for(int i=1;i<8;i++) { + int xNueva = x+i; + if(xNueva <= tablero.length-1 && xNueva >= 0) { + Pieza posicionNueva = tablero[y][xNueva]; + if(posicionNueva == null) { + locations.add(new MovimientoPosible(partida.getLocationDesdeTablero(xNueva, y),piezaOriginal)); + }else if(!posicionNueva.getColor().equals(piezaOriginal.getColor())) { + locations.add(new MovimientoPosible(partida.getLocationDesdeTablero(xNueva, y),piezaOriginal)); + break; + }else if(posicionNueva.getColor().equals(piezaOriginal.getColor())) { + break; + } + } + } + for(int i=1;i<8;i++) { + int xNueva = x-i; + if(xNueva <= tablero.length-1 && xNueva >= 0) { + Pieza posicionNueva = tablero[y][xNueva]; + if(posicionNueva == null) { + locations.add(new MovimientoPosible(partida.getLocationDesdeTablero(xNueva, y),piezaOriginal)); + }else if(!posicionNueva.getColor().equals(piezaOriginal.getColor())) { + locations.add(new MovimientoPosible(partida.getLocationDesdeTablero(xNueva, y),piezaOriginal)); + break; + }else if(posicionNueva.getColor().equals(piezaOriginal.getColor())) { + break; + } + } + } + for(int i=1;i<8;i++) { + int yNueva = y+i; + if(yNueva <= tablero.length-1 && yNueva >= 0) { + Pieza posicionNueva = tablero[yNueva][x]; + if(posicionNueva == null) { + locations.add(new MovimientoPosible(partida.getLocationDesdeTablero(x, yNueva),piezaOriginal)); + }else if(!posicionNueva.getColor().equals(piezaOriginal.getColor())) { + locations.add(new MovimientoPosible(partida.getLocationDesdeTablero(x, yNueva),piezaOriginal)); + break; + }else if(posicionNueva.getColor().equals(piezaOriginal.getColor())) { + break; + } + } + } + for(int i=1;i<8;i++) { + int yNueva = y-i; + if(yNueva <= tablero.length-1 && yNueva >= 0) { + Pieza posicionNueva = tablero[yNueva][x]; + if(posicionNueva == null) { + locations.add(new MovimientoPosible(partida.getLocationDesdeTablero(x, yNueva),piezaOriginal)); + }else if(!posicionNueva.getColor().equals(piezaOriginal.getColor())) { + locations.add(new MovimientoPosible(partida.getLocationDesdeTablero(x, yNueva),piezaOriginal)); + break; + }else if(posicionNueva.getColor().equals(piezaOriginal.getColor())) { + break; + } + } + } + return locations; + } + + public static ArrayList getMovimientosPosiblesAlfil(Partida partida,Pieza[][] tablero,int x,int y){ + ArrayList locations = new ArrayList(); + Pieza piezaOriginal = tablero[y][x]; + for(int i=1;i<8;i++) { + int xNueva = x+i; + int yNueva = y+i; + if(xNueva <= tablero.length-1 && yNueva <= tablero.length-1 && xNueva >= 0 && yNueva >= 0) { + Pieza posicionNueva = tablero[yNueva][xNueva]; + if(posicionNueva == null) { + locations.add(new MovimientoPosible(partida.getLocationDesdeTablero(xNueva, yNueva),piezaOriginal)); + }else if(!posicionNueva.getColor().equals(piezaOriginal.getColor())) { + locations.add(new MovimientoPosible(partida.getLocationDesdeTablero(xNueva, yNueva),piezaOriginal)); + break; + }else if(posicionNueva.getColor().equals(piezaOriginal.getColor())) { + break; + } + } + } + for(int i=1;i<8;i++) { + int xNueva = x-i; + int yNueva = y+i; + if(xNueva <= tablero.length-1 && yNueva <= tablero.length-1 && xNueva >= 0 && yNueva >= 0) { + Pieza posicionNueva = tablero[yNueva][xNueva]; + if(posicionNueva == null) { + locations.add(new MovimientoPosible(partida.getLocationDesdeTablero(xNueva, yNueva),piezaOriginal)); + }else if(!posicionNueva.getColor().equals(piezaOriginal.getColor())) { + locations.add(new MovimientoPosible(partida.getLocationDesdeTablero(xNueva, yNueva),piezaOriginal)); + break; + }else if(posicionNueva.getColor().equals(piezaOriginal.getColor())) { + break; + } + } + } + for(int i=1;i<8;i++) { + int xNueva = x+i; + int yNueva = y-i; + if(xNueva <= tablero.length-1 && yNueva <= tablero.length-1 && xNueva >= 0 && yNueva >= 0) { + Pieza posicionNueva = tablero[yNueva][xNueva]; + if(posicionNueva == null) { + locations.add(new MovimientoPosible(partida.getLocationDesdeTablero(xNueva, yNueva),piezaOriginal)); + }else if(!posicionNueva.getColor().equals(piezaOriginal.getColor())) { + locations.add(new MovimientoPosible(partida.getLocationDesdeTablero(xNueva, yNueva),piezaOriginal)); + break; + }else if(posicionNueva.getColor().equals(piezaOriginal.getColor())) { + break; + } + } + } + for(int i=1;i<8;i++) { + int xNueva = x-i; + int yNueva = y-i; + if(xNueva <= tablero.length-1 && yNueva <= tablero.length-1 && xNueva >= 0 && yNueva >= 0) { + Pieza posicionNueva = tablero[yNueva][xNueva]; + if(posicionNueva == null) { + locations.add(new MovimientoPosible(partida.getLocationDesdeTablero(xNueva, yNueva),piezaOriginal)); + }else if(!posicionNueva.getColor().equals(piezaOriginal.getColor())) { + locations.add(new MovimientoPosible(partida.getLocationDesdeTablero(xNueva, yNueva),piezaOriginal)); + break; + }else if(posicionNueva.getColor().equals(piezaOriginal.getColor())) { + break; + } + } + } + return locations; + } + + public static ArrayList getMovimientosPosiblesRey(Partida partida,Pieza[][] tablero,int x,int y, boolean enroqueBloqueado){ + ArrayList locations = new ArrayList(); + Pieza piezaOriginal = tablero[y][x]; + int xNueva = x; + int yNueva = y-1; + if(xNueva <= tablero.length-1 && yNueva <= tablero.length-1 && xNueva >= 0 && yNueva >= 0) { + Pieza posicionNueva = tablero[yNueva][xNueva]; + if(posicionNueva == null || !posicionNueva.getColor().equals(piezaOriginal.getColor())) { + locations.add(new MovimientoPosible(partida.getLocationDesdeTablero(xNueva, yNueva),piezaOriginal)); + } + } + xNueva = x+1; + yNueva = y; + if(xNueva <= tablero.length-1 && yNueva <= tablero.length-1 && xNueva >= 0 && yNueva >= 0) { + Pieza posicionNueva = tablero[yNueva][xNueva]; + if(posicionNueva == null || !posicionNueva.getColor().equals(piezaOriginal.getColor())) { + locations.add(new MovimientoPosible(partida.getLocationDesdeTablero(xNueva, yNueva),piezaOriginal)); + } + } + xNueva = x-1; + yNueva = y; + if(xNueva <= tablero.length-1 && yNueva <= tablero.length-1 && xNueva >= 0 && yNueva >= 0) { + Pieza posicionNueva = tablero[yNueva][xNueva]; + if(posicionNueva == null || !posicionNueva.getColor().equals(piezaOriginal.getColor())) { + locations.add(new MovimientoPosible(partida.getLocationDesdeTablero(xNueva, yNueva),piezaOriginal)); + } + } + xNueva = x; + yNueva = y+1; + if(xNueva <= tablero.length-1 && yNueva <= tablero.length-1 && xNueva >= 0 && yNueva >= 0) { + Pieza posicionNueva = tablero[yNueva][xNueva]; + if(posicionNueva == null || !posicionNueva.getColor().equals(piezaOriginal.getColor())) { + locations.add(new MovimientoPosible(partida.getLocationDesdeTablero(xNueva, yNueva),piezaOriginal)); + } + } + xNueva = x+1; + yNueva = y+1; + if(xNueva <= tablero.length-1 && yNueva <= tablero.length-1 && xNueva >= 0 && yNueva >= 0) { + Pieza posicionNueva = tablero[yNueva][xNueva]; + if(posicionNueva == null || !posicionNueva.getColor().equals(piezaOriginal.getColor())) { + locations.add(new MovimientoPosible(partida.getLocationDesdeTablero(xNueva, yNueva),piezaOriginal)); + } + } + xNueva = x+1; + yNueva = y-1; + if(xNueva <= tablero.length-1 && yNueva <= tablero.length-1 && xNueva >= 0 && yNueva >= 0) { + Pieza posicionNueva = tablero[yNueva][xNueva]; + if(posicionNueva == null || !posicionNueva.getColor().equals(piezaOriginal.getColor())) { + locations.add(new MovimientoPosible(partida.getLocationDesdeTablero(xNueva, yNueva),piezaOriginal)); + } + } + xNueva = x-1; + yNueva = y+1; + if(xNueva <= tablero.length-1 && yNueva <= tablero.length-1 && xNueva >= 0 && yNueva >= 0) { + Pieza posicionNueva = tablero[yNueva][xNueva]; + if(posicionNueva == null || !posicionNueva.getColor().equals(piezaOriginal.getColor())) { + locations.add(new MovimientoPosible(partida.getLocationDesdeTablero(xNueva, yNueva),piezaOriginal)); + } + } + xNueva = x-1; + yNueva = y-1; + if(xNueva <= tablero.length-1 && yNueva <= tablero.length-1 && xNueva >= 0 && yNueva >= 0) { + Pieza posicionNueva = tablero[yNueva][xNueva]; + if(posicionNueva == null || !posicionNueva.getColor().equals(piezaOriginal.getColor())) { + locations.add(new MovimientoPosible(partida.getLocationDesdeTablero(xNueva, yNueva),piezaOriginal)); + } + } + + //ENROQUE + if(!enroqueBloqueado) { + if(!piezaOriginal.seHaMovido()) { + //CORTO + for(int i=1;i<=3;i++) { + xNueva = x-i; + yNueva = y; + if(i == 3) { + Pieza posicionNueva = tablero[yNueva][xNueva]; + if(posicionNueva != null && posicionNueva.getTipo().equals("torre") && posicionNueva.getColor().equals(piezaOriginal.getColor()) + && !posicionNueva.seHaMovido()) { + locations.add(new MovimientoPosible(partida.getLocationDesdeTablero(xNueva, yNueva),piezaOriginal)); + } + }else { + Pieza posicionNueva = tablero[yNueva][xNueva]; + if(posicionNueva != null) { + break; + } + } + } + + //LARGO + for(int i=1;i<=4;i++) { + xNueva = x+i; + yNueva = y; + if(i == 4) { + Pieza posicionNueva = tablero[yNueva][xNueva]; + if(posicionNueva != null && posicionNueva.getTipo().equals("torre") && posicionNueva.getColor().equals(piezaOriginal.getColor()) + && !posicionNueva.seHaMovido()) { + locations.add(new MovimientoPosible(partida.getLocationDesdeTablero(xNueva, yNueva),piezaOriginal)); + } + }else { + Pieza posicionNueva = tablero[yNueva][xNueva]; + if(posicionNueva != null) { + break; + } + } + } + + + } + } + + + return locations; + } + + public static ArrayList getMovimientosPosiblesReina(Partida partida,Pieza[][] tablero,int x,int y){ + ArrayList locations = new ArrayList(); + Pieza piezaOriginal = tablero[y][x]; + for(int i=1;i<8;i++) { + int xNueva = x+i; + int yNueva = y+i; + if(xNueva <= tablero.length-1 && yNueva <= tablero.length-1 && xNueva >= 0 && yNueva >= 0) { + Pieza posicionNueva = tablero[yNueva][xNueva]; + if(posicionNueva == null) { + locations.add(new MovimientoPosible(partida.getLocationDesdeTablero(xNueva, yNueva),piezaOriginal)); + }else if(!posicionNueva.getColor().equals(piezaOriginal.getColor())) { + locations.add(new MovimientoPosible(partida.getLocationDesdeTablero(xNueva, yNueva),piezaOriginal)); + break; + }else if(posicionNueva.getColor().equals(piezaOriginal.getColor())) { + break; + } + } + } + for(int i=1;i<8;i++) { + int xNueva = x-i; + int yNueva = y+i; + if(xNueva <= tablero.length-1 && yNueva <= tablero.length-1 && xNueva >= 0 && yNueva >= 0) { + Pieza posicionNueva = tablero[yNueva][xNueva]; + if(posicionNueva == null) { + locations.add(new MovimientoPosible(partida.getLocationDesdeTablero(xNueva, yNueva),piezaOriginal)); + }else if(!posicionNueva.getColor().equals(piezaOriginal.getColor())) { + locations.add(new MovimientoPosible(partida.getLocationDesdeTablero(xNueva, yNueva),piezaOriginal)); + break; + }else if(posicionNueva.getColor().equals(piezaOriginal.getColor())) { + break; + } + } + } + for(int i=1;i<8;i++) { + int xNueva = x+i; + int yNueva = y-i; + if(xNueva <= tablero.length-1 && yNueva <= tablero.length-1 && xNueva >= 0 && yNueva >= 0) { + Pieza posicionNueva = tablero[yNueva][xNueva]; + if(posicionNueva == null) { + locations.add(new MovimientoPosible(partida.getLocationDesdeTablero(xNueva, yNueva),piezaOriginal)); + }else if(!posicionNueva.getColor().equals(piezaOriginal.getColor())) { + locations.add(new MovimientoPosible(partida.getLocationDesdeTablero(xNueva, yNueva),piezaOriginal)); + break; + }else if(posicionNueva.getColor().equals(piezaOriginal.getColor())) { + break; + } + } + } + for(int i=1;i<8;i++) { + int xNueva = x-i; + int yNueva = y-i; + if(xNueva <= tablero.length-1 && yNueva <= tablero.length-1 && xNueva >= 0 && yNueva >= 0) { + Pieza posicionNueva = tablero[yNueva][xNueva]; + if(posicionNueva == null) { + locations.add(new MovimientoPosible(partida.getLocationDesdeTablero(xNueva, yNueva),piezaOriginal)); + }else if(!posicionNueva.getColor().equals(piezaOriginal.getColor())) { + locations.add(new MovimientoPosible(partida.getLocationDesdeTablero(xNueva, yNueva),piezaOriginal)); + break; + }else if(posicionNueva.getColor().equals(piezaOriginal.getColor())) { + break; + } + } + } + for(int i=1;i<8;i++) { + int xNueva = x+i; + if(xNueva <= tablero.length-1 && xNueva >= 0) { + Pieza posicionNueva = tablero[y][xNueva]; + if(posicionNueva == null) { + locations.add(new MovimientoPosible(partida.getLocationDesdeTablero(xNueva, y),piezaOriginal)); + }else if(!posicionNueva.getColor().equals(piezaOriginal.getColor())) { + locations.add(new MovimientoPosible(partida.getLocationDesdeTablero(xNueva, y),piezaOriginal)); + break; + }else if(posicionNueva.getColor().equals(piezaOriginal.getColor())) { + break; + } + } + } + for(int i=1;i<8;i++) { + int xNueva = x-i; + if(xNueva <= tablero.length-1 && xNueva >= 0) { + Pieza posicionNueva = tablero[y][xNueva]; + if(posicionNueva == null) { + locations.add(new MovimientoPosible(partida.getLocationDesdeTablero(xNueva, y),piezaOriginal)); + }else if(!posicionNueva.getColor().equals(piezaOriginal.getColor())) { + locations.add(new MovimientoPosible(partida.getLocationDesdeTablero(xNueva, y),piezaOriginal)); + break; + }else if(posicionNueva.getColor().equals(piezaOriginal.getColor())) { + break; + } + } + } + for(int i=1;i<8;i++) { + int yNueva = y+i; + if(yNueva <= tablero.length-1 && yNueva >= 0) { + Pieza posicionNueva = tablero[yNueva][x]; + if(posicionNueva == null) { + locations.add(new MovimientoPosible(partida.getLocationDesdeTablero(x, yNueva),piezaOriginal)); + }else if(!posicionNueva.getColor().equals(piezaOriginal.getColor())) { + locations.add(new MovimientoPosible(partida.getLocationDesdeTablero(x, yNueva),piezaOriginal)); + break; + }else if(posicionNueva.getColor().equals(piezaOriginal.getColor())) { + break; + } + } + } + for(int i=1;i<8;i++) { + int yNueva = y-i; + if(yNueva <= tablero.length-1 && yNueva >= 0) { + Pieza posicionNueva = tablero[yNueva][x]; + if(posicionNueva == null) { + locations.add(new MovimientoPosible(partida.getLocationDesdeTablero(x, yNueva),piezaOriginal)); + }else if(!posicionNueva.getColor().equals(piezaOriginal.getColor())) { + locations.add(new MovimientoPosible(partida.getLocationDesdeTablero(x, yNueva),piezaOriginal)); + break; + }else if(posicionNueva.getColor().equals(piezaOriginal.getColor())) { + break; + } + } + } + return locations; + } +} diff --git a/src/mc/ajneb97/juego/ElementosGuardados.java b/src/mc/ajneb97/juego/ElementosGuardados.java new file mode 100644 index 0000000..c718e6a --- /dev/null +++ b/src/mc/ajneb97/juego/ElementosGuardados.java @@ -0,0 +1,89 @@ +package mc.ajneb97.juego; + + +import org.bukkit.GameMode; +import org.bukkit.Location; +import org.bukkit.inventory.ItemStack; + + +public class ElementosGuardados { + + private ItemStack[] inventarioGuardado; + private ItemStack[] equipamientoGuardado; + private GameMode gamemodeGuardado; + private float experienciaGuardada; + private int levelGuardado; + private int hambreGuardada; + private double vidaGuardada; + private double maxVidaGuardada; + private Location lastLocation; + private boolean allowFligth; + private boolean isFlying; + + public ElementosGuardados(Location lastLocation, ItemStack[] inventarioGuardado,ItemStack[] equipamientoGuardado,GameMode gamemodeGuardado,float experienciaGuardada,int levelGuardado,int hambreGuardada, + double vidaGuardada,double maxVidaGuardada,boolean allowFligth,boolean isFlying) { + this.lastLocation = lastLocation; + this.inventarioGuardado = inventarioGuardado; + this.equipamientoGuardado = equipamientoGuardado; + this.gamemodeGuardado = gamemodeGuardado; + this.experienciaGuardada = experienciaGuardada; + this.levelGuardado = levelGuardado; + this.hambreGuardada = hambreGuardada; + this.vidaGuardada = vidaGuardada; + this.maxVidaGuardada = maxVidaGuardada; + this.allowFligth = allowFligth; + this.isFlying = isFlying; + } + + public boolean isAllowFligth() { + return allowFligth; + } + + public void setAllowFligth(boolean allowFligth) { + this.allowFligth = allowFligth; + } + + public boolean isFlying() { + return isFlying; + } + + public void setFlying(boolean isFlying) { + this.isFlying = isFlying; + } + + public Location getLastLocation() { + return this.lastLocation; + } + + public ItemStack[] getInventarioGuardado() { + return inventarioGuardado; + } + + public ItemStack[] getEquipamientoGuardado() { + return equipamientoGuardado; + } + + public GameMode getGamemodeGuardado() { + return gamemodeGuardado; + } + + public float getXPGuardada() { + return experienciaGuardada; + } + + public int getLevelGuardado() { + return this.levelGuardado; + } + + public int getHambreGuardada() { + return this.hambreGuardada; + } + + public double getVidaGuardada() { + return vidaGuardada; + } + + public double getMaxVidaGuardada() { + return maxVidaGuardada; + } +} diff --git a/src/mc/ajneb97/juego/Estado.java b/src/mc/ajneb97/juego/Estado.java new file mode 100644 index 0000000..3d3de17 --- /dev/null +++ b/src/mc/ajneb97/juego/Estado.java @@ -0,0 +1,10 @@ +package mc.ajneb97.juego; + +public enum Estado { + + ESPERANDO, + COMENZANDO, + JUGANDO, + TERMINANDO, + DESACTIVADA; +} diff --git a/src/mc/ajneb97/juego/Jugador.java b/src/mc/ajneb97/juego/Jugador.java new file mode 100644 index 0000000..277b17b --- /dev/null +++ b/src/mc/ajneb97/juego/Jugador.java @@ -0,0 +1,134 @@ +package mc.ajneb97.juego; + +import java.util.ArrayList; + +import org.bukkit.Location; +import org.bukkit.entity.Player; + + +public class Jugador { + + private Player jugador; + private int puntos; + private String color; + private ElementosGuardados guardados; + private Pieza piezaObservada; + private Pieza piezaSeleccionada; + private ArrayList movimientosPiezaSeleccionada; + private int[] celdaObservada; + private boolean coronandoPeon; + private boolean enJaque; + private boolean espectador; + private int tiempo; + private long millisAntes; //Tiempo al iniciar la partida + + public Jugador(Player jugador,boolean espectador) { + this.jugador = jugador; + this.tiempo = 0; + this.espectador = espectador; + this.guardados = new ElementosGuardados(jugador.getLocation().clone(),jugador.getInventory().getContents().clone(),jugador.getEquipment().getArmorContents().clone(),jugador.getGameMode() + ,jugador.getExp(),jugador.getLevel(),jugador.getFoodLevel(),jugador.getHealth(),jugador.getMaxHealth(),jugador.getAllowFlight(),jugador.isFlying()); + } + + public long getMillisAntes() { + return this.millisAntes; + } + + public void setMillisAntes() { + this.millisAntes = System.currentTimeMillis(); + } + + public int getTiempo() { + return this.tiempo; + } + + public void setTiempo(int tiempo) { + this.tiempo = tiempo; + } + + public void disminuirTiempo() { + this.tiempo--; + } + + public boolean esEspectador() { + return this.espectador; + } + + public void setEspectador(boolean espectador) { + this.espectador = espectador; + } + + public void setMovimientos(ArrayList movimientos) { + this.movimientosPiezaSeleccionada = movimientos; + } + + public ArrayList getMovimientos(){ + return this.movimientosPiezaSeleccionada; + } + + public boolean enJaque() { + return this.enJaque; + } + + public void setEnJaque(boolean enJaque) { + this.enJaque = enJaque; + } + + public boolean estaCoronandoPeon() { + return this.coronandoPeon; + } + + public void setCoronandoPeon(boolean coronando) { + this.coronandoPeon = coronando; + } + + public int[] getCeldaObservada() { + return celdaObservada; + } + + public void setCeldaObservada(int[] celdaObservada) { + this.celdaObservada = celdaObservada; + } + + public Pieza getPiezaSeleccionada() { + return piezaSeleccionada; + } + public void setPiezaSeleccionada(Pieza piezaSeleccionada) { + this.piezaSeleccionada = piezaSeleccionada; + } + public void setPiezaObservada(Pieza piezaObservada) { + this.piezaObservada = piezaObservada; + } + public Pieza getPiezaObservada() { + return this.piezaObservada; + } + public Player getJugador() { + return jugador; + } + public void setJugador(Player jugador) { + this.jugador = jugador; + } + public int getPuntos() { + return puntos; + } + public void setPuntos(int puntos) { + this.puntos = puntos; + } + public void aumentarPuntos(int puntos) { + this.puntos = this.puntos+puntos; + } + public String getColor() { + return color; + } + public void setColor(String color) { + this.color = color; + } + public ElementosGuardados getGuardados() { + return guardados; + } + public void setGuardados(ElementosGuardados guardados) { + this.guardados = guardados; + } + + +} diff --git a/src/mc/ajneb97/juego/MovimientoPosible.java b/src/mc/ajneb97/juego/MovimientoPosible.java new file mode 100644 index 0000000..099de74 --- /dev/null +++ b/src/mc/ajneb97/juego/MovimientoPosible.java @@ -0,0 +1,28 @@ +package mc.ajneb97.juego; + +import org.bukkit.Location; + +public class MovimientoPosible { + + private Location location; + private Pieza pieza; //pieza original + + public MovimientoPosible(Location location, Pieza pieza) { + this.location = location; + this.pieza = pieza; + } + public Location getLocation() { + return location; + } + public void setLocation(Location location) { + this.location = location; + } + public Pieza getPieza() { + return pieza; + } + public void setPieza(Pieza pieza) { + this.pieza = pieza; + } + + +} diff --git a/src/mc/ajneb97/juego/Partida.java b/src/mc/ajneb97/juego/Partida.java new file mode 100644 index 0000000..64143af --- /dev/null +++ b/src/mc/ajneb97/juego/Partida.java @@ -0,0 +1,390 @@ +package mc.ajneb97.juego; + +import java.util.ArrayList; + +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.entity.Player; + +public class Partida { + + private Jugador jugador1; + private Jugador jugador2; + private Pieza[][] tablero = new Pieza[8][8]; + private Estado estado; + private String nombre; + private Location esquina1; + private int tiempoMaximo; + private int tiempo; + private Location spawn; + private Jugador turno; + private ArrayList espectadores; + private int tiempoEnTerminar; + + public Partida(String nombre) { + this.nombre = nombre; + this.estado = Estado.DESACTIVADA; + this.espectadores = new ArrayList(); + this.tiempo = 0; + this.tiempoEnTerminar = 0; + reiniciarPiezas(); + } + + public int getTiempoEnTerminar() { + return this.tiempoEnTerminar; + } + + public void setTiempoEnTerminar(int tiempo) { + this.tiempoEnTerminar = tiempo; + } + + public void agregarEspectador(Player espectador) { + espectadores.add(new Jugador(espectador,true)); + } + + public void removerEspectador(String nombre) { + for(int i=0;i getJugadores(){ + ArrayList jugadores = new ArrayList(); + if(jugador1 != null) { + jugadores.add(jugador1); + } + if(jugador2 != null) { + jugadores.add(jugador2); + } + for(int i=0;i puntos2) { + return jugador1; + }else if(puntos2 > puntos1) { + return jugador2; + }else { + return null; //empate + } + } + +} diff --git a/src/mc/ajneb97/juego/Pieza.java b/src/mc/ajneb97/juego/Pieza.java new file mode 100644 index 0000000..f45cdc0 --- /dev/null +++ b/src/mc/ajneb97/juego/Pieza.java @@ -0,0 +1,51 @@ +package mc.ajneb97.juego; + +import org.bukkit.Location; + +public class Pieza { + + private int id; + private String tipo; + private String color; + private boolean movida; + private boolean enPassant; + + public Pieza(int id,String tipo, String color, boolean movida, boolean enPassant) { + this.tipo = tipo; + this.color = color; + this.id = id; + this.movida = movida; + this.enPassant = enPassant; + } + public void setEnPassant(boolean enPassant) { + this.enPassant = enPassant; + } + public boolean isEnPassant() { + return this.enPassant; + } + public String getColor() { + return color; + } + public void setColor(String color) { + this.color = color; + } + public String getTipo() { + return tipo; + } + public void setTipo(String tipo) { + this.tipo = tipo; + } + public int getId() { + return id; + } + public void setId(int id) { + this.id = id; + } + public boolean seHaMovido() { + return movida; + } + public void setMovida(boolean movida) { + this.movida = movida; + } + +} diff --git a/src/mc/ajneb97/juego/Tablero.java b/src/mc/ajneb97/juego/Tablero.java new file mode 100644 index 0000000..d90ac1f --- /dev/null +++ b/src/mc/ajneb97/juego/Tablero.java @@ -0,0 +1,322 @@ +package mc.ajneb97.juego; + +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.configuration.file.FileConfiguration; + +import com.gmail.filoghost.holographicdisplays.api.Hologram; +import com.gmail.filoghost.holographicdisplays.api.HologramsAPI; +import com.gmail.filoghost.holographicdisplays.api.VisibilityManager; + +import mc.ajneb97.MineChess; +import mc.ajneb97.otros.Utilidades; + +public class Tablero { + + @SuppressWarnings("deprecation") + public static void construirCelda(Location l,String color) { + Material m = null; + if(color.equals("b")) { + if(Bukkit.getVersion().contains("1.13") || Bukkit.getVersion().contains("1.14") || Bukkit.getVersion().contains("1.15") + || Bukkit.getVersion().contains("1.16") || Bukkit.getVersion().contains("1.17")) { + m = Material.valueOf("WHITE_WOOL"); + }else { + m = Material.WOOL; + } + + l.getBlock().setType(m); + l.clone().add(1,0,0).getBlock().setType(m); + l.clone().add(2,0,0).getBlock().setType(m); + l.clone().add(0,0,1).getBlock().setType(m); + l.clone().add(1,0,1).getBlock().setType(m); + l.clone().add(2,0,1).getBlock().setType(m); + l.clone().add(0,0,2).getBlock().setType(m); + l.clone().add(1,0,2).getBlock().setType(m); + l.clone().add(2,0,2).getBlock().setType(m); + }else { + if(Bukkit.getVersion().contains("1.13") || Bukkit.getVersion().contains("1.14") || Bukkit.getVersion().contains("1.15") + || Bukkit.getVersion().contains("1.16") || Bukkit.getVersion().contains("1.17")) { + m = Material.valueOf("GRAY_WOOL"); + l.getBlock().setType(m); + l.clone().add(1,0,0).getBlock().setType(m); + l.clone().add(2,0,0).getBlock().setType(m); + l.clone().add(0,0,1).getBlock().setType(m); + l.clone().add(1,0,1).getBlock().setType(m); + l.clone().add(2,0,1).getBlock().setType(m); + l.clone().add(0,0,2).getBlock().setType(m); + l.clone().add(1,0,2).getBlock().setType(m); + l.clone().add(2,0,2).getBlock().setType(m); + }else { + m = Material.valueOf("WOOL"); + l.getBlock().setType(m); + l.getBlock().setData((byte) 8); + Location l2 = l.clone().add(1,0,0); + l2.getBlock().setType(m); + l2.getBlock().setData((byte) 8); + Location l3 = l.clone().add(2,0,0); + l3.getBlock().setType(m); + l3.getBlock().setData((byte) 8); + Location l4 = l.clone().add(0,0,1); + l4.getBlock().setType(m); + l4.getBlock().setData((byte) 8); + Location l5 = l.clone().add(1,0,1); + l5.getBlock().setType(m); + l5.getBlock().setData((byte) 8); + Location l6 = l.clone().add(2,0,1); + l6.getBlock().setType(m); + l6.getBlock().setData((byte) 8); + Location l7 = l.clone().add(0,0,2); + l7.getBlock().setType(m); + l7.getBlock().setData((byte) 8); + Location l8 = l.clone().add(1,0,2); + l8.getBlock().setType(m); + l8.getBlock().setData((byte) 8); + Location l9 = l.clone().add(2,0,2); + l9.getBlock().setType(m); + l9.getBlock().setData((byte) 8); + } + } + } + + public static void construirTablero(Location l) { + Location actual = l.clone().add(0,-1,0); + String color = "b"; + for(int i=0;i<8;i++) { + for(int c=0;c<8;c++) { + construirCelda(actual,color); + if(c != 7) { + if(color.equals("b")) { + color = "n"; + }else { + color = "b"; + } + } + actual.add(3,0,0); + } + actual.add(-24,0,3); + } + } + + public static void crearPiezas(Location esquina) { + Location nueva = esquina.clone().add(1,1,1); + for(int i=0;i<8;i++) { + if(i==0 || i==7) { + crearPieza(nueva,"torre","b"); + }else if(i==1 || i==6) { + crearPieza(nueva,"caballo","b"); + }else if(i==2 || i==5) { + crearPieza(nueva,"alfil","b"); + }else if(i==3) { + crearPieza(nueva,"rey","b"); + }else { + crearPieza(nueva,"reina","b"); + } + nueva.add(3,0,0); + } + + nueva = esquina.clone().add(1,1,4); + for(int i=0;i<8;i++) { + crearPieza(nueva,"peon","b"); + nueva.add(3,0,0); + } + + nueva = esquina.clone().add(1,1,19); + for(int i=0;i<8;i++) { + crearPieza(nueva,"peon","n"); + nueva.add(3,0,0); + } + + nueva = esquina.clone().add(1,1,22); + for(int i=0;i<8;i++) { + if(i==0 || i==7) { + crearPieza(nueva,"torre","n"); + }else if(i==1 || i==6) { + crearPieza(nueva,"caballo","n"); + }else if(i==2 || i==5) { + crearPieza(nueva,"alfil","n"); + }else if(i==3) { + crearPieza(nueva,"rey","n"); + }else { + crearPieza(nueva,"reina","n"); + } + nueva.add(3,0,0); + } + } + + public static void crearPieza(Location l,String tipo,String color) { + Material m = null; + int rot = 0; + if(color.equals("b")) { + m = Material.IRON_BLOCK; + rot = 8; + }else { + m = Material.COAL_BLOCK; + } + + if(tipo.equals("torre")) { + l.getBlock().setType(m); + l.clone().add(0,1,0).getBlock().setType(m); + Location l2 = l.clone().add(0,2,0); + Utilidades.setSkullBlock(l2, "5e193aa2-292e-43c6-b92b-e823f6e0cc1e", "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvZjQ1NTlkNzU0NjRiMmU0MGE1MThlNGRlOGU2Y2YzMDg1ZjBhM2NhMGIxYjcwMTI2MTRjNGNkOTZmZWQ2MDM3OCJ9fX0=", rot); + }else if(tipo.equals("caballo")) { + l.getBlock().setType(m); + l.clone().add(0,1,0).getBlock().setType(m); + Location l2 = l.clone().add(0,2,0); + Utilidades.setSkullBlock(l2, "022202fd-9546-4492-b8b6-b768e95701c2", "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvN2JiNGIyODg5OTFlZmI4Y2EwNzQzYmVjY2VmMzEyNThiMzFkMzlmMjQ5NTFlZmIxYzljMThhNDE3YmE0OGY5In19fQ==", rot); + }else if(tipo.equals("alfil")) { + l.getBlock().setType(m); + l.clone().add(0,1,0).getBlock().setType(m); + Location l2 = l.clone().add(0,2,0); + if(color.equals("b")) { + Utilidades.setSkullBlock(l2, "eb1fc1a8-763e-442f-bf10-302b3beebb32", "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvMTI2Yjc3MjMyOWNmMzJmODY0M2M0OTI4NjI2YjZhMzI1MjMzZmY2MWFhOWM3NzI1ODczYTRiZDY2ZGIzZDY5MiJ9fX0=", rot); + }else { + Utilidades.setSkullBlock(l2, "c7b9f611-64c6-4e9c-ac97-8dedf8b97e17", "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvZjZjNWVjYWM5NDJjNzdiOTVhYjQ2MjBkZjViODVlMzgwNjRjOTc0ZjljNWM1NzZiODQzNjIyODA2YTQ1NTcifX19", rot); + } + }else if(tipo.equals("rey")) { + l.getBlock().setType(m); + l.clone().add(0,1,0).getBlock().setType(m); + l.clone().add(0,2,0).getBlock().setType(m); + l.clone().add(0,3,0).getBlock().setType(Material.DIAMOND_BLOCK); + }else if(tipo.equals("reina")) { + l.getBlock().setType(m); + l.clone().add(0,1,0).getBlock().setType(m); + l.clone().add(0,2,0).getBlock().setType(m); + Location l2 = l.clone().add(0,3,0); + Utilidades.setSkullBlock(l2, "fdea850d-ae8b-4e10-8b03-6883494ae266", "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvNTRiZjg5M2ZjNmRlZmFkMjE4Zjc4MzZlZmVmYmU2MzZmMWMyY2MxYmI2NTBjODJmY2NkOTlmMmMxZWU2In19fQ==", rot); + }else if(tipo.equals("peon")) { + l.getBlock().setType(m); + Location l2 = l.clone().add(0,1,0); + if(color.equals("b")) { + Utilidades.setSkullBlock(l2, "eb1fc1a8-763e-442f-bf10-302b3beebb32", "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvMTI2Yjc3MjMyOWNmMzJmODY0M2M0OTI4NjI2YjZhMzI1MjMzZmY2MWFhOWM3NzI1ODczYTRiZDY2ZGIzZDY5MiJ9fX0=", rot); + }else { + Utilidades.setSkullBlock(l2, "c7b9f611-64c6-4e9c-ac97-8dedf8b97e17", "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvZjZjNWVjYWM5NDJjNzdiOTVhYjQ2MjBkZjViODVlMzgwNjRjOTc0ZjljNWM1NzZiODQzNjIyODA2YTQ1NTcifX19", rot); + } + } + } + + public static void eliminarPieza(Location l) { + l.getBlock().setType(Material.AIR); + l.clone().add(0,1,0).getBlock().setType(Material.AIR); + l.clone().add(0,2,0).getBlock().setType(Material.AIR); + l.clone().add(0,3,0).getBlock().setType(Material.AIR); + } + + public static void eliminarPiezas(Location esquina) { + Location nueva = esquina.clone().add(1,1,1); + for(int x=0;x<8;x++) { + for(int y=0;y<8;y++) { + nueva.getBlock().setType(Material.AIR); + nueva.clone().add(0,1,0).getBlock().setType(Material.AIR); + nueva.clone().add(0,2,0).getBlock().setType(Material.AIR); + nueva.clone().add(0,3,0).getBlock().setType(Material.AIR); + nueva.add(3,0,0); + } + nueva.add(-24,0,3); + //Bukkit.getConsoleSender().sendMessage("eliminando en: "+nueva.getX()+" "+nueva.getY()+" "+nueva.getZ()); + } + } + + public static void crearHologramasPiezas(Location esquina,MineChess plugin) { + Location nueva = esquina.clone().add(1.5,5.7,1.5); + FileConfiguration config = plugin.getConfig(); + for(int i=0;i<8;i++) { + if(i==0 || i==7) { + crearPiezaHolograma(plugin,nueva,"torre",config); + }else if(i==1 || i==6) { + crearPiezaHolograma(plugin,nueva,"caballo",config); + }else if(i==2 || i==5) { + crearPiezaHolograma(plugin,nueva,"alfil",config); + }else if(i==3) { + crearPiezaHolograma(plugin,nueva,"rey",config); + }else { + crearPiezaHolograma(plugin,nueva,"reina",config); + } + nueva.add(3,0,0); + } + + nueva = esquina.clone().add(1.5,4,4.5); + for(int i=0;i<8;i++) { + crearPiezaHolograma(plugin,nueva,"peon",config); + nueva.add(3,0,0); + } + + nueva = esquina.clone().add(1.5,4,19.5); + for(int i=0;i<8;i++) { + crearPiezaHolograma(plugin,nueva,"peon",config); + nueva.add(3,0,0); + } + + nueva = esquina.clone().add(1.5,5.7,22.5); + for(int i=0;i<8;i++) { + if(i==0 || i==7) { + crearPiezaHolograma(plugin,nueva,"torre",config); + }else if(i==1 || i==6) { + crearPiezaHolograma(plugin,nueva,"caballo",config); + }else if(i==2 || i==5) { + crearPiezaHolograma(plugin,nueva,"alfil",config); + }else if(i==3) { + crearPiezaHolograma(plugin,nueva,"rey",config); + }else { + crearPiezaHolograma(plugin,nueva,"reina",config); + } + nueva.add(3,0,0); + } + } + + public static void crearPiezaHolograma(MineChess plugin,Location l,String tipo,FileConfiguration config) { + if(Bukkit.getServer().getPluginManager().getPlugin("HolographicDisplays") != null && config.getString("Config.piece_holograms_enabled").equals("true")) { + Hologram hologram = HologramsAPI.createHologram(plugin, l); + VisibilityManager visibilityManager = hologram.getVisibilityManager(); + visibilityManager.setVisibleByDefault(false); + if(tipo.equals("torre")) { + hologram.insertTextLine(0, ChatColor.translateAlternateColorCodes('&',config.getString("Messages.pieceRook"))); + }else if(tipo.equals("caballo")) { + hologram.insertTextLine(0, ChatColor.translateAlternateColorCodes('&',config.getString("Messages.pieceKnight"))); + }else if(tipo.equals("alfil")) { + hologram.insertTextLine(0, ChatColor.translateAlternateColorCodes('&',config.getString("Messages.pieceBishop"))); + }else if(tipo.equals("rey")) { + hologram.insertTextLine(0, ChatColor.translateAlternateColorCodes('&',config.getString("Messages.pieceKing"))); + }else if(tipo.equals("reina")) { + hologram.insertTextLine(0, ChatColor.translateAlternateColorCodes('&',config.getString("Messages.pieceQueen"))); + }else if(tipo.equals("peon")) { + hologram.insertTextLine(0, ChatColor.translateAlternateColorCodes('&',config.getString("Messages.piecePawn"))); + } + visibilityManager.setVisibleByDefault(true); + } + + } + + public static void eliminarPiezaHolograma(MineChess plugin,Location l,FileConfiguration config) { + if(Bukkit.getServer().getPluginManager().getPlugin("HolographicDisplays") != null && config.getString("Config.piece_holograms_enabled").equals("true")) { + for(Hologram h : HologramsAPI.getHolograms(plugin)) { + if(h.getX() == l.getX() && h.getZ() == l.getZ() && h.getWorld().getName().equals(l.getWorld().getName())) { + h.delete(); + } + } + } + + } + + public static void eliminarPiezasHologramas(MineChess plugin,Location esquina,FileConfiguration config,boolean cerrandoServer) { + if(Bukkit.getServer().getPluginManager().getPlugin("HolographicDisplays") != null && config.getString("Config.piece_holograms_enabled").equals("true") + && !cerrandoServer) { + Location nueva = esquina.clone().add(1.5,1,1.5); + for(int x=0;x<8;x++) { + for(int y=0;y<8;y++) { + for(Hologram h : HologramsAPI.getHolograms(plugin)) { + if(h.getX() == nueva.getX() && h.getZ() == nueva.getZ() && h.getWorld().getName().equals(nueva.getWorld().getName())) { + h.delete(); + } + } + nueva.add(3,0,0); + } + nueva.add(-24,0,3); + //Bukkit.getConsoleSender().sendMessage("eliminando en: "+nueva.getX()+" "+nueva.getY()+" "+nueva.getZ()); + } + } + + } +} + diff --git a/src/mc/ajneb97/lib/actionbarapi/ActionBarAPI.java b/src/mc/ajneb97/lib/actionbarapi/ActionBarAPI.java new file mode 100644 index 0000000..fd22b17 --- /dev/null +++ b/src/mc/ajneb97/lib/actionbarapi/ActionBarAPI.java @@ -0,0 +1,108 @@ +package mc.ajneb97.lib.actionbarapi; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.scheduler.BukkitRunnable; + +import mc.ajneb97.MineChess; +import net.md_5.bungee.api.ChatColor; +import net.md_5.bungee.api.ChatMessageType; +import net.md_5.bungee.api.chat.TextComponent; + +public class ActionBarAPI +{ + + public static void sendActionBar(Player player, String message) + { + if(Bukkit.getVersion().contains("1.16") || Bukkit.getVersion().contains("1.17")) { + TextComponent text_component = new TextComponent(message); + player.spigot().sendMessage(ChatMessageType.ACTION_BAR, text_component); + return; + } + boolean useOldMethods = false; + String nmsver = Bukkit.getServer().getClass().getPackage().getName(); + nmsver = nmsver.substring(nmsver.lastIndexOf(".") + 1); + if ((nmsver.equalsIgnoreCase("v1_8_R1")) || (nmsver.startsWith("v1_7_"))) { + useOldMethods = true; + } + if (!player.isOnline()) { + return; // Player may have logged out + } + + // Call the event, if cancelled don't send Action Bar + ActionBarMessageEvent actionBarMessageEvent = new ActionBarMessageEvent(player, message); + Bukkit.getPluginManager().callEvent(actionBarMessageEvent); + if (actionBarMessageEvent.isCancelled()) + return; + + try { + Class craftPlayerClass = Class.forName("org.bukkit.craftbukkit." + nmsver + ".entity.CraftPlayer"); + Object craftPlayer = craftPlayerClass.cast(player); + Object packet; + Class packetPlayOutChatClass = Class.forName("net.minecraft.server." + nmsver + ".PacketPlayOutChat"); + Class packetClass = Class.forName("net.minecraft.server." + nmsver + ".Packet"); + if (useOldMethods) { + Class chatSerializerClass = Class.forName("net.minecraft.server." + nmsver + ".ChatSerializer"); + Class iChatBaseComponentClass = Class.forName("net.minecraft.server." + nmsver + ".IChatBaseComponent"); + Method m3 = chatSerializerClass.getDeclaredMethod("a", String.class); + Object cbc = iChatBaseComponentClass.cast(m3.invoke(chatSerializerClass, "{\"text\": \"" + message + "\"}")); + packet = packetPlayOutChatClass.getConstructor(new Class[]{iChatBaseComponentClass, byte.class}).newInstance(cbc, (byte) 2); + } else { + Class chatComponentTextClass = Class.forName("net.minecraft.server." + nmsver + ".ChatComponentText"); + Class iChatBaseComponentClass = Class.forName("net.minecraft.server." + nmsver + ".IChatBaseComponent"); + try { + + Class chatMessageTypeClass = Class.forName("net.minecraft.server." + nmsver + ".ChatMessageType"); + Object[] chatMessageTypes = chatMessageTypeClass.getEnumConstants(); + Object chatMessageType = null; + for (Object obj : chatMessageTypes) { + if (obj.toString().equals("GAME_INFO")) { + chatMessageType = obj; + } + } + Object chatCompontentText = chatComponentTextClass.getConstructor(new Class[]{String.class}).newInstance(message); + packet = packetPlayOutChatClass.getConstructor(new Class[]{iChatBaseComponentClass, chatMessageTypeClass}).newInstance(chatCompontentText, chatMessageType); + } catch (ClassNotFoundException cnfe) { + Object chatCompontentText = chatComponentTextClass.getConstructor(new Class[]{String.class}).newInstance(message); + packet = packetPlayOutChatClass.getConstructor(new Class[]{iChatBaseComponentClass, byte.class}).newInstance(chatCompontentText, (byte) 2); + } + } + Method craftPlayerHandleMethod = craftPlayerClass.getDeclaredMethod("getHandle"); + Object craftPlayerHandle = craftPlayerHandleMethod.invoke(craftPlayer); + Field playerConnectionField = craftPlayerHandle.getClass().getDeclaredField("playerConnection"); + Object playerConnection = playerConnectionField.get(craftPlayerHandle); + Method sendPacketMethod = playerConnection.getClass().getDeclaredMethod("sendPacket", packetClass); + sendPacketMethod.invoke(playerConnection, packet); + } catch (Exception e) { + e.printStackTrace(); +} + } + + public static void sendActionBar(final Player player, final String message, int duration,MineChess plugin) { + sendActionBar(player, message); + + if (duration >= 0) { + // Sends empty message at the end of the duration. Allows messages shorter than 3 seconds, ensures precision. + new BukkitRunnable() { + @Override + public void run() { + sendActionBar(player, ""); + } + }.runTaskLater(plugin, duration + 1); + } + + // Re-sends the messages every 3 seconds so it doesn't go away from the player's screen. + while (duration > 40) { + duration -= 40; + new BukkitRunnable() { + @Override + public void run() { + sendActionBar(player, message); + } + }.runTaskLater(plugin, (long) duration); + } + } + +} diff --git a/src/mc/ajneb97/lib/actionbarapi/ActionBarMessageEvent.java b/src/mc/ajneb97/lib/actionbarapi/ActionBarMessageEvent.java new file mode 100644 index 0000000..eee2e71 --- /dev/null +++ b/src/mc/ajneb97/lib/actionbarapi/ActionBarMessageEvent.java @@ -0,0 +1,55 @@ +package mc.ajneb97.lib.actionbarapi; + +import org.bukkit.entity.Player; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; + +public class ActionBarMessageEvent + extends Event +{ + private static final HandlerList handlers = new HandlerList(); + private final Player player; + private String message; + private boolean cancelled = false; + + public ActionBarMessageEvent(Player player, String message) + { + this.player = player; + this.message = message; + } + + public HandlerList getHandlers() + { + return handlers; + } + + public static HandlerList getHandlerList() + { + return handlers; + } + + public Player getPlayer() + { + return this.player; + } + + public String getMessage() + { + return this.message; + } + + public void setMessage(String message) + { + this.message = message; + } + + public boolean isCancelled() + { + return this.cancelled; + } + + public void setCancelled(boolean cancelled) + { + this.cancelled = cancelled; + } +} diff --git a/src/mc/ajneb97/lib/fastboard/FastBoard.java b/src/mc/ajneb97/lib/fastboard/FastBoard.java new file mode 100644 index 0000000..b7e5921 --- /dev/null +++ b/src/mc/ajneb97/lib/fastboard/FastBoard.java @@ -0,0 +1,607 @@ +package mc.ajneb97.lib.fastboard; + +import org.bukkit.ChatColor; +import org.bukkit.entity.Player; + +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.lang.invoke.MethodType; +import java.lang.reflect.Array; +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.concurrent.ThreadLocalRandom; + +/** + * Lightweight packet-based scoreboard API for Bukkit plugins. + * It can be safely used asynchronously as everything is at packet level. + *

+ * The project is on GitHub. + * + * @author MrMicky + * @version 1.2.0-SNAPSHOT + */ +public class FastBoard { + + private static final Map, Field[]> PACKETS = new HashMap<>(8); + private static final String[] COLOR_CODES = Arrays.stream(ChatColor.values()) + .map(Object::toString) + .toArray(String[]::new); + private static final VersionType VERSION_TYPE; + // Packets and components + private static final Class CHAT_COMPONENT_CLASS; + private static final Class CHAT_FORMAT_ENUM; + private static final Object EMPTY_MESSAGE; + private static final Object RESET_FORMATTING; + private static final MethodHandle MESSAGE_FROM_STRING; + private static final MethodHandle PLAYER_CONNECTION; + private static final MethodHandle SEND_PACKET; + private static final MethodHandle PLAYER_GET_HANDLE; + // Scoreboard packets + private static final FastReflection.PacketConstructor PACKET_SB_OBJ; + private static final FastReflection.PacketConstructor PACKET_SB_DISPLAY_OBJ; + private static final FastReflection.PacketConstructor PACKET_SB_SCORE; + private static final FastReflection.PacketConstructor PACKET_SB_TEAM; + private static final FastReflection.PacketConstructor PACKET_SB_SERIALIZABLE_TEAM; + // Scoreboard enums + private static final Class ENUM_SB_HEALTH_DISPLAY; + private static final Class ENUM_SB_ACTION; + private static final Object ENUM_SB_HEALTH_DISPLAY_INTEGER; + private static final Object ENUM_SB_ACTION_CHANGE; + private static final Object ENUM_SB_ACTION_REMOVE; + + static { + try { + MethodHandles.Lookup lookup = MethodHandles.lookup(); + + if (FastReflection.isRepackaged()) { + VERSION_TYPE = VersionType.V1_17; + } else if (FastReflection.nmsOptionalClass(null, "ScoreboardServer$Action").isPresent()) { + VERSION_TYPE = VersionType.V1_13; + } else if (FastReflection.nmsOptionalClass(null, "IScoreboardCriteria$EnumScoreboardHealthDisplay").isPresent()) { + VERSION_TYPE = VersionType.V1_8; + } else { + VERSION_TYPE = VersionType.V1_7; + } + + String gameProtocolPackage = "network.protocol.game"; + Class craftPlayerClass = FastReflection.obcClass("entity.CraftPlayer"); + Class craftChatMessageClass = FastReflection.obcClass("util.CraftChatMessage"); + Class entityPlayerClass = FastReflection.nmsClass("server.level", "EntityPlayer"); + Class playerConnectionClass = FastReflection.nmsClass("server.network", "PlayerConnection"); + Class packetClass = FastReflection.nmsClass("network.protocol", "Packet"); + Class packetSbObjClass = FastReflection.nmsClass(gameProtocolPackage, "PacketPlayOutScoreboardObjective"); + Class packetSbDisplayObjClass = FastReflection.nmsClass(gameProtocolPackage, "PacketPlayOutScoreboardDisplayObjective"); + Class packetSbScoreClass = FastReflection.nmsClass(gameProtocolPackage, "PacketPlayOutScoreboardScore"); + Class packetSbTeamClass = FastReflection.nmsClass(gameProtocolPackage, "PacketPlayOutScoreboardTeam"); + Class sbTeamClass = VersionType.V1_17.isHigherOrEqual() + ? FastReflection.innerClass(packetSbTeamClass, innerClass -> !innerClass.isEnum()) : null; + Field playerConnectionField = Arrays.stream(entityPlayerClass.getFields()) + .filter(field -> field.getType().isAssignableFrom(playerConnectionClass)) + .findFirst().orElseThrow(NoSuchFieldException::new); + + MESSAGE_FROM_STRING = lookup.unreflect(craftChatMessageClass.getMethod("fromString", String.class)); + CHAT_COMPONENT_CLASS = FastReflection.nmsClass("network.chat", "IChatBaseComponent"); + CHAT_FORMAT_ENUM = FastReflection.nmsClass(null, "EnumChatFormat"); + EMPTY_MESSAGE = Array.get(MESSAGE_FROM_STRING.invoke(""), 0); + RESET_FORMATTING = FastReflection.enumValueOf(CHAT_FORMAT_ENUM, "RESET", 21); + PLAYER_GET_HANDLE = lookup.findVirtual(craftPlayerClass, "getHandle", MethodType.methodType(entityPlayerClass)); + PLAYER_CONNECTION = lookup.unreflectGetter(playerConnectionField); + SEND_PACKET = lookup.findVirtual(playerConnectionClass, "sendPacket", MethodType.methodType(void.class, packetClass)); + PACKET_SB_OBJ = FastReflection.findPacketConstructor(packetSbObjClass, lookup); + PACKET_SB_DISPLAY_OBJ = FastReflection.findPacketConstructor(packetSbDisplayObjClass, lookup); + PACKET_SB_SCORE = FastReflection.findPacketConstructor(packetSbScoreClass, lookup); + PACKET_SB_TEAM = FastReflection.findPacketConstructor(packetSbTeamClass, lookup); + PACKET_SB_SERIALIZABLE_TEAM = sbTeamClass == null ? null : FastReflection.findPacketConstructor(sbTeamClass, lookup); + + for (Class clazz : Arrays.asList(packetSbObjClass, packetSbDisplayObjClass, packetSbScoreClass, packetSbTeamClass, sbTeamClass)) { + if (clazz == null) { + continue; + } + Field[] fields = Arrays.stream(clazz.getDeclaredFields()) + .filter(field -> !Modifier.isStatic(field.getModifiers())) + .toArray(Field[]::new); + for (Field field : fields) { + field.setAccessible(true); + } + PACKETS.put(clazz, fields); + } + + if (VersionType.V1_8.isHigherOrEqual()) { + String enumSbActionClass = VersionType.V1_13.isHigherOrEqual() + ? "ScoreboardServer$Action" + : "PacketPlayOutScoreboardScore$EnumScoreboardAction"; + ENUM_SB_HEALTH_DISPLAY = FastReflection.nmsClass("world.scores.criteria", "IScoreboardCriteria$EnumScoreboardHealthDisplay"); + ENUM_SB_ACTION = FastReflection.nmsClass("server", enumSbActionClass); + ENUM_SB_HEALTH_DISPLAY_INTEGER = FastReflection.enumValueOf(ENUM_SB_HEALTH_DISPLAY, "INTEGER", 0); + ENUM_SB_ACTION_CHANGE = FastReflection.enumValueOf(ENUM_SB_ACTION, "CHANGE", 0); + ENUM_SB_ACTION_REMOVE = FastReflection.enumValueOf(ENUM_SB_ACTION, "REMOVE", 1); + } else { + ENUM_SB_HEALTH_DISPLAY = null; + ENUM_SB_ACTION = null; + ENUM_SB_HEALTH_DISPLAY_INTEGER = null; + ENUM_SB_ACTION_CHANGE = null; + ENUM_SB_ACTION_REMOVE = null; + } + } catch (Throwable t) { + throw new ExceptionInInitializerError(t); + } + } + + private final Player player; + private final String id; + + private final List lines = new ArrayList<>(); + private String title = ChatColor.RESET.toString(); + + private boolean deleted = false; + + /** + * Creates a new FastBoard. + * + * @param player the owner of the scoreboard + */ + public FastBoard(Player player) { + this.player = Objects.requireNonNull(player, "player"); + this.id = "fb-" + Integer.toHexString(ThreadLocalRandom.current().nextInt()); + + try { + sendObjectivePacket(ObjectiveMode.CREATE); + sendDisplayObjectivePacket(); + } catch (Throwable t) { + throw new RuntimeException("Unable to create scoreboard", t); + } + } + + /** + * Get the scoreboard title. + * + * @return the scoreboard title + */ + public String getTitle() { + return this.title; + } + + /** + * Update the scoreboard title. + * + * @param title the new scoreboard title + * @throws IllegalArgumentException if the title is longer than 32 chars on 1.12 or lower + * @throws IllegalStateException if {@link #delete()} was call before + */ + public void updateTitle(String title) { + if (this.title.equals(Objects.requireNonNull(title, "title"))) { + return; + } + + if (!VersionType.V1_13.isHigherOrEqual() && title.length() > 32) { + throw new IllegalArgumentException("Title is longer than 32 chars"); + } + + this.title = title; + + try { + sendObjectivePacket(ObjectiveMode.UPDATE); + } catch (Throwable t) { + throw new RuntimeException("Unable to update scoreboard title", t); + } + } + + /** + * Get the scoreboard lines. + * + * @return the scoreboard lines + */ + public List getLines() { + return new ArrayList<>(this.lines); + } + + /** + * Get the specified scoreboard line. + * + * @param line the line number + * @return the line + * @throws IndexOutOfBoundsException if the line is higher than {@code size} + */ + public String getLine(int line) { + checkLineNumber(line, true, false); + + return this.lines.get(line); + } + + /** + * Update a single scoreboard line. + * + * @param line the line number + * @param text the new line text + * @throws IndexOutOfBoundsException if the line is higher than {@link #size() size() + 1} + */ + public synchronized void updateLine(int line, String text) { + checkLineNumber(line, false, true); + + try { + if (line < size()) { + this.lines.set(line, text); + + sendTeamPacket(getScoreByLine(line), TeamMode.UPDATE); + return; + } + + List newLines = new ArrayList<>(this.lines); + + if (line > size()) { + for (int i = size(); i < line; i++) { + newLines.add(""); + } + } + + newLines.add(text); + + updateLines(newLines); + } catch (Throwable t) { + throw new RuntimeException("Unable to update scoreboard lines", t); + } + } + + /** + * Remove a scoreboard line. + * + * @param line the line number + */ + public synchronized void removeLine(int line) { + checkLineNumber(line, false, false); + + if (line >= size()) { + return; + } + + List newLines = new ArrayList<>(this.lines); + newLines.remove(line); + updateLines(newLines); + } + + /** + * Update all the scoreboard lines. + * + * @param lines the new lines + * @throws IllegalArgumentException if one line is longer than 30 chars on 1.12 or lower + * @throws IllegalStateException if {@link #delete()} was call before + */ + public void updateLines(String... lines) { + updateLines(Arrays.asList(lines)); + } + + /** + * Update the lines of the scoreboard + * + * @param lines the new scoreboard lines + * @throws IllegalArgumentException if one line is longer than 30 chars on 1.12 or lower + * @throws IllegalStateException if {@link #delete()} was call before + */ + public synchronized void updateLines(Collection lines) { + Objects.requireNonNull(lines, "lines"); + checkLineNumber(lines.size(), false, true); + + if (!VersionType.V1_13.isHigherOrEqual()) { + int lineCount = 0; + for (String s : lines) { + if (s != null && s.length() > 30) { + throw new IllegalArgumentException("Line " + lineCount + " is longer than 30 chars"); + } + lineCount++; + } + } + + List oldLines = new ArrayList<>(this.lines); + this.lines.clear(); + this.lines.addAll(lines); + + int linesSize = this.lines.size(); + + try { + if (oldLines.size() != linesSize) { + List oldLinesCopy = new ArrayList<>(oldLines); + + if (oldLines.size() > linesSize) { + for (int i = oldLinesCopy.size(); i > linesSize; i--) { + sendTeamPacket(i - 1, TeamMode.REMOVE); + sendScorePacket(i - 1, ScoreboardAction.REMOVE); + + oldLines.remove(0); + } + } else { + for (int i = oldLinesCopy.size(); i < linesSize; i++) { + sendScorePacket(i, ScoreboardAction.CHANGE); + sendTeamPacket(i, TeamMode.CREATE); + + oldLines.add(oldLines.size() - i, getLineByScore(i)); + } + } + } + + for (int i = 0; i < linesSize; i++) { + if (!Objects.equals(getLineByScore(oldLines, i), getLineByScore(i))) { + sendTeamPacket(i, TeamMode.UPDATE); + } + } + } catch (Throwable t) { + throw new RuntimeException("Unable to update scoreboard lines", t); + } + } + + /** + * Get the player who has the scoreboard. + * + * @return current player for this FastBoard + */ + public Player getPlayer() { + return this.player; + } + + /** + * Get the scoreboard id. + * + * @return the id + */ + public String getId() { + return this.id; + } + + /** + * Get if the scoreboard is deleted. + * + * @return true if the scoreboard is deleted + */ + public boolean isDeleted() { + return this.deleted; + } + + /** + * Get the scoreboard size (the number of lines). + * + * @return the size + */ + public int size() { + return this.lines.size(); + } + + /** + * Delete this FastBoard, and will remove the scoreboard for the associated player if he is online. + * After this, all uses of {@link #updateLines} and {@link #updateTitle} will throws an {@link IllegalStateException} + * + * @throws IllegalStateException if this was already call before + */ + public void delete() { + try { + for (int i = 0; i < this.lines.size(); i++) { + sendTeamPacket(i, TeamMode.REMOVE); + } + + sendObjectivePacket(ObjectiveMode.REMOVE); + } catch (Throwable t) { + throw new RuntimeException("Unable to delete scoreboard", t); + } + + this.deleted = true; + } + + /** + * Return if the player has a prefix/suffix characters limit. + * By default, it returns true only in 1.12 or lower. + * This method can be overridden to fix compatibility with some versions support plugin. + * + * @return max length + */ + protected boolean hasLinesMaxLength() { + return !VersionType.V1_13.isHigherOrEqual(); + } + + private void checkLineNumber(int line, boolean checkInRange, boolean checkMax) { + if (line < 0) { + throw new IllegalArgumentException("Line number must be positive"); + } + + if (checkInRange && line >= this.lines.size()) { + throw new IllegalArgumentException("Line number must be under " + this.lines.size()); + } + + if (checkMax && line >= COLOR_CODES.length - 1) { + throw new IllegalArgumentException("Line number is too high: " + this.lines.size()); + } + } + + private int getScoreByLine(int line) { + return this.lines.size() - line - 1; + } + + private String getLineByScore(int score) { + return getLineByScore(this.lines, score); + } + + private String getLineByScore(List lines, int score) { + return lines.get(lines.size() - score - 1); + } + + private void sendObjectivePacket(ObjectiveMode mode) throws Throwable { + Object packet = PACKET_SB_OBJ.invoke(); + + setField(packet, String.class, this.id); + setField(packet, int.class, mode.ordinal()); + + if (mode != ObjectiveMode.REMOVE) { + setComponentField(packet, this.title, 1); + + if (VersionType.V1_8.isHigherOrEqual()) { + setField(packet, ENUM_SB_HEALTH_DISPLAY, ENUM_SB_HEALTH_DISPLAY_INTEGER); + } + } else if (VERSION_TYPE == VersionType.V1_7) { + setField(packet, String.class, "", 1); + } + + sendPacket(packet); + } + + private void sendDisplayObjectivePacket() throws Throwable { + Object packet = PACKET_SB_DISPLAY_OBJ.invoke(); + + setField(packet, int.class, 1); // Position (1: sidebar) + setField(packet, String.class, this.id); // Score Name + + sendPacket(packet); + } + + private void sendScorePacket(int score, ScoreboardAction action) throws Throwable { + Object packet = PACKET_SB_SCORE.invoke(); + + setField(packet, String.class, COLOR_CODES[score], 0); // Player Name + + if (VersionType.V1_8.isHigherOrEqual()) { + setField(packet, ENUM_SB_ACTION, action == ScoreboardAction.REMOVE ? ENUM_SB_ACTION_REMOVE : ENUM_SB_ACTION_CHANGE); + } else { + setField(packet, int.class, action.ordinal(), 1); // Action + } + + if (action == ScoreboardAction.CHANGE) { + setField(packet, String.class, this.id, 1); // Objective Name + setField(packet, int.class, score); // Score + } + + sendPacket(packet); + } + + private void sendTeamPacket(int score, TeamMode mode) throws Throwable { + if (mode == TeamMode.ADD_PLAYERS || mode == TeamMode.REMOVE_PLAYERS) { + throw new UnsupportedOperationException(); + } + + int maxLength = hasLinesMaxLength() ? 16 : 1024; + Object packet = PACKET_SB_TEAM.invoke(); + + setField(packet, String.class, this.id + ':' + score); // Team name + setField(packet, int.class, mode.ordinal(), VERSION_TYPE == VersionType.V1_8 ? 1 : 0); // Update mode + + if (mode == TeamMode.CREATE || mode == TeamMode.UPDATE) { + String line = getLineByScore(score); + String prefix; + String suffix = null; + + if (line == null || line.isEmpty()) { + prefix = COLOR_CODES[score] + ChatColor.RESET; + } else if (line.length() <= maxLength) { + prefix = line; + } else { + // Prevent splitting color codes + int index = line.charAt(maxLength - 1) == ChatColor.COLOR_CHAR ? (maxLength - 1) : maxLength; + prefix = line.substring(0, index); + String suffixTmp = line.substring(index); + ChatColor chatColor = null; + + if (suffixTmp.length() >= 2 && suffixTmp.charAt(0) == ChatColor.COLOR_CHAR) { + chatColor = ChatColor.getByChar(suffixTmp.charAt(1)); + } + + String color = ChatColor.getLastColors(prefix); + boolean addColor = chatColor == null || chatColor.isFormat(); + + suffix = (addColor ? (color.isEmpty() ? ChatColor.RESET.toString() : color) : "") + suffixTmp; + } + + if (prefix.length() > maxLength || (suffix != null && suffix.length() > maxLength)) { + // Something went wrong, just cut to prevent client crash/kick + prefix = prefix.substring(0, maxLength); + suffix = (suffix != null) ? suffix.substring(0, maxLength) : null; + } + + if (VersionType.V1_17.isHigherOrEqual()) { + Object team = PACKET_SB_SERIALIZABLE_TEAM.invoke(); + // Since the packet is initialized with null values, we need to change more things. + setComponentField(team, "", 0); // Display name + setField(team, CHAT_FORMAT_ENUM, RESET_FORMATTING); // Color + setComponentField(team, prefix, 1); // Prefix + setComponentField(team, suffix == null ? "" : suffix, 2); // Suffix + setField(team, String.class, "always", 0); // Visibility + setField(team, String.class, "always", 1); // Collisions + setField(packet, Optional.class, Optional.of(team)); + } else { + setComponentField(packet, prefix, 2); // Prefix + setComponentField(packet, suffix == null ? "" : suffix, 3); // Suffix + setField(packet, String.class, "always", 4); // Visibility for 1.8+ + setField(packet, String.class, "always", 5); // Collisions for 1.9+ + } + + if (mode == TeamMode.CREATE) { + setField(packet, Collection.class, Collections.singletonList(COLOR_CODES[score])); // Players in the team + } + } + + sendPacket(packet); + } + + private void sendPacket(Object packet) throws Throwable { + if (this.deleted) { + throw new IllegalStateException("This FastBoard is deleted"); + } + + if (this.player.isOnline()) { + Object entityPlayer = PLAYER_GET_HANDLE.invoke(this.player); + Object playerConnection = PLAYER_CONNECTION.invoke(entityPlayer); + SEND_PACKET.invoke(playerConnection, packet); + } + } + + private void setField(Object object, Class fieldType, Object value) throws ReflectiveOperationException { + setField(object, fieldType, value, 0); + } + + private void setField(Object packet, Class fieldType, Object value, int count) throws ReflectiveOperationException { + int i = 0; + for (Field field : PACKETS.get(packet.getClass())) { + if (field.getType() == fieldType && count == i++) { + field.set(packet, value); + } + } + } + + private void setComponentField(Object packet, String value, int count) throws Throwable { + if (!VersionType.V1_13.isHigherOrEqual()) { + setField(packet, String.class, value, count); + return; + } + + int i = 0; + for (Field field : PACKETS.get(packet.getClass())) { + if ((field.getType() == String.class || field.getType() == CHAT_COMPONENT_CLASS) && count == i++) { + field.set(packet, value.isEmpty() ? EMPTY_MESSAGE : Array.get(MESSAGE_FROM_STRING.invoke(value), 0)); + } + } + } + + enum ObjectiveMode { + CREATE, REMOVE, UPDATE + } + + enum TeamMode { + CREATE, REMOVE, UPDATE, ADD_PLAYERS, REMOVE_PLAYERS + } + + enum ScoreboardAction { + CHANGE, REMOVE + } + + enum VersionType { + V1_7, V1_8, V1_13, V1_17; + + public boolean isHigherOrEqual() { + return VERSION_TYPE.ordinal() >= ordinal(); + } + } +} + diff --git a/src/mc/ajneb97/lib/fastboard/FastReflection.java b/src/mc/ajneb97/lib/fastboard/FastReflection.java new file mode 100644 index 0000000..c784a97 --- /dev/null +++ b/src/mc/ajneb97/lib/fastboard/FastReflection.java @@ -0,0 +1,128 @@ +package mc.ajneb97.lib.fastboard; + +import org.bukkit.Bukkit; + +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.lang.invoke.MethodType; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.Optional; +import java.util.function.Predicate; + +/** + * Small reflection utility class to use CraftBukkit and NMS. + * + * @author MrMicky + */ +public final class FastReflection { + + private static final String NM_PACKAGE = "net.minecraft"; + public static final String OBC_PACKAGE = "org.bukkit.craftbukkit"; + public static final String NMS_PACKAGE = NM_PACKAGE + ".server"; + + public static final String VERSION = Bukkit.getServer().getClass().getPackage().getName().substring(OBC_PACKAGE.length() + 1); + + private static final MethodType VOID_METHOD_TYPE = MethodType.methodType(void.class); + private static final boolean NMS_REPACKAGED = optionalClass(NM_PACKAGE + ".network.protocol.Packet").isPresent(); + + private static volatile Object theUnsafe; + + private FastReflection() { + throw new UnsupportedOperationException(); + } + + public static boolean isRepackaged() { + return NMS_REPACKAGED; + } + + public static String nmsClassName(String post1_17package, String className) { + if (NMS_REPACKAGED) { + String classPackage = post1_17package == null ? NM_PACKAGE : NM_PACKAGE + '.' + post1_17package; + return classPackage + '.' + className; + } + return NMS_PACKAGE + '.' + VERSION + '.' + className; + } + + public static Class nmsClass(String post1_17package, String className) throws ClassNotFoundException { + return Class.forName(nmsClassName(post1_17package, className)); + } + + public static Optional> nmsOptionalClass(String post1_17package, String className) { + return optionalClass(nmsClassName(post1_17package, className)); + } + + public static String obcClassName(String className) { + return OBC_PACKAGE + '.' + VERSION + '.' + className; + } + + public static Class obcClass(String className) throws ClassNotFoundException { + return Class.forName(obcClassName(className)); + } + + public static Optional> obcOptionalClass(String className) { + return optionalClass(obcClassName(className)); + } + + public static Optional> optionalClass(String className) { + try { + return Optional.of(Class.forName(className)); + } catch (ClassNotFoundException e) { + return Optional.empty(); + } + } + + public static Object enumValueOf(Class enumClass, String enumName) { + return Enum.valueOf(enumClass.asSubclass(Enum.class), enumName); + } + + public static Object enumValueOf(Class enumClass, String enumName, int fallbackOrdinal) { + try { + return enumValueOf(enumClass, enumName); + } catch (IllegalArgumentException e) { + Object[] constants = enumClass.getEnumConstants(); + if (constants.length > fallbackOrdinal) { + return constants[fallbackOrdinal]; + } + throw e; + } + } + + static Class innerClass(Class parentClass, Predicate> classPredicate) throws ClassNotFoundException { + for (Class innerClass : parentClass.getDeclaredClasses()) { + if (classPredicate.test(innerClass)) { + return innerClass; + } + } + throw new ClassNotFoundException("No class in " + parentClass.getCanonicalName() + " matches the predicate."); + } + + public static PacketConstructor findPacketConstructor(Class packetClass, MethodHandles.Lookup lookup) throws Exception { + try { + MethodHandle constructor = lookup.findConstructor(packetClass, VOID_METHOD_TYPE); + return constructor::invoke; + } catch (NoSuchMethodException | IllegalAccessException e) { + // try below with Unsafe + } + + if (theUnsafe == null) { + synchronized (FastReflection.class) { + if (theUnsafe == null) { + Class unsafeClass = Class.forName("sun.misc.Unsafe"); + Field theUnsafeField = unsafeClass.getDeclaredField("theUnsafe"); + theUnsafeField.setAccessible(true); + theUnsafe = theUnsafeField.get(null); + } + } + } + + Method allocateMethod = theUnsafe.getClass().getMethod("allocateInstance", Class.class); + return () -> allocateMethod.invoke(theUnsafe, packetClass); + } + + @FunctionalInterface + interface PacketConstructor { + Object invoke() throws Throwable; + } +} + diff --git a/src/mc/ajneb97/lib/titleapi/TabTitleSendEvent.java b/src/mc/ajneb97/lib/titleapi/TabTitleSendEvent.java new file mode 100644 index 0000000..d663aef --- /dev/null +++ b/src/mc/ajneb97/lib/titleapi/TabTitleSendEvent.java @@ -0,0 +1,57 @@ +package mc.ajneb97.lib.titleapi; + +import org.bukkit.entity.Player; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; + +public class TabTitleSendEvent extends Event { + private static final HandlerList handlers = new HandlerList(); + private final Player player; + private String header; + private String footer; + private boolean cancelled = false; + + public TabTitleSendEvent(Player player, String header, String footer) { + this.player = player; + this.header = header; + this.footer = footer; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + public Player getPlayer() { + return player; + } + + public String getHeader() { + return header; + } + + public void setHeader(String header) { + this.header = header; + } + + public String getFooter() { + return footer; + } + + public void setFooter(String footer) { + this.footer = footer; + } + + public boolean isCancelled() { + return cancelled; + } + + public void setCancelled(boolean cancelled) { + this.cancelled = cancelled; + } + +} \ No newline at end of file diff --git a/src/mc/ajneb97/lib/titleapi/TitleAPI.java b/src/mc/ajneb97/lib/titleapi/TitleAPI.java new file mode 100644 index 0000000..28452a0 --- /dev/null +++ b/src/mc/ajneb97/lib/titleapi/TitleAPI.java @@ -0,0 +1,158 @@ +package mc.ajneb97.lib.titleapi; + +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Server; +import org.bukkit.command.ConsoleCommandSender; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.plugin.java.JavaPlugin; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; + + +public class TitleAPI implements Listener { + + @Deprecated + public static void sendSubtitle(Player player, Integer fadeIn, Integer stay, Integer fadeOut, String message) { + sendTitle(player, fadeIn, stay, fadeOut, null, message); + } + + @Deprecated + public static void sendFullTitle(Player player, Integer fadeIn, Integer stay, Integer fadeOut, String title, String subtitle) { + sendTitle(player, fadeIn, stay, fadeOut, title, subtitle); + } + + public static void sendPacket(Player player, Object packet) { + try { + Object handle = player.getClass().getMethod("getHandle").invoke(player); + Object playerConnection = handle.getClass().getField("playerConnection").get(handle); + playerConnection.getClass().getMethod("sendPacket", getNMSClass("Packet")).invoke(playerConnection, packet); + } catch (Exception e) { + e.printStackTrace(); + } + } + + public static Class getNMSClass(String name) { + String version = Bukkit.getServer().getClass().getPackage().getName().split("\\.")[3]; + try { + return Class.forName("net.minecraft.server." + version + "." + name); + } catch (ClassNotFoundException e) { + e.printStackTrace(); + return null; + } + } + + public static void sendTitle(Player player, Integer fadeIn, Integer stay, Integer fadeOut, String title, String subtitle) { + TitleSendEvent titleSendEvent = new TitleSendEvent(player, title, subtitle); + if(Bukkit.getVersion().contains("1.13") || Bukkit.getVersion().contains("1.14") || Bukkit.getVersion().contains("1.15") + || Bukkit.getVersion().contains("1.16") || Bukkit.getVersion().contains("1.17")) { + if(title.isEmpty()) { + title = " "; + } + if(subtitle.isEmpty()) { + subtitle = " "; + } + title = ChatColor.translateAlternateColorCodes('&', title); + subtitle = ChatColor.translateAlternateColorCodes('&', subtitle); + player.sendTitle(title, subtitle, fadeIn, stay, fadeOut); + return; + } + Bukkit.getPluginManager().callEvent(titleSendEvent); + if (titleSendEvent.isCancelled()) + return; + + try { + Object e; + Object chatTitle; + Object chatSubtitle; + Constructor subtitleConstructor; + Object titlePacket; + Object subtitlePacket; + + if (title != null) { + title = ChatColor.translateAlternateColorCodes('&', title); + title = title.replaceAll("%player%", player.getDisplayName()); + // Times packets + e = getNMSClass("PacketPlayOutTitle").getDeclaredClasses()[0].getField("TIMES").get((Object) null); + chatTitle = getNMSClass("IChatBaseComponent").getDeclaredClasses()[0].getMethod("a", new Class[]{String.class}).invoke((Object) null, new Object[]{"{\"text\":\"" + title + "\"}"}); + subtitleConstructor = getNMSClass("PacketPlayOutTitle").getConstructor(new Class[]{getNMSClass("PacketPlayOutTitle").getDeclaredClasses()[0], getNMSClass("IChatBaseComponent"), Integer.TYPE, Integer.TYPE, Integer.TYPE}); + titlePacket = subtitleConstructor.newInstance(new Object[]{e, chatTitle, fadeIn, stay, fadeOut}); + sendPacket(player, titlePacket); + + e = getNMSClass("PacketPlayOutTitle").getDeclaredClasses()[0].getField("TITLE").get((Object) null); + chatTitle = getNMSClass("IChatBaseComponent").getDeclaredClasses()[0].getMethod("a", new Class[]{String.class}).invoke((Object) null, new Object[]{"{\"text\":\"" + title + "\"}"}); + subtitleConstructor = getNMSClass("PacketPlayOutTitle").getConstructor(new Class[]{getNMSClass("PacketPlayOutTitle").getDeclaredClasses()[0], getNMSClass("IChatBaseComponent")}); + titlePacket = subtitleConstructor.newInstance(new Object[]{e, chatTitle}); + sendPacket(player, titlePacket); + } + + if (subtitle != null) { + subtitle = ChatColor.translateAlternateColorCodes('&', subtitle); + subtitle = subtitle.replaceAll("%player%", player.getDisplayName()); + // Times packets + e = getNMSClass("PacketPlayOutTitle").getDeclaredClasses()[0].getField("TIMES").get((Object) null); + chatSubtitle = getNMSClass("IChatBaseComponent").getDeclaredClasses()[0].getMethod("a", new Class[]{String.class}).invoke((Object) null, new Object[]{"{\"text\":\"" + title + "\"}"}); + subtitleConstructor = getNMSClass("PacketPlayOutTitle").getConstructor(new Class[]{getNMSClass("PacketPlayOutTitle").getDeclaredClasses()[0], getNMSClass("IChatBaseComponent"), Integer.TYPE, Integer.TYPE, Integer.TYPE}); + subtitlePacket = subtitleConstructor.newInstance(new Object[]{e, chatSubtitle, fadeIn, stay, fadeOut}); + sendPacket(player, subtitlePacket); + + e = getNMSClass("PacketPlayOutTitle").getDeclaredClasses()[0].getField("SUBTITLE").get((Object) null); + chatSubtitle = getNMSClass("IChatBaseComponent").getDeclaredClasses()[0].getMethod("a", new Class[]{String.class}).invoke((Object) null, new Object[]{"{\"text\":\"" + subtitle + "\"}"}); + subtitleConstructor = getNMSClass("PacketPlayOutTitle").getConstructor(new Class[]{getNMSClass("PacketPlayOutTitle").getDeclaredClasses()[0], getNMSClass("IChatBaseComponent"), Integer.TYPE, Integer.TYPE, Integer.TYPE}); + subtitlePacket = subtitleConstructor.newInstance(new Object[]{e, chatSubtitle, fadeIn, stay, fadeOut}); + sendPacket(player, subtitlePacket); + } + } catch (Exception var11) { + var11.printStackTrace(); + } + } + + public static void clearTitle(Player player) { + sendTitle(player, 0, 0, 0, "", ""); + } + + public static void sendTabTitle(Player player, String header, String footer) { + if (header == null) header = ""; + header = ChatColor.translateAlternateColorCodes('&', header); + + if (footer == null) footer = ""; + footer = ChatColor.translateAlternateColorCodes('&', footer); + + TabTitleSendEvent tabTitleSendEvent = new TabTitleSendEvent(player, header, footer); + Bukkit.getPluginManager().callEvent(tabTitleSendEvent); + if (tabTitleSendEvent.isCancelled()) + return; + + header = header.replaceAll("%player%", player.getDisplayName()); + footer = footer.replaceAll("%player%", player.getDisplayName()); + + try { + Object tabHeader = getNMSClass("IChatBaseComponent").getDeclaredClasses()[0].getMethod("a", String.class).invoke(null, "{\"text\":\"" + header + "\"}"); + Object tabFooter = getNMSClass("IChatBaseComponent").getDeclaredClasses()[0].getMethod("a", String.class).invoke(null, "{\"text\":\"" + footer + "\"}"); + Constructor titleConstructor = getNMSClass("PacketPlayOutPlayerListHeaderFooter").getConstructor(); + Object packet = titleConstructor.newInstance(); + try { + Field aField = packet.getClass().getDeclaredField("a"); + aField.setAccessible(true); + aField.set(packet, tabHeader); + Field bField = packet.getClass().getDeclaredField("b"); + bField.setAccessible(true); + bField.set(packet, tabFooter); + } catch (Exception e) { + Field aField = packet.getClass().getDeclaredField("header"); + aField.setAccessible(true); + aField.set(packet, tabHeader); + Field bField = packet.getClass().getDeclaredField("footer"); + bField.setAccessible(true); + bField.set(packet, tabFooter); + } + sendPacket(player, packet); + } catch (Exception ex) { + ex.printStackTrace(); + } + } +} \ No newline at end of file diff --git a/src/mc/ajneb97/lib/titleapi/TitleSendEvent.java b/src/mc/ajneb97/lib/titleapi/TitleSendEvent.java new file mode 100644 index 0000000..eb48a49 --- /dev/null +++ b/src/mc/ajneb97/lib/titleapi/TitleSendEvent.java @@ -0,0 +1,57 @@ +package mc.ajneb97.lib.titleapi; + +import org.bukkit.entity.Player; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; + +public class TitleSendEvent extends Event { + private static final HandlerList handlers = new HandlerList(); + private final Player player; + private String title; + private String subtitle; + private boolean cancelled = false; + + public TitleSendEvent(Player player, String title, String subtitle) { + this.player = player; + this.title = title; + this.subtitle = subtitle; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + public Player getPlayer() { + return player; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getSubtitle() { + return subtitle; + } + + public void setSubtitle(String subtitle) { + this.subtitle = subtitle; + } + + public boolean isCancelled() { + return cancelled; + } + + public void setCancelled(boolean cancelled) { + this.cancelled = cancelled; + } + +} \ No newline at end of file diff --git a/src/mc/ajneb97/managers/CartelesListener.java b/src/mc/ajneb97/managers/CartelesListener.java new file mode 100644 index 0000000..09704da --- /dev/null +++ b/src/mc/ajneb97/managers/CartelesListener.java @@ -0,0 +1,153 @@ +package mc.ajneb97.managers; + +import java.util.List; + +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.World; +import org.bukkit.block.Block; +import org.bukkit.block.Sign; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.block.Action; +import org.bukkit.event.block.BlockBreakEvent; +import org.bukkit.event.block.SignChangeEvent; +import org.bukkit.event.player.PlayerInteractEvent; + +import mc.ajneb97.MineChess; +import mc.ajneb97.juego.Estado; +import mc.ajneb97.juego.Partida; +import mc.ajneb97.otros.Utilidades; + +public class CartelesListener implements Listener{ + + private MineChess plugin; + public CartelesListener(MineChess plugin) { + this.plugin = plugin; + } + + //Al poner Cartel + @EventHandler + public void crearCartel(SignChangeEvent event ) { + Player jugador = event.getPlayer(); + if(jugador.isOp() || jugador.hasPermission("chess.admin")) { + if(event.getLine(0).equals("[Chess]")) { + String arena = event.getLine(1); + if(arena != null && plugin.getPartida(arena) != null) { + FileConfiguration config = plugin.getConfig(); + Partida partida = plugin.getPartida(arena); + String estado = ""; + if(partida.estaIniciada()) { + estado = config.getString("Messages.signStatusIngame"); + }else if(partida.getEstado().equals(Estado.COMENZANDO)) { + estado = config.getString("Messages.signStatusStarting"); + }else if(partida.getEstado().equals(Estado.ESPERANDO)) { + estado = config.getString("Messages.signStatusWaiting"); + }else if(partida.getEstado().equals(Estado.DESACTIVADA)) { + estado = config.getString("Messages.signStatusDisabled"); + }else if(partida.getEstado().equals(Estado.TERMINANDO)) { + estado = config.getString("Messages.signStatusFinishing"); + } + + List lista = config.getStringList("Messages.signFormat"); + for(int i=0;i jugadores = partida.getJugadores(); + for(int i=0;i 0) { + ArrayList jugadores = partida.getJugadores(); + for(int i=0;i jugadores = partida.getJugadores(); + for(int i=0;i jugadores = partida.getJugadores(); + Jugador turno = partida.getTurno(); + String contrincante = ""; + if(turno.equals(partida.getJugador1())) { + contrincante = partida.getJugador1().getJugador().getName(); + }else { + contrincante = partida.getJugador2().getJugador().getName(); + } + for(int i=0;i locs){ + this.jugador = j; + this.partida = partida; + this.pieza = pieza; + BukkitScheduler scheduler = Bukkit.getServer().getScheduler(); + taskID = scheduler.scheduleSyncRepeatingTask(plugin, new Runnable() { + public void run(){ + if(!ejecutarCooldownParticulaSeleccionada(locs)){ + Bukkit.getScheduler().cancelTask(taskID); + return; + } + } + }, 0L, 5L); + } + + protected boolean ejecutarCooldownParticulaSeleccionada(ArrayList locs) { + if(jugador != null) { + if(partida != null && partida.getEstado().equals(Estado.JUGANDO)) { + Pieza p = jugador.getPiezaSeleccionada(); + if(p == null) { + return false; + } + if(pieza == null) { + return false; + } + if((p.getId() != pieza.getId())) { + return false; + } + if(locs != null) { + for(MovimientoPosible loc : locs) { + Location nueva = loc.getLocation().clone().add(0.5,0,0.5); + double y = partida.getEsquina1().getY(); + nueva.setY(y+1.35); + + Utilidades.generarParticula("VILLAGER_HAPPY", nueva.clone().add(0.5,0,0.5), 0.001F, 0.001F, 0.001F, 0.001F, 1, jugador.getJugador()); + Utilidades.generarParticula("VILLAGER_HAPPY", nueva.clone().add(0.5,0,-0.5), 0.001F, 0.001F, 0.001F, 0.001F, 1, jugador.getJugador()); + Utilidades.generarParticula("VILLAGER_HAPPY", nueva.clone().add(-0.5,0,0.5), 0.001F, 0.001F, 0.001F, 0.001F, 1, jugador.getJugador()); + Utilidades.generarParticula("VILLAGER_HAPPY", nueva.clone().add(-0.5,0,-0.5), 0.001F, 0.001F, 0.001F, 0.001F, 1, jugador.getJugador()); + } + } + + return true; + }else { + return false; + } + }else { + return false; + } + } + + public void cooldownParticulaObservarMovimiento(Jugador j,Partida partida,final Location loc){ + this.jugador = j; + this.partida = partida; + BukkitScheduler scheduler = Bukkit.getServer().getScheduler(); + taskID = scheduler.scheduleSyncRepeatingTask(plugin, new Runnable() { + public void run(){ + if(!ejecutarCooldownObservarMovimiento(loc)){ + Bukkit.getScheduler().cancelTask(taskID); + return; + } + } + }, 0L, 5L); + } + + protected boolean ejecutarCooldownObservarMovimiento(Location loc) { + if(jugador != null) { + if(partida != null && partida.getEstado().equals(Estado.JUGANDO)) { + int[] celdaS = jugador.getCeldaObservada(); + if(celdaS == null) { + return false; + } + + if(loc != null) { + Location nueva = loc.clone().add(0.5,0,0.5); + double y = partida.getEsquina1().getY(); + nueva.setY(y+1.35); + + Utilidades.generarParticula("FLAME", nueva.clone().add(0.5,0,0.5), 0.001F, 0.001F, 0.001F, 0.01F, 1, jugador.getJugador()); + Utilidades.generarParticula("FLAME", nueva.clone().add(0.5,0,-0.5), 0.001F, 0.001F, 0.001F, 0.01F, 1, jugador.getJugador()); + Utilidades.generarParticula("FLAME", nueva.clone().add(-0.5,0,0.5), 0.001F, 0.001F, 0.001F, 0.01F, 1, jugador.getJugador()); + Utilidades.generarParticula("FLAME", nueva.clone().add(-0.5,0,-0.5), 0.001F, 0.001F, 0.001F, 0.01F, 1, jugador.getJugador()); + } + + return true; + }else { + return false; + } + }else { + return false; + } + } +} diff --git a/src/mc/ajneb97/managers/CooldownTurno.java b/src/mc/ajneb97/managers/CooldownTurno.java new file mode 100644 index 0000000..e64cf65 --- /dev/null +++ b/src/mc/ajneb97/managers/CooldownTurno.java @@ -0,0 +1,56 @@ +package mc.ajneb97.managers; + +import org.bukkit.Bukkit; +import org.bukkit.scheduler.BukkitScheduler; + +import mc.ajneb97.MineChess; +import mc.ajneb97.juego.Estado; +import mc.ajneb97.juego.Jugador; +import mc.ajneb97.juego.Partida; + +public class CooldownTurno { + + private Partida partida; + int taskID; + int tiempo; + private MineChess plugin; + public CooldownTurno(MineChess plugin){ + this.plugin = plugin; + } + + public void cooldown(Partida partida,int tiempo,final String accion){ + this.partida = partida; + Jugador turno = partida.getTurno(); + this.tiempo = tiempo; + turno.setTiempo(tiempo); + BukkitScheduler scheduler = Bukkit.getServer().getScheduler(); + taskID = scheduler.scheduleSyncRepeatingTask(plugin, new Runnable() { + public void run(){ + if(!ejecutarCooldown(accion)){ + Bukkit.getScheduler().cancelTask(taskID); + return; + } + } + }, 0L, 20L); + } + + protected boolean ejecutarCooldown(String accion) { + if(partida != null && partida.getEstado().equals(Estado.JUGANDO)) { + Jugador turno = partida.getTurno(); + if(turno.getTiempo() > 0) { + turno.disminuirTiempo(); + }else { + if(accion.equalsIgnoreCase("pass")) { + PartidaManager.cambiarTurno(partida, plugin.getConfig(), plugin); + }else { + //mover + PartidaManager.moverPiezaAleatoria(partida, plugin); + } + + } + return true; + }else { + return false; + } + } +} diff --git a/src/mc/ajneb97/managers/Entrar.java b/src/mc/ajneb97/managers/Entrar.java new file mode 100644 index 0000000..e25fb25 --- /dev/null +++ b/src/mc/ajneb97/managers/Entrar.java @@ -0,0 +1,26 @@ +package mc.ajneb97.managers; + +import org.bukkit.ChatColor; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerJoinEvent; + +import mc.ajneb97.MineChess; + +public class Entrar implements Listener{ + private MineChess plugin; + public Entrar(MineChess plugin){ + this.plugin = plugin; + } + @EventHandler + public void Join(PlayerJoinEvent event){ + Player jugador = event.getPlayer(); + if(jugador.isOp() && !(plugin.version.equals(plugin.latestversion))){ + jugador.sendMessage(plugin.prefix + ChatColor.RED +" There is a new version available. "+ChatColor.YELLOW+ + "("+ChatColor.GRAY+plugin.latestversion+ChatColor.YELLOW+")"); + jugador.sendMessage(ChatColor.RED+"You can download it at: "+ChatColor.GREEN+"https://www.spigotmc.org/resources/74178/"); + } + } +} diff --git a/src/mc/ajneb97/managers/InventarioCoronacion.java b/src/mc/ajneb97/managers/InventarioCoronacion.java new file mode 100644 index 0000000..175b608 --- /dev/null +++ b/src/mc/ajneb97/managers/InventarioCoronacion.java @@ -0,0 +1,222 @@ +package mc.ajneb97.managers; + +import java.util.ArrayList; + +import org.bukkit.Bukkit; +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.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +import mc.ajneb97.MineChess; +import mc.ajneb97.juego.Jugador; +import mc.ajneb97.juego.Partida; +import mc.ajneb97.juego.Pieza; +import mc.ajneb97.juego.Tablero; +import mc.ajneb97.otros.Utilidades; +import net.md_5.bungee.api.ChatColor; + +public class InventarioCoronacion implements Listener { + + private MineChess plugin; + public InventarioCoronacion(MineChess plugin) { + this.plugin = plugin; + } + + public static void crearInventario(Jugador jugador,MineChess plugin) { + FileConfiguration config = plugin.getConfig(); + Inventory inv = Bukkit.createInventory(null, 9, ChatColor.translateAlternateColorCodes('&', config.getString("Messages.pawnPromotionInventoryTitle"))); + + ItemStack item = null; + + //Torre + if(Bukkit.getVersion().contains("1.13") || Bukkit.getVersion().contains("1.14") || Bukkit.getVersion().contains("1.15") + || Bukkit.getVersion().contains("1.16") || Bukkit.getVersion().contains("1.17")) { + item = new ItemStack(Material.valueOf("PLAYER_HEAD"),1); + }else { + item = new ItemStack(Material.SKULL_ITEM,1,(short) 3); + } + item = Utilidades.getCabeza(item, "5e193aa2-292e-43c6-b92b-e823f6e0cc1e", "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvZjQ1NTlkNzU0NjRiMmU0MGE1MThlNGRlOGU2Y2YzMDg1ZjBhM2NhMGIxYjcwMTI2MTRjNGNkOTZmZWQ2MDM3OCJ9fX0="); + ItemMeta meta = item.getItemMeta(); + meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', config.getString("Messages.promoteItemName").replace("%piece%", config.getString("Messages.pieceRook")))); + item.setItemMeta(meta); + inv.setItem(1, item); + + //Caballo + if(Bukkit.getVersion().contains("1.13") || Bukkit.getVersion().contains("1.14") || Bukkit.getVersion().contains("1.15") + || Bukkit.getVersion().contains("1.16") || Bukkit.getVersion().contains("1.17")) { + item = new ItemStack(Material.valueOf("PLAYER_HEAD"),1); + }else { + item = new ItemStack(Material.SKULL_ITEM,1,(short) 3); + } + item = Utilidades.getCabeza(item, "022202fd-9546-4492-b8b6-b768e95701c2", "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvN2JiNGIyODg5OTFlZmI4Y2EwNzQzYmVjY2VmMzEyNThiMzFkMzlmMjQ5NTFlZmIxYzljMThhNDE3YmE0OGY5In19fQ=="); + meta = item.getItemMeta(); + meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', config.getString("Messages.promoteItemName").replace("%piece%", config.getString("Messages.pieceKnight")))); + item.setItemMeta(meta); + inv.setItem(3, item); + + //Alfil + if(Bukkit.getVersion().contains("1.13") || Bukkit.getVersion().contains("1.14") || Bukkit.getVersion().contains("1.15") + || Bukkit.getVersion().contains("1.16") || Bukkit.getVersion().contains("1.17")) { + item = new ItemStack(Material.valueOf("PLAYER_HEAD"),1); + }else { + item = new ItemStack(Material.SKULL_ITEM,1,(short) 3); + } + if(jugador.getColor().equals("b")) { + item = Utilidades.getCabeza(item, "eb1fc1a8-763e-442f-bf10-302b3beebb32", "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvMTI2Yjc3MjMyOWNmMzJmODY0M2M0OTI4NjI2YjZhMzI1MjMzZmY2MWFhOWM3NzI1ODczYTRiZDY2ZGIzZDY5MiJ9fX0="); + }else { + item = Utilidades.getCabeza(item, "c7b9f611-64c6-4e9c-ac97-8dedf8b97e17", "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvZjZjNWVjYWM5NDJjNzdiOTVhYjQ2MjBkZjViODVlMzgwNjRjOTc0ZjljNWM1NzZiODQzNjIyODA2YTQ1NTcifX19"); + } + + meta = item.getItemMeta(); + meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', config.getString("Messages.promoteItemName").replace("%piece%", config.getString("Messages.pieceBishop")))); + item.setItemMeta(meta); + inv.setItem(5, item); + + //Reina + if(Bukkit.getVersion().contains("1.13") || Bukkit.getVersion().contains("1.14") || Bukkit.getVersion().contains("1.15") + || Bukkit.getVersion().contains("1.16") || Bukkit.getVersion().contains("1.17")) { + item = new ItemStack(Material.valueOf("PLAYER_HEAD"),1); + }else { + item = new ItemStack(Material.SKULL_ITEM,1,(short) 3); + } + item = Utilidades.getCabeza(item, "fdea850d-ae8b-4e10-8b03-6883494ae266", "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvNTRiZjg5M2ZjNmRlZmFkMjE4Zjc4MzZlZmVmYmU2MzZmMWMyY2MxYmI2NTBjODJmY2NkOTlmMmMxZWU2In19fQ=="); + meta = item.getItemMeta(); + meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', config.getString("Messages.promoteItemName").replace("%piece%", config.getString("Messages.pieceQueen")))); + item.setItemMeta(meta); + inv.setItem(7, item); + + jugador.getJugador().openInventory(inv); + } + + @EventHandler + public void clickearInventarioCoronacion(InventoryClickEvent event) { + FileConfiguration config = plugin.getConfig(); + String pathInventory = ChatColor.translateAlternateColorCodes('&', config.getString("Messages.pawnPromotionInventoryTitle")); + String pathInventoryM = ChatColor.stripColor(pathInventory); + if(ChatColor.stripColor(event.getView().getTitle()).equals(pathInventoryM)){ + if(event.getCurrentItem() == null){ + event.setCancelled(true); + return; + } + if((event.getSlotType() == null)){ + event.setCancelled(true); + return; + }else{ + Player jugador = (Player) event.getWhoClicked(); + event.setCancelled(true); + if(event.getClickedInventory().equals(jugador.getOpenInventory().getTopInventory())) { + Partida partida = plugin.getPartidaJugador(jugador.getName()); + if(partida != null) { + Jugador j = partida.getJugador(jugador.getName()); + if(j.estaCoronandoPeon()) { + int slot = event.getSlot(); + if(slot == 1 || slot == 3 || slot == 5 || slot == 7) { + coronacion(partida,j,slot,config,plugin); + } + } + } + } + } + } + } + + public static void coronacion(Partida partida,Jugador j,int slot,FileConfiguration config,MineChess plugin) { + Pieza seleccionada = j.getPiezaSeleccionada(); + Location l = partida.getLocationDesdePieza(seleccionada).clone(); + int[] posPieza = partida.getPosicionDesdeCoordenada(l); + l.setY(partida.getEsquina1().getY()); + l.add(0,1,0); + String prefix = ChatColor.translateAlternateColorCodes('&', config.getString("Messages.prefix")); + ArrayList jugadores = partida.getJugadores(); + if(slot == 1) { + //torre + Tablero.eliminarPieza(l); + Location l1h = l.clone().add(0.5,0,0.5); + Tablero.eliminarPiezaHolograma(plugin, l1h,config); + + Tablero.crearPieza(l, "torre", seleccionada.getColor()); + Location l2h = l.clone().add(0.5,4.7,0.5); + Tablero.crearPiezaHolograma(plugin, l2h, "torre", config); + + Pieza nuevaPieza = new Pieza(seleccionada.getId(),"torre",seleccionada.getColor(),true,false); + partida.reemplazarPieza(posPieza, nuevaPieza); + for(Jugador jug : jugadores) { + jug.getJugador().sendMessage(prefix+ChatColor.translateAlternateColorCodes('&', config.getString("Messages.promotion") + .replace("%player%", j.getJugador().getName()).replace("%piece%", config.getString("Messages.pieceRook")))); + } + }else if(slot == 3) { + //caballo + Tablero.eliminarPieza(l); + Location l1h = l.clone().add(0.5,0,0.5); + Tablero.eliminarPiezaHolograma(plugin, l1h,config); + + Tablero.crearPieza(l, "caballo", seleccionada.getColor()); + Location l2h = l.clone().add(0.5,4.7,0.5); + Tablero.crearPiezaHolograma(plugin, l2h, "caballo", config); + + Pieza nuevaPieza = new Pieza(seleccionada.getId(),"caballo",seleccionada.getColor(),true,false); + partida.reemplazarPieza(posPieza, nuevaPieza); + for(Jugador jug : jugadores) { + jug.getJugador().sendMessage(prefix+ChatColor.translateAlternateColorCodes('&', config.getString("Messages.promotion") + .replace("%player%", j.getJugador().getName()).replace("%piece%", config.getString("Messages.pieceKnight")))); + } + }else if(slot == 5) { + //alfil + Tablero.eliminarPieza(l); + Location l1h = l.clone().add(0.5,0,0.5); + Tablero.eliminarPiezaHolograma(plugin, l1h,config); + + Tablero.crearPieza(l, "alfil", seleccionada.getColor()); + Location l2h = l.clone().add(0.5,4.7,0.5); + Tablero.crearPiezaHolograma(plugin, l2h, "alfil", config); + + Pieza nuevaPieza = new Pieza(seleccionada.getId(),"alfil",seleccionada.getColor(),true,false); + partida.reemplazarPieza(posPieza, nuevaPieza); + for(Jugador jug : jugadores) { + jug.getJugador().sendMessage(prefix+ChatColor.translateAlternateColorCodes('&', config.getString("Messages.promotion") + .replace("%player%", j.getJugador().getName()).replace("%piece%", config.getString("Messages.pieceBishop")))); + } + }else if(slot == 7) { + //reina + Tablero.eliminarPieza(l); + Location l1h = l.clone().add(0.5,0,0.5); + Tablero.eliminarPiezaHolograma(plugin, l1h,config); + + Tablero.crearPieza(l, "reina", seleccionada.getColor()); + Location l2h = l.clone().add(0.5,4.7,0.5); + Tablero.crearPiezaHolograma(plugin, l2h, "reina", config); + + Pieza nuevaPieza = new Pieza(seleccionada.getId(),"reina",seleccionada.getColor(),true,false); + partida.reemplazarPieza(posPieza, nuevaPieza); + for(Jugador jug : jugadores) { + jug.getJugador().sendMessage(prefix+ChatColor.translateAlternateColorCodes('&', config.getString("Messages.promotion") + .replace("%player%", j.getJugador().getName()).replace("%piece%", config.getString("Messages.pieceQueen")))); + } + } + + String[] separados = config.getString("Config.soundPromotion").split(";"); + try { + Sound sound = Sound.valueOf(separados[0]); + for(Jugador jug : jugadores) { + jug.getJugador().playSound(jug.getJugador().getLocation(), sound, Float.valueOf(separados[1]), Float.valueOf(separados[2])); + } + }catch(Exception e) { + Bukkit.getConsoleSender().sendMessage(prefix+ChatColor.translateAlternateColorCodes('&',"&7Sound Name: &c"+separados[0]+" &7is not valid. Change it in the config!")); + } + + j.setCoronandoPeon(false); + j.getJugador().closeInventory(); + + j.setPiezaSeleccionada(null); + + PartidaManager.cambiarTurno(partida,config,plugin); + } +} diff --git a/src/mc/ajneb97/managers/PartidaListener.java b/src/mc/ajneb97/managers/PartidaListener.java new file mode 100644 index 0000000..b21e19e --- /dev/null +++ b/src/mc/ajneb97/managers/PartidaListener.java @@ -0,0 +1,520 @@ +package mc.ajneb97.managers; + +import java.util.ArrayList; +import java.util.List; + +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.block.Block; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.block.Action; +import org.bukkit.event.block.BlockBreakEvent; +import org.bukkit.event.block.BlockPlaceEvent; +import org.bukkit.event.entity.EntityDamageEvent; +import org.bukkit.event.entity.FoodLevelChangeEvent; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.inventory.InventoryCloseEvent; +import org.bukkit.event.inventory.InventoryType; +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.inventory.ItemStack; + +import mc.ajneb97.JugadorDatos; +import mc.ajneb97.MineChess; +import mc.ajneb97.juego.Ajedrez; +import mc.ajneb97.juego.Estado; +import mc.ajneb97.juego.Jugador; +import mc.ajneb97.juego.MovimientoPosible; +import mc.ajneb97.juego.Partida; +import mc.ajneb97.juego.Pieza; +import mc.ajneb97.mysql.MySQL; +import mc.ajneb97.mysql.MySQLJugadorCallback; +import mc.ajneb97.otros.Utilidades; + +public class PartidaListener implements Listener{ + + private MineChess plugin; + public PartidaListener(MineChess plugin) { + this.plugin = plugin; + } + + //Para seleccionar una pieza a mover se debe hacer click izquierdo mirando a una pieza. Aqui detectar + //de alguna manera que pieza es + + @EventHandler + public void alSalir(PlayerQuitEvent event) { + Player jugador = event.getPlayer(); + Partida partida = plugin.getPartidaJugador(jugador.getName()); + FileConfiguration config = plugin.getConfig(); + if(partida != null) { + Jugador j = partida.getJugador(jugador.getName()); + if(j.esEspectador()) { + PartidaManager.espectadorSale(partida, jugador,plugin); + }else { + if(partida.getEstado().equals(Estado.JUGANDO)) { + JugadorDatos jDatos = plugin.getJugador(j.getJugador().getName()); + if(jDatos == null) { + jDatos = new JugadorDatos(j.getJugador().getName(), j.getJugador().getUniqueId().toString(),0,0,0,0); + plugin.agregarJugadorDatos(jDatos); + } + jDatos.aumentarLoses(config,plugin); + } + PartidaManager.jugadorSale(partida, jugador,false,plugin,false); + } + } + } + + @EventHandler + public void alEntrar(PlayerJoinEvent event) { + final Player jugador = event.getPlayer(); + FileConfiguration config = plugin.getConfig(); + if(MySQL.isEnabled(config)) { + MySQL.getJugador(jugador.getName(), plugin, new MySQLJugadorCallback() { + @Override + public void alTerminar(JugadorDatos j) { + plugin.removerJugadorDatos(jugador.getName()); + if(j != null) { + plugin.agregarJugadorDatos(j); + }else { + //Lo crea si no existe + plugin.crearJugadorDatosSQL(jugador.getName(), jugador.getUniqueId().toString()); + plugin.agregarJugadorDatos(new JugadorDatos(jugador.getName(),jugador.getUniqueId().toString(),0,0,0,0)); + } + } + }); + } + } + + @EventHandler + public void clickearItemSalir(PlayerInteractEvent event) { + Player jugador = event.getPlayer(); + Partida partida = plugin.getPartidaJugador(jugador.getName()); + if(partida != null) { + Jugador j = partida.getJugador(jugador.getName()); + if(event.getAction().equals(Action.RIGHT_CLICK_AIR) || event.getAction().equals(Action.RIGHT_CLICK_BLOCK)) { + if(event.getItem() != null) { + FileConfiguration config = plugin.getConfig(); + ItemStack item = Utilidades.crearItem(config, "Config.leave_item"); + if(event.getItem().isSimilar(item)) { + event.setCancelled(true); + if(j.esEspectador()) { + PartidaManager.espectadorSale(partida, jugador,plugin); + }else { + if(partida.getEstado().equals(Estado.JUGANDO)) { + JugadorDatos jDatos = plugin.getJugador(j.getJugador().getName()); + if(jDatos == null) { + jDatos = new JugadorDatos(j.getJugador().getName(), j.getJugador().getUniqueId().toString(),0,0,0,0); + plugin.agregarJugadorDatos(jDatos); + } + jDatos.aumentarLoses(config,plugin); + } + PartidaManager.jugadorSale(partida, jugador,false,plugin,false); + } + + } + } + } + } + } + + @EventHandler + public void clickearItemPieza(PlayerInteractEvent event) { + Player jugador = event.getPlayer(); + Partida partida = plugin.getPartidaJugador(jugador.getName()); + if(partida != null) { + if(event.getItem() != null) { + FileConfiguration config = plugin.getConfig(); + int clickDistance = config.getInt("Config.click_distance"); + ItemStack item = Utilidades.crearItem(config, "Config.select_item"); + if(event.getItem().isSimilar(item)) { + event.setCancelled(true); + if(event.getAction().equals(Action.RIGHT_CLICK_AIR) || event.getAction().equals(Action.RIGHT_CLICK_BLOCK)) { + //Mover + + Block b = jugador.getTargetBlock(null, clickDistance); + + if(b != null) { + Pieza p = partida.getPiezaDesdeCoordenada(b.getLocation()); + Jugador j = partida.getJugador(jugador.getName()); + if(p == null || !p.getColor().equals(j.getColor())) { + Pieza piezaS = j.getPiezaSeleccionada(); + if(piezaS != null) { + int[] posPieza = partida.getPosicion(piezaS); + ArrayList movimientosPosibles = j.getMovimientos(); + if(movimientosPosibles != null) { + for(MovimientoPosible l : movimientosPosibles) { + if(l.getLocation().getBlockX() == b.getLocation().getBlockX() && l.getLocation().getBlockZ() == b.getLocation().getBlockZ()) { + //MOVER + Location locTo = b.getLocation(); + int[] posPiezaNueva = partida.getPosicionDesdeCoordenada(locTo); + j.setEnJaque(false); + PartidaManager.moverPieza(plugin, partida, j, posPieza, posPiezaNueva, locTo, false); + return; + } + } + } + } + }else if(p != null && p.getColor().equals(j.getColor())) { + Pieza piezaS = j.getPiezaSeleccionada(); + if(piezaS != null && piezaS.getTipo().equals("rey")) { + int[] posPieza = partida.getPosicion(piezaS); + ArrayList movimientosPosibles = j.getMovimientos(); + if(movimientosPosibles != null) { + for(MovimientoPosible l : movimientosPosibles) { + if(l.getLocation().getBlockX() == b.getLocation().getBlockX() && l.getLocation().getBlockZ() == b.getLocation().getBlockZ()) { + //ENROQUE + Location locTo = b.getLocation(); + int[] posPiezaNueva = partida.getPosicionDesdeCoordenada(locTo); + PartidaManager.enroque(plugin, partida, j, posPieza, posPiezaNueva, locTo); + return; + } + } + } + } + } + } + }else if(event.getAction().equals(Action.LEFT_CLICK_AIR) || event.getAction().equals(Action.LEFT_CLICK_BLOCK)) { + //Seleccionar + Block b = jugador.getTargetBlock(null, clickDistance); + String prefix = ChatColor.translateAlternateColorCodes('&', config.getString("Messages.prefix")); + if(b != null) { + Pieza p = partida.getPiezaDesdeCoordenada(b.getLocation()); + if(p != null) { + Jugador j = partida.getJugador(jugador.getName()); + if(p.getColor().equals(j.getColor())) { + if(partida.getTurno() != null && partida.getTurno().getJugador().getName().equals(jugador.getName())) { + if(j.getPiezaSeleccionada() == null || j.getPiezaSeleccionada().getId() != p.getId()) { + j.setPiezaSeleccionada(p); + j.setCeldaObservada(null); + CooldownParticulaPieza cooldown = new CooldownParticulaPieza(plugin); + cooldown.cooldownParticulaSeleccionada(j,partida,p); + + double y = partida.getEsquina1().getY(); + Location nueva = b.getLocation().clone().add(0.5,0,0.5); + nueva.setY(y+1.35); + int[] posPieza = partida.getPosicion(p); + ArrayList movimientosPosibles = null; + if(partida.getTurno().enJaque()) { + movimientosPosibles = Ajedrez.getMovimientosPosibles(partida, partida.getTablero(), posPieza[0], posPieza[1],true); + }else { + movimientosPosibles = Ajedrez.getMovimientosPosibles(partida, partida.getTablero(), posPieza[0], posPieza[1],false); + } + ArrayList movimientosAEliminar = new ArrayList(); + Location locationRey = partida.getLocationRey(partida.getTurno().getColor()); + if(movimientosPosibles != null) { +// jugador.sendMessage("movimientos posibles: "+movimientosPosibles.size()); + for(MovimientoPosible l : movimientosPosibles) { + if(p.getTipo().equals("rey")) { + locationRey = l.getLocation(); + } + //jugador.sendMessage("probando por posicion posible"); + //Verificar por cada location, si la pieza en esa posicion evita que se coman al rey + //l es la nueva posicion de la pieza + Pieza[][] tablero = partida.getTablero().clone(); + int[] cFinal = partida.getPosicionDesdeCoordenada(l.getLocation()).clone(); + + Pieza aux = partida.getPiezaDesdeCoordenada(b.getLocation()); + Pieza nuevaPieza = new Pieza(aux.getId(),aux.getTipo(),aux.getColor(),aux.seHaMovido(),aux.isEnPassant()); + Pieza auxComida = partida.getPiezaDesdeCoordenada(l.getLocation()); + Pieza piezaComida = null; + if(auxComida != null) { + piezaComida = new Pieza(auxComida.getId(),auxComida.getTipo(),auxComida.getColor(),auxComida.seHaMovido(),auxComida.isEnPassant()); + } + tablero[cFinal[1]][cFinal[0]] = nuevaPieza; + tablero[posPieza[1]][posPieza[0]] = null; +// jugador.sendMessage("Pos Inicial: "+posPieza[1]+","+posPieza[0]); +// jugador.sendMessage("Pos Nueva: "+cFinal[1]+","+cFinal[0]); + for(int i=0;i movimientosPosiblesPieza = Ajedrez.getMovimientosPosibles(partida, tablero, i, c, false); + if(movimientosPosiblesPieza != null) { + for(MovimientoPosible l2 : movimientosPosiblesPieza) { + if(l2.getLocation().getWorld().getName().equals(locationRey.getWorld().getName()) && + l2.getLocation().getBlockX() == locationRey.getBlockX() && l2.getLocation().getBlockZ() == locationRey.getBlockZ()) { + //Se pueden comer al rey asi que habria que eliminar la Location l de la lista + //aun puede haber otra posicion que si sirva + //jugador.sendMessage("se elimina posicion ya que "+tablero[c][i].getTipo()+" puede comerse al rey"); + movimientosAEliminar.add(l); + break; + } + } + } + } + } + } + //Volver a poner la pieza en su lugar original + Pieza aux2 = new Pieza(nuevaPieza.getId(),nuevaPieza.getTipo(),nuevaPieza.getColor(),nuevaPieza.seHaMovido(),nuevaPieza.isEnPassant()); + tablero[posPieza[1]][posPieza[0]] = aux2; + tablero[cFinal[1]][cFinal[0]] = piezaComida; + } + } + movimientosPosibles.removeAll(movimientosAEliminar); + + j.setMovimientos(movimientosPosibles); + + CooldownParticulaPieza cooldown2 = new CooldownParticulaPieza(plugin); + cooldown2.cooldownParticulaMovimientosPosibles(j, partida, p, movimientosPosibles); + + j.getJugador().sendMessage(prefix+ChatColor.translateAlternateColorCodes('&', config.getString("Messages.pieceSelected").replace("%piece%", PartidaManager.getNombrePieza(config, p.getTipo())))); + String[] separados = config.getString("Config.soundSelectPiece").split(";"); + try { + Sound sound = Sound.valueOf(separados[0]); + j.getJugador().playSound(j.getJugador().getLocation(), sound, Float.valueOf(separados[1]), Float.valueOf(separados[2])); + }catch(Exception e) { + Bukkit.getConsoleSender().sendMessage(prefix+ChatColor.translateAlternateColorCodes('&',"&7Sound Name: &c"+separados[0]+" &7is not valid. Change it in the config!")); + } + } + + + }else { + jugador.sendMessage(prefix+ChatColor.translateAlternateColorCodes('&', config.getString("Messages.notYourTurn"))); + } + }else { + jugador.sendMessage(prefix+ChatColor.translateAlternateColorCodes('&', config.getString("Messages.notYourPiece"))); + } + + } + } + } + } + } + } + } + + @EventHandler + //Para evitar lag, que en la clase Jugador se guarden los posibles movimientos de la pieza seleccionada + public void mirarPieza(PlayerMoveEvent event) { + Player jugador = event.getPlayer(); + Partida partida = plugin.getPartidaJugador(jugador.getName()); + if(partida != null) { + FileConfiguration config = plugin.getConfig(); + int clickDistance = config.getInt("Config.click_distance"); + Block b = jugador.getTargetBlock(null, clickDistance); + if(b != null) { + Jugador j = partida.getJugador(jugador.getName()); + if(partida.getTurno() != null && partida.getTurno().equals(j)) { + Pieza p = partida.getPiezaDesdeCoordenada(b.getLocation()); + if(p != null) { + Pieza piezaS = j.getPiezaSeleccionada(); + if(!p.getColor().equals(j.getColor()) && piezaS != null) { + int[] posPieza = partida.getPosicion(piezaS); + if(j.getCeldaObservada() == null || (posPieza[0] != j.getCeldaObservada()[0] && posPieza[1] != j.getCeldaObservada()[1])) { + //ArrayList movimientosPosibles = Ajedrez.getMovimientosPosibles(partida, partida.getTablero(), posPieza[0], posPieza[1]); + ArrayList movimientosPosibles = j.getMovimientos(); + if(movimientosPosibles != null) { + for(MovimientoPosible l : movimientosPosibles) { + if(l.getLocation().getBlockX() == b.getLocation().getBlockX() && l.getLocation().getBlockZ() == b.getLocation().getBlockZ()) { + j.setCeldaObservada(posPieza); + CooldownParticulaPieza c = new CooldownParticulaPieza(plugin); + c.cooldownParticulaObservarMovimiento(j, partida, l.getLocation()); + return; + } + } + } + + return; + }else { + j.setCeldaObservada(null); + return; + } + } + if(p.getColor().equals(j.getColor()) && piezaS != null) { + if(p.getTipo().equals("torre") && piezaS.getTipo().equals("rey")) { + int[] posPieza = partida.getPosicion(piezaS); + if(j.getCeldaObservada() == null || (posPieza[0] != j.getCeldaObservada()[0] && posPieza[1] != j.getCeldaObservada()[1])) { + //ArrayList movimientosPosibles = Ajedrez.getMovimientosPosibles(partida, partida.getTablero(), posPieza[0], posPieza[1]); + ArrayList movimientosPosibles = j.getMovimientos(); + if(movimientosPosibles != null) { + for(MovimientoPosible l : movimientosPosibles) { + if(l.getLocation().getBlockX() == b.getLocation().getBlockX() && l.getLocation().getBlockZ() == b.getLocation().getBlockZ()) { + j.setCeldaObservada(posPieza); + CooldownParticulaPieza c = new CooldownParticulaPieza(plugin); + c.cooldownParticulaObservarMovimiento(j, partida, l.getLocation()); + return; + } + } + } + }else { + return; + } + } + + } + if(!p.getColor().equals(j.getColor())){ + return; + } + if(j.getPiezaObservada() == null || j.getPiezaObservada().getId() != p.getId()) { + j.setPiezaObservada(p); + CooldownParticulaPieza c = new CooldownParticulaPieza(plugin); + c.cooldownParticula(j,partida,p); + } + }else { + j.setPiezaObservada(null); + Pieza piezaS = j.getPiezaSeleccionada(); + if(piezaS != null) { + int[] posPieza = partida.getPosicion(piezaS); + if(j.getCeldaObservada() == null || (posPieza[0] != j.getCeldaObservada()[0] && posPieza[1] != j.getCeldaObservada()[1])) { + //ArrayList movimientosPosibles = Ajedrez.getMovimientosPosibles(partida, partida.getTablero(), posPieza[0], posPieza[1]); + ArrayList movimientosPosibles = j.getMovimientos(); + if(movimientosPosibles != null) { + for(MovimientoPosible l : movimientosPosibles) { + if(l.getLocation().getBlockX() == b.getLocation().getBlockX() && l.getLocation().getBlockZ() == b.getLocation().getBlockZ()) { + j.setCeldaObservada(posPieza); + CooldownParticulaPieza c = new CooldownParticulaPieza(plugin); + c.cooldownParticulaObservarMovimiento(j, partida, l.getLocation()); + return; + } + } + } + + return; + }else { + j.setCeldaObservada(null); + return; + } + + } + j.setCeldaObservada(null); + } + }else { + j.setCeldaObservada(null); + } + } + } + } + + @EventHandler + public void alUsarComando(PlayerCommandPreprocessEvent event) { + String comando = event.getMessage().toLowerCase(); + Player jugador = event.getPlayer(); + Partida partida = plugin.getPartidaJugador(jugador.getName()); + if(partida != null && !jugador.isOp() && !jugador.hasPermission("chess.admin")) { + FileConfiguration config = plugin.getConfig(); + List comandos = config.getStringList("Config.commands_whitelist"); + for(int i=0;i jugadores = partida.getJugadores(); + for(int i=0;i jugadores = partida.getJugadores(); + for(int i=0;i= 5) { + partida.getJugador1().setColor("n"); + partida.getJugador2().setColor("b"); + partida.setTurno(partida.getJugador2()); + }else { + partida.getJugador1().setColor("b"); + partida.getJugador2().setColor("n"); + partida.setTurno(partida.getJugador1()); + } + + darItems(partida,plugin.getConfig()); + + ArrayList jugadores = partida.getJugadores(); + for(int i=0;i jugadores = partida.getJugadores(); + for(int i=0;i jugadores = partida.getJugadores(); + for(Jugador j : jugadores) { + if(!j.esEspectador()) { + Player p = j.getJugador(); + if(j.getColor().equals("b")) { + darEquipamientoJugador(p,16777215); + }else { + darEquipamientoJugador(p,0); + } + + ItemStack item = Utilidades.crearItem(config, "Config.select_item"); + p.getInventory().setItem(0, item); + } + } + } + + public static void darEquipamientoJugador(Player jugador,int color) { + ItemStack item = new ItemStack(Material.LEATHER_HELMET,1); + LeatherArmorMeta meta = (LeatherArmorMeta) item.getItemMeta(); + meta.setColor(Color.fromRGB(color)); + item.setItemMeta(meta); + jugador.getInventory().setHelmet(item); + + item = new ItemStack(Material.LEATHER_CHESTPLATE,1); + meta = (LeatherArmorMeta) item.getItemMeta(); + meta.setColor(Color.fromRGB(color)); + item.setItemMeta(meta); + jugador.getInventory().setChestplate(item); + + item = new ItemStack(Material.LEATHER_LEGGINGS,1); + meta = (LeatherArmorMeta) item.getItemMeta(); + meta.setColor(Color.fromRGB(color)); + item.setItemMeta(meta); + jugador.getInventory().setLeggings(item); + + item = new ItemStack(Material.LEATHER_BOOTS,1); + meta = (LeatherArmorMeta) item.getItemMeta(); + meta.setColor(Color.fromRGB(color)); + item.setItemMeta(meta); + jugador.getInventory().setBoots(item); + } + + public static void lanzarFuegos(Jugador j) { + Firework fw = (Firework) j.getJugador().getWorld().spawnEntity(j.getJugador().getLocation(), EntityType.FIREWORK); + FireworkMeta fwm = fw.getFireworkMeta(); + Type type = Type.BALL; + Color c1 = Color.RED; + Color c2 = Color.AQUA; + FireworkEffect efecto = FireworkEffect.builder().withColor(c1).withFade(c2).with(type).build(); + fwm.addEffect(efecto); + fwm.setPower(2); + fw.setFireworkMeta(fwm); + } + + public static void iniciarFaseFinalizacion(Partida partida,MineChess plugin,Jugador ganador) { + partida.setEstado(Estado.TERMINANDO); + FileConfiguration config = plugin.getConfig(); + int tiempoEnTerminar = partida.getTiempoMaximo()-partida.getTiempo(); + partida.setTiempoEnTerminar(tiempoEnTerminar); + + List msg = null; + if(ganador == null) { + //empate + msg = config.getStringList("Messages.gameFinishedTie"); + }else { + msg = config.getStringList("Messages.gameFinished"); + } + ArrayList jugadores = partida.getJugadores(); + for(Jugador j : jugadores) { + if(ganador == null) { + for(int i=0;i= minimumTime) { + List commands = config.getStringList("Config.winners_command_rewards"); + ejecutarComandosRewards(commands,j); + } + }else if(ganador != null && !j.equals(ganador)){ + if(tiempoEnTerminar >= minimumTime) { + List commands = config.getStringList("Config.losers_command_rewards"); + ejecutarComandosRewards(commands,j); + } + } + } + } + + } + + int time = Integer.valueOf(config.getString("Config.arena_ending_phase_cooldown")); + CooldownManager c = new CooldownManager(plugin); + c.cooldownFaseFinalizacion(partida,time,ganador); + } + + public static void ejecutarComandosRewards(List commands,Jugador j) { + CommandSender console = Bukkit.getServer().getConsoleSender(); + for(int i=0;i jugadores = partida.getJugadores(); + + FileConfiguration config = plugin.getConfig(); + for(Jugador j : jugadores) { + boolean esJugadorGanador = false; + Player jugador = j.getJugador(); + if(ganador != null) { + if(ganador.getJugador().getName().equals(jugador.getName()) && !cerrandoServer) { + esJugadorGanador = true; + } + } + + if(j.esEspectador()) { + espectadorSale(partida, j.getJugador(),plugin); + }else { + jugadorSale(partida, j.getJugador(),true,plugin,cerrandoServer); + } + + if(!j.esEspectador()) { + if(config.getString("Config.rewards_executed_after_teleport").equals("true")) { + int tiempoEnTerminar = partida.getTiempoEnTerminar(); + int minimumTime = Integer.valueOf(config.getString("Config.minimum_time_for_rewards")); + if(esJugadorGanador) { + if(tiempoEnTerminar >= minimumTime) { + List commands = config.getStringList("Config.winners_command_rewards"); + ejecutarComandosRewards(commands,j); + } + }else { + if(tiempoEnTerminar >= minimumTime) { + List commands = config.getStringList("Config.losers_command_rewards"); + ejecutarComandosRewards(commands,j); + } + } + } + } + + + } + Tablero.eliminarPiezas(partida.getEsquina1()); + Tablero.eliminarPiezasHologramas(plugin, partida.getEsquina1(),plugin.getConfig(),cerrandoServer); + Tablero.crearPiezas(partida.getEsquina1()); + partida.reiniciarPiezas(); + partida.setTurno(null); + + partida.setEstado(Estado.ESPERANDO); + } + + @SuppressWarnings("deprecation") + public static void moverPieza(MineChess plugin, Partida partida,Jugador jugador,int[] posPiezaSeleccionada,int[] posNueva,Location locTo,boolean aleatorio) { + Pieza pieza = jugador.getPiezaSeleccionada(); + Location lAntes = partida.getLocationDesdePieza(pieza); + //Bukkit.getConsoleSender().sendMessage("se mueve pieza desde "+posPiezaSeleccionada[0]+" "+posPiezaSeleccionada[1]+" hasta "+posNueva[0]+" "+posNueva[1]); + Location l1 = locTo.clone(); + l1.setY(partida.getEsquina1().getY()); + l1.add(0,1,0); + + FileConfiguration config = plugin.getConfig(); + Pieza piezaCapturada = partida.getPiezaDesdeCoordenada(l1); + + + + boolean esCapturada = false; + Player jugadorContrincante = null; + if(partida.getJugador1().equals(jugador)) { + jugadorContrincante = partida.getJugador2().getJugador(); + }else { + jugadorContrincante = partida.getJugador1().getJugador(); + } + String piezaContrincante = ""; + if(piezaCapturada != null) { + esCapturada = true; + piezaContrincante = getNombrePieza(config,piezaCapturada.getTipo()); + capturaPieza(partida,jugador,config,piezaCapturada.getTipo(),l1,jugadorContrincante); + }else { + //En-passant + //Si se come en diagonal y no hay pieza significa que es en-passant + if(pieza.getTipo().equals("peon")) { + if(pieza.getColor().equals("b")) { + if(posPiezaSeleccionada[1]+1 == posNueva[1] && posPiezaSeleccionada[0] != posNueva[0]) { + esCapturada = true; + piezaContrincante = getNombrePieza(config,"peon"); + Location l3 = l1.clone().add(0,0,-3); + Tablero.eliminarPieza(l3); + Location l3h = l3.clone().add(0.5,0,0.5); + Tablero.eliminarPiezaHolograma(plugin, l3h,config); + capturaPieza(partida,jugador,config,"peon",l3,jugadorContrincante); + partida.reemplazarPieza(partida.getPosicionDesdeCoordenada(l3), null); + } + }else { + if(posPiezaSeleccionada[1]-1 == posNueva[1] && posPiezaSeleccionada[0] != posNueva[0]) { + esCapturada = true; + piezaContrincante = getNombrePieza(config,"peon"); + Location l3 = l1.clone().add(0,0,3); + Tablero.eliminarPieza(l3); + Location l3h = l3.clone().add(0.5,0,0.5); + Tablero.eliminarPiezaHolograma(plugin, l3h,config); + capturaPieza(partida,jugador,config,"peon",l3,jugadorContrincante); + partida.reemplazarPieza(partida.getPosicionDesdeCoordenada(l3), null); + } + } + } + } + + Tablero.eliminarPieza(l1); + Location l1h = l1.clone().add(0.5,0,0.5); + Tablero.eliminarPiezaHolograma(plugin, l1h,config); + + Tablero.crearPieza(l1, pieza.getTipo(), pieza.getColor()); + Location l2h = l1.clone().add(0.5,3,0.5); + if(!pieza.getTipo().equals("peon")) { + l2h.add(0,1.7,0); + } + Tablero.crearPiezaHolograma(plugin, l2h, pieza.getTipo(), config); + + Tablero.eliminarPieza(lAntes.clone().add(0,1,0)); + Location lAntesh = lAntes.clone().add(0.5,0,0.5); + Tablero.eliminarPiezaHolograma(plugin, lAntesh,config); + + //partida.mostrarTablero(); + //Bukkit.getConsoleSender().sendMessage(""); + + //en-passant (mover las 2 casillas) +// Bukkit.getConsoleSender().sendMessage("MOVIENDO PIEZA: "+pieza.getTipo()+" "+pieza.getColor()+" a "+posNueva[0]+","+posNueva[1]); + boolean isEnPassant = false; + if(piezaCapturada == null) { + if(pieza.getTipo().equals("peon") && pieza.getColor().equals("b")) { + if(posNueva[1] == 3 && posPiezaSeleccionada[1] == 1) { + pieza.setEnPassant(true); + isEnPassant = true; +// Bukkit.getConsoleSender().sendMessage("SETEANDO EN PASSANT"); + } + }else if(pieza.getTipo().equals("peon") && pieza.getColor().equals("n")) { + if(posNueva[1] == 4 && posPiezaSeleccionada[1] == 6) { + pieza.setEnPassant(true); + isEnPassant = true; +// Bukkit.getConsoleSender().sendMessage("SETEANDO EN PASSANT"); + } + } + } + partida.moverPieza(posPiezaSeleccionada, posNueva,isEnPassant); + //partida.mostrarTablero(); + //Bukkit.getConsoleSender().sendMessage(""); + + int coord2 = posNueva[1]+1; + String coord1 = getCoord1(posNueva[0]); + String coordsFinal = coord1+coord2; + + String prefix = ChatColor.translateAlternateColorCodes('&', config.getString("Messages.prefix")); + ArrayList jugadores = partida.getJugadores(); + String nombrePieza = getNombrePieza(config,pieza.getTipo()); + for(Jugador j : jugadores) { + if(esCapturada) { + j.getJugador().sendMessage(prefix+ChatColor.translateAlternateColorCodes('&', config.getString("Messages.pieceCaptured") + .replace("%player%", jugador.getJugador().getName()).replace("%piece%", nombrePieza).replace("%coords%", coordsFinal) + .replace("%player2%", jugadorContrincante.getName()).replace("%player2_piece%", piezaContrincante))); + }else { + j.getJugador().sendMessage(prefix+ChatColor.translateAlternateColorCodes('&', config.getString("Messages.pieceMove") + .replace("%player%", jugador.getJugador().getName()).replace("%piece%", nombrePieza).replace("%coords%", coordsFinal))); + } + } + + if(piezaCapturada == null) { + String[] separados = config.getString("Config.soundMovePiece").split(";"); + try { + Sound sound = Sound.valueOf(separados[0]); + for(Jugador j : jugadores) { + j.getJugador().playSound(j.getJugador().getLocation(), sound, Float.valueOf(separados[1]), Float.valueOf(separados[2])); + } + }catch(Exception e) { + Bukkit.getConsoleSender().sendMessage(prefix+ChatColor.translateAlternateColorCodes('&',"&7Sound Name: &c"+separados[0]+" &7is not valid. Change it in the config!")); + } + } + + + + //coronacion del peon (pawn promotion) + //Bukkit.getConsoleSender().sendMessage(posNueva[1]+""); + if(pieza.getTipo().equals("peon") && pieza.getColor().equals("b") && posNueva[1] == 7) { + //Bukkit.getConsoleSender().sendMessage("coronacion blanca"); + if(piezaCapturada == null || !piezaCapturada.getTipo().equals("rey")) { + jugador.setCoronandoPeon(true); + InventarioCoronacion.crearInventario(jugador, plugin); + if(aleatorio) { + int slot = 0; + Random r = new Random(); + int num = r.nextInt(4); + if(num == 0) { + slot = 1; + }else if(num == 1) { + slot = 3; + }else if(num == 2) { + slot = 5; + }else { + slot = 7; + } + InventarioCoronacion.coronacion(partida,jugador,slot,config,plugin); + } + return; + } + + }else if(pieza.getTipo().equals("peon") && pieza.getColor().equals("n") && posNueva[1] == 0) { + //Bukkit.getConsoleSender().sendMessage("coronacion negra"); + if(piezaCapturada == null || !piezaCapturada.getTipo().equals("rey")) { + jugador.setCoronandoPeon(true); + InventarioCoronacion.crearInventario(jugador, plugin); + if(aleatorio) { + int slot = 0; + Random r = new Random(); + int num = r.nextInt(4); + if(num == 0) { + slot = 1; + }else if(num == 1) { + slot = 3; + }else if(num == 2) { + slot = 5; + }else { + slot = 7; + } + InventarioCoronacion.coronacion(partida,jugador,slot,config,plugin); + } + return; + } + } + + jugador.setPiezaSeleccionada(null); + + if(piezaCapturada != null && piezaCapturada.getTipo().equals("rey")) { + //Se termina la partida + iniciarFaseFinalizacion(partida,plugin,jugador); + return; + } + +// Bukkit.getConsoleSender().sendMessage("en passant: "+p2.isEnPassant()); + + cambiarTurno(partida,config,plugin); + } + + public static boolean comprobarCheck(Partida partida) { + Jugador turno = partida.getTurno(); + Location rey = partida.getLocationRey(turno.getColor()); + + Pieza[][] tablero = partida.getTablero(); + for(int i=0;i movimientosPosibles = Ajedrez.getMovimientosPosibles(partida, tablero, i, c, false); + if(movimientosPosibles != null) { + for(MovimientoPosible l : movimientosPosibles) { + if(l.getLocation().getWorld().getName().equals(rey.getWorld().getName()) && + l.getLocation().getBlockX() == rey.getBlockX() && l.getLocation().getBlockZ() == rey.getBlockZ()) { + return true; + } + } + } + } + } + } + return false; + } + + public static void capturaPieza(Partida partida,Jugador jugador,FileConfiguration config,String tipo,Location l,Player jugadorContrincante) { + String prefix = ChatColor.translateAlternateColorCodes('&', config.getString("Messages.prefix")); + aumentarPuntos(tipo,jugador,config); + + //Efecto Captura + if(Bukkit.getVersion().contains("1.8")) { + l.getWorld().playEffect(l, Effect.EXPLOSION_LARGE, 2); + }else { + l.getWorld().spawnParticle(Particle.EXPLOSION_LARGE,l,2); + } + + String[] separados = config.getString("Config.soundCapturePiece").split(";"); + try { + Sound sound = Sound.valueOf(separados[0]); + jugador.getJugador().playSound(jugador.getJugador().getLocation(), sound, Float.valueOf(separados[1]), Float.valueOf(separados[2])); + }catch(Exception e) { + Bukkit.getConsoleSender().sendMessage(prefix+ChatColor.translateAlternateColorCodes('&',"&7Sound Name: &c"+separados[0]+" &7is not valid. Change it in the config!")); + } + + separados = config.getString("Config.soundLosePiece").split(";"); + try { + Sound sound = Sound.valueOf(separados[0]); + jugadorContrincante.playSound(jugadorContrincante.getLocation(), sound, Float.valueOf(separados[1]), Float.valueOf(separados[2])); + }catch(Exception e) { + Bukkit.getConsoleSender().sendMessage(prefix+ChatColor.translateAlternateColorCodes('&',"&7Sound Name: &c"+separados[0]+" &7is not valid. Change it in the config!")); + } + } + + private static String getCoord1(int i) { + if(i==7) { + return "A"; + }else if(i==6) { + return "B"; + }else if(i==5) { + return "C"; + }else if(i==4) { + return "D"; + }else if(i==3) { + return "E"; + }else if(i==2) { + return "F"; + }else if(i==1) { + return "G"; + }else { + return "H"; + } + } + + @SuppressWarnings("deprecation") + public static void enroque(MineChess plugin, Partida partida,Jugador jugador,int[] posPiezaSeleccionada,int[] posNueva,Location locTo) { + Pieza pieza = jugador.getPiezaSeleccionada(); + Location lAntes = partida.getLocationDesdePieza(pieza).clone().add(0,1,0); + //Bukkit.getConsoleSender().sendMessage("enroque "+posPiezaSeleccionada[0]+" "+posPiezaSeleccionada[1]+" hasta "+posNueva[0]+" "+posNueva[1]); + Location l1 = locTo.clone(); + l1.setY(partida.getEsquina1().getY()); + l1.add(0,1,0); + + FileConfiguration config = plugin.getConfig(); + Pieza piezaCapturada = partida.getPiezaDesdeCoordenada(l1); + //Bukkit.getConsoleSender().sendMessage(piezaCapturada.getId()+""); + if(piezaCapturada.getId() == 1 || piezaCapturada.getId() == 17) { + Location lNuevaRey = l1.clone().add(3,0,0); + Location lNuevaTorre = l1.clone().add(6,0,0); + //Bukkit.getConsoleSender().sendMessage("eliminando: "+l1.getBlockX()+" "+l1.getBlockY()+" "+l1.getBlockZ()); + //Bukkit.getConsoleSender().sendMessage("location nueva rey: "+lNuevaRey.getBlockX()+" "+lNuevaRey.getBlockZ()); + //Bukkit.getConsoleSender().sendMessage("location nueva torre: "+lNuevaTorre.getBlockX()+" "+lNuevaTorre.getBlockZ()); + Tablero.eliminarPieza(l1); + Location l1h = l1.clone().add(0.5,0,0.5); + Tablero.eliminarPiezaHolograma(plugin, l1h,config); + + Tablero.eliminarPieza(lAntes); + Location lAntesh = lAntes.clone().add(0.5,0,0.5); + Tablero.eliminarPiezaHolograma(plugin, lAntesh,config); + + Tablero.crearPieza(lNuevaRey, pieza.getTipo(), pieza.getColor()); + Location l2h = lNuevaRey.clone().add(0.5,3,0.5); + if(!pieza.getTipo().equals("peon")) { + l2h.add(0,1.7,0); + } + Tablero.crearPiezaHolograma(plugin, l2h, pieza.getTipo(), config); + + Tablero.crearPieza(lNuevaTorre, piezaCapturada.getTipo(), piezaCapturada.getColor()); + Location l3h = lNuevaTorre.clone().add(0.5,3,0.5); + if(!piezaCapturada.getTipo().equals("peon")) { + l3h.add(0,1.7,0); + } + Tablero.crearPiezaHolograma(plugin, l3h, piezaCapturada.getTipo(), config); + //partida.mostrarTablero(); + //Bukkit.getConsoleSender().sendMessage(""); + int[] posPiezaSeleccionadaNueva = {posPiezaSeleccionada[0]-2,posPiezaSeleccionada[1]}; + partida.moverPieza(posPiezaSeleccionada, posPiezaSeleccionadaNueva,false); + int[] posPiezaCapturadaNueva = {posNueva[0]+2,posNueva[1]}; + partida.moverPieza(posNueva, posPiezaCapturadaNueva,false); + //fpartida.mostrarTablero(); + //Bukkit.getConsoleSender().sendMessage(""); + }else if(piezaCapturada.getId() == 8 || piezaCapturada.getId() == 24) { + Location lNuevaRey = l1.clone().add(-6,0,0); + Location lNuevaTorre = l1.clone().add(-9,0,0); + //Bukkit.getConsoleSender().sendMessage("location nueva rey: "+lNuevaRey.getBlockX()+" "+lNuevaRey.getBlockZ()); + //Bukkit.getConsoleSender().sendMessage("location nueva torre: "+lNuevaTorre.getBlockX()+" "+lNuevaTorre.getBlockZ()); + Tablero.eliminarPieza(l1); + Location l1h = l1.clone().add(0.5,0,0.5); + Tablero.eliminarPiezaHolograma(plugin, l1h,config); + + Tablero.eliminarPieza(lAntes); + Location lAntesh = lAntes.clone().add(0.5,0,0.5); + Tablero.eliminarPiezaHolograma(plugin, lAntesh,config); + + Tablero.crearPieza(lNuevaRey, pieza.getTipo(), pieza.getColor()); + Location l2h = lNuevaRey.clone().add(0.5,3,0.5); + if(!pieza.getTipo().equals("peon")) { + l2h.add(0,1.7,0); + } + Tablero.crearPiezaHolograma(plugin, l2h, pieza.getTipo(), config); + + Tablero.crearPieza(lNuevaTorre, piezaCapturada.getTipo(), piezaCapturada.getColor()); + Location l3h = lNuevaTorre.clone().add(0.5,3,0.5); + if(!piezaCapturada.getTipo().equals("peon")) { + l3h.add(0,1.7,0); + } + Tablero.crearPiezaHolograma(plugin, l3h, piezaCapturada.getTipo(), config); + //partida.mostrarTablero(); + //Bukkit.getConsoleSender().sendMessage(""); + int[] posPiezaSeleccionadaNueva = {posPiezaSeleccionada[0]+2,posPiezaSeleccionada[1]}; + partida.moverPieza(posPiezaSeleccionada, posPiezaSeleccionadaNueva,false); + int[] posPiezaCapturadaNueva = {posNueva[0]-3,posNueva[1]}; + partida.moverPieza(posNueva, posPiezaCapturadaNueva,false); + //partida.mostrarTablero(); + //Bukkit.getConsoleSender().sendMessage(""); + } + + int coord2 = posNueva[1]+1; + String coord1 = getCoord1(posNueva[0]); + String coordsFinal = coord1+coord2; + + String prefix = ChatColor.translateAlternateColorCodes('&', config.getString("Messages.prefix")); + ArrayList jugadores = partida.getJugadores(); + for(Jugador j : jugadores) { + j.getJugador().sendMessage(prefix+ChatColor.translateAlternateColorCodes('&', config.getString("Messages.castling") + .replace("%player%", jugador.getJugador().getName()).replace("%coords%", coordsFinal))); + } + + String[] separados = config.getString("Config.soundCastling").split(";"); + try { + Sound sound = Sound.valueOf(separados[0]); + for(Jugador j : jugadores) { + j.getJugador().playSound(j.getJugador().getLocation(), sound, Float.valueOf(separados[1]), Float.valueOf(separados[2])); + } + }catch(Exception e) { + Bukkit.getConsoleSender().sendMessage(prefix+ChatColor.translateAlternateColorCodes('&',"&7Sound Name: &c"+separados[0]+" &7is not valid. Change it in the config!")); + } + + jugador.setPiezaSeleccionada(null); + + cambiarTurno(partida,config,plugin); + } + + public static String getNombrePieza(FileConfiguration config,String pieza) { + if(pieza.equals("peon")) { + return config.getString("Messages.piecePawn"); + }else if(pieza.equals("torre")) { + return config.getString("Messages.pieceRook"); + }else if(pieza.equals("rey")) { + return config.getString("Messages.pieceKing"); + }else if(pieza.equals("reina")) { + return config.getString("Messages.pieceQueen"); + }else if(pieza.equals("alfil")) { + return config.getString("Messages.pieceBishop"); + }else { + return config.getString("Messages.pieceKnight"); + } + } + + public static void aumentarPuntos(String pieza,Jugador jugador,FileConfiguration config) { + if(pieza.equals("peon")) { + jugador.aumentarPuntos(Integer.valueOf(config.getString("Config.pointsPawn"))); + }else if(pieza.equals("torre")) { + jugador.aumentarPuntos(Integer.valueOf(config.getString("Config.pointsRook"))); + }else if(pieza.equals("rey")) { + jugador.aumentarPuntos(Integer.valueOf(config.getString("Config.pointsKing"))); + }else if(pieza.equals("reina")) { + jugador.aumentarPuntos(Integer.valueOf(config.getString("Config.pointsQueen"))); + }else if(pieza.equals("alfil")) { + jugador.aumentarPuntos(Integer.valueOf(config.getString("Config.pointsBishop"))); + }else { + jugador.aumentarPuntos(Integer.valueOf(config.getString("Config.pointsKnight"))); + } + } + + public static ArrayList getMovimientosPosibles(Partida partida,String color){ + ArrayList movimientosFinales = new ArrayList(); + //int cantidadMovimientos = 0; + for(int x=0;x movimientosAEliminar = new ArrayList(); + ArrayList movimientosPosibles = null; + Pieza p = partida.getTablero()[y][x]; + int[] posPieza = partida.getPosicion(p); + if(partida.getTurno().enJaque()) { + movimientosPosibles = Ajedrez.getMovimientosPosibles(partida, partida.getTablero(), posPieza[0], posPieza[1],true); + }else { + movimientosPosibles = Ajedrez.getMovimientosPosibles(partida, partida.getTablero(), posPieza[0], posPieza[1],false); + } + Location locationRey = partida.getLocationRey(partida.getTurno().getColor()); + + if(movimientosPosibles != null) { + for(MovimientoPosible l : movimientosPosibles) { + if(p.getTipo().equals("rey")) { + locationRey = l.getLocation(); + } + + //En esta parte de aqui hay que hacer la siguiente comprobacion: + //El movimiento del enroque ver la posicion FINAL del rey y ver si queda o no en jaque + //El l.getLocation() seria la posicion de la torre. Comprobar si la location seleccionada + //corresponde a una torre, y el rey esta seleccionado. Luego de esto determinar la nueva + //posicion del rey y la torre + + Pieza[][] tablero = partida.getTablero().clone(); + int[] cFinal = partida.getPosicionDesdeCoordenada(l.getLocation()).clone(); + + Pieza aux = partida.getTablero()[y][x]; + Pieza nuevaPieza = new Pieza(aux.getId(),aux.getTipo(),aux.getColor(),aux.seHaMovido(),aux.isEnPassant()); + Pieza auxComida = partida.getPiezaDesdeCoordenada(l.getLocation()); + Pieza piezaComida = null; + if(auxComida != null) { + piezaComida = new Pieza(auxComida.getId(),auxComida.getTipo(),auxComida.getColor(),auxComida.seHaMovido(),auxComida.isEnPassant()); + } + tablero[cFinal[1]][cFinal[0]] = nuevaPieza; + tablero[posPieza[1]][posPieza[0]] = null; + //jugador.sendMessage("Pos Inicial: "+posPieza[1]+","+posPieza[0]); + //jugador.sendMessage("Pos Nueva: "+cFinal[1]+","+cFinal[0]); + for(int i=0;i movimientosPosiblesPieza = Ajedrez.getMovimientosPosibles(partida, tablero, i, c, false); + if(movimientosPosiblesPieza != null) { + for(MovimientoPosible l2 : movimientosPosiblesPieza) { + if(l2.getLocation().getWorld().getName().equals(locationRey.getWorld().getName()) && + l2.getLocation().getBlockX() == locationRey.getBlockX() && l2.getLocation().getBlockZ() == locationRey.getBlockZ()) { + //Se pueden comer al rey asi que habria que eliminar la Location l de la lista + //aun puede haber otra posicion que si sirva + //jugador.sendMessage("se elimina posicion ya que "+tablero[c][i].getTipo()+" puede comerse al rey"); + movimientosAEliminar.add(l); + break; + } + } + } + } + } + } + //Volver a poner la pieza en su lugar original + Pieza aux2 = new Pieza(nuevaPieza.getId(),nuevaPieza.getTipo(),nuevaPieza.getColor(),nuevaPieza.seHaMovido(),nuevaPieza.isEnPassant()); + tablero[posPieza[1]][posPieza[0]] = aux2; + tablero[cFinal[1]][cFinal[0]] = piezaComida; + } + } + movimientosPosibles.removeAll(movimientosAEliminar); + movimientosFinales.addAll(movimientosPosibles); + //cantidadMovimientos = cantidadMovimientos+movimientosPosibles.size(); + } + } + } + + + + return movimientosFinales; + } + + public static void moverPiezaAleatoria(Partida partida,MineChess plugin) { + Jugador turno = partida.getTurno(); + //Los movimientos posibles de alguna manera deberian guardar de que pieza exactamente es ese movimiento + ArrayList movimientos = PartidaManager.getMovimientosPosibles(partida, turno.getColor()); + Random r = new Random(); + int num = r.nextInt(movimientos.size()); + MovimientoPosible lAleatoria = movimientos.get(num); + int[] posPiezaSeleccionada = partida.getPosicion(lAleatoria.getPieza()); + int[] posNueva = partida.getPosicionDesdeCoordenada(lAleatoria.getLocation()); + //seleccionarle la pieza al jugador + turno.setPiezaSeleccionada(lAleatoria.getPieza()); + + PartidaManager.moverPieza(plugin, partida, turno, posPiezaSeleccionada, posNueva, lAleatoria.getLocation(),true); + } + + public static Partida getPartidaDisponible(MineChess plugin) { + ArrayList partidas = plugin.getPartidas(); + ArrayList disponibles = new ArrayList(); + for(int i=0;i boards = new HashMap<>(); + public ScoreboardAdmin(MineChess plugin){ + this.plugin = plugin; + } + + public void crearScoreboards() { + BukkitScheduler scheduler = Bukkit.getServer().getScheduler(); + taskID = scheduler.scheduleSyncRepeatingTask(plugin, new Runnable() { + public void run() { + for(Player player : Bukkit.getOnlinePlayers()) { + actualizarScoreboard(player); + } + } + },0, 20L); + } + + protected void actualizarScoreboard(final Player player) { + FileConfiguration config = plugin.getConfig(); + Partida partida = plugin.getPartidaJugador(player.getName()); + FastBoard board = boards.get(player.getUniqueId()); + if(partida != null) { + if(board == null) { + board = new FastBoard(player); + board.updateTitle(ChatColor.translateAlternateColorCodes('&',config.getString("Messages.gameScoreboardTitle"))); + boards.put(player.getUniqueId(), board); + } + + List lista = config.getStringList("Messages.gameScoreboardBody"); + Jugador j1 = partida.getJugador1(); + Jugador j2 = partida.getJugador2(); + String nombre1 = ""; + String nombre2 = ""; + int puntos1 = 0; + int puntos2 = 0; + if(j1 != null) { + nombre1 = j1.getJugador().getName(); + puntos1 = j1.getPuntos(); + }else { + nombre1 = config.getString("Messages.gameScoreboardWaitingPlayer"); + } + if(j2 != null) { + nombre2 = j2.getJugador().getName(); + puntos2 = j2.getPuntos(); + }else { + nombre2 = config.getString("Messages.gameScoreboardWaitingPlayer"); + } + for(int i=0;i> 4; + int chunkZ = z >> 4; + if(world.isChunkLoaded(chunkX, chunkZ)) { + Block block = world.getBlockAt(x,y,z); + if(block.getType().name().contains("SIGN")) { + + Sign sign = (Sign) block.getState(); + String estado = ""; + if(partida.estaIniciada() && !partida.getEstado().equals(Estado.TERMINANDO)) { + estado = config.getString("Messages.signStatusIngame"); + }else if(partida.getEstado().equals(Estado.COMENZANDO)) { + estado = config.getString("Messages.signStatusStarting"); + }else if(partida.getEstado().equals(Estado.ESPERANDO)) { + estado = config.getString("Messages.signStatusWaiting"); + }else if(partida.getEstado().equals(Estado.DESACTIVADA)) { + estado = config.getString("Messages.signStatusDisabled"); + }else if(partida.getEstado().equals(Estado.TERMINANDO)) { + estado = config.getString("Messages.signStatusFinishing"); + } + + List lista = config.getStringList("Messages.signFormat"); + for(int i=0;i getJugadores(MineChess plugin){ + ArrayList jugadores = new ArrayList(); + try { + PreparedStatement statement = plugin.getConnection().prepareStatement("SELECT * FROM minechess_data"); + ResultSet resultado = statement.executeQuery(); + while(resultado.next()){ + String uuid = resultado.getString("UUID"); + int wins = resultado.getInt("WINS"); + int loses = resultado.getInt("LOSES"); + int ties = resultado.getInt("TIES"); + long timePlayed = resultado.getLong("PLAYED_TIME"); + String name = resultado.getString("PLAYER_NAME"); + jugadores.add(new JugadorDatos(name,uuid,wins,loses,ties,timePlayed)); + } + } catch (SQLException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return jugadores; + } + + public static void getJugador(final String nombre,final MineChess plugin,final MySQLJugadorCallback callback){ + Bukkit.getScheduler().runTaskAsynchronously(plugin, new Runnable() { + @Override + public void run() { + int wins = 0; + int loses = 0; + int ties = 0; + long timePlayed = 0; + String uuid = ""; + boolean encuentra = false; + try { + PreparedStatement statement = plugin.getConnection().prepareStatement("SELECT * FROM minechess_data WHERE player_name=?"); + statement.setString(1, nombre); + ResultSet resultado = statement.executeQuery(); + if(resultado.next()){ + uuid = resultado.getString("UUID"); + wins = resultado.getInt("WINS"); + loses = resultado.getInt("LOSES"); + ties = resultado.getInt("TIES"); + timePlayed = resultado.getLong("PLAYED_TIME"); + encuentra = true; + } + } catch (SQLException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + if(encuentra) { + final JugadorDatos j = new JugadorDatos(nombre,uuid,wins,loses,ties,timePlayed); + Bukkit.getScheduler().runTask(plugin, new Runnable() { + @Override + public void run() { + callback.alTerminar(j); + } + }); + }else { + Bukkit.getScheduler().runTask(plugin, new Runnable() { + @Override + public void run() { + callback.alTerminar(null); + } + }); + } + } + }); + } + + public static void crearJugador(final MineChess plugin, final String name, final String uuid){ + Bukkit.getScheduler().runTaskAsynchronously(plugin, new Runnable() { + @Override + public void run() { + try{ + PreparedStatement insert = plugin.getConnection() + .prepareStatement("INSERT INTO minechess_data (UUID,PLAYER_NAME,WINS,LOSES,TIES,PLAYED_TIME) VALUE (?,?,?,?,?,?)"); + insert.setString(1, uuid); + insert.setString(2, name); + insert.setInt(3, 0); + insert.setInt(4, 0); + insert.setInt(5, 0); + insert.setLong(6, 0); + insert.executeUpdate(); + } catch (SQLException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + }); + } + + public static void modificarJugador(final MineChess plugin,final JugadorDatos j){ + final String uuid = j.getUUID(); + final String name = j.getPlayer(); + final int wins = j.getWins(); + final int loses = j.getLoses(); + final int ties = j.getTies(); + final long timePlayed = j.getMillisJugados(); + Bukkit.getScheduler().runTaskAsynchronously(plugin, new Runnable() { + @Override + public void run() { + try { + PreparedStatement statement = plugin.getConnection().prepareStatement("UPDATE minechess_data SET player_name=?, wins=?, loses=?, ties=?, played_time=? WHERE (uuid=?)"); + statement.setString(1, name); + statement.setInt(2, wins); + statement.setInt(3, loses); + statement.setInt(4, ties); + statement.setLong(5, timePlayed); + statement.setString(6, uuid); + statement.executeUpdate(); + } catch (SQLException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + }); + } +} diff --git a/src/mc/ajneb97/mysql/MySQLJugadorCallback.java b/src/mc/ajneb97/mysql/MySQLJugadorCallback.java new file mode 100644 index 0000000..a02972a --- /dev/null +++ b/src/mc/ajneb97/mysql/MySQLJugadorCallback.java @@ -0,0 +1,9 @@ +package mc.ajneb97.mysql; + + +import mc.ajneb97.JugadorDatos; + +public interface MySQLJugadorCallback { + + public void alTerminar(JugadorDatos j); +} diff --git a/src/mc/ajneb97/otros/Utilidades.java b/src/mc/ajneb97/otros/Utilidades.java new file mode 100644 index 0000000..5853dbc --- /dev/null +++ b/src/mc/ajneb97/otros/Utilidades.java @@ -0,0 +1,431 @@ +package mc.ajneb97.otros; + +import java.util.List; +import java.util.Random; + +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemFlag; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.PlayerInventory; +import org.bukkit.inventory.meta.ItemMeta; + +import mc.ajneb97.versiones.V1_10; +import mc.ajneb97.versiones.V1_11; +import mc.ajneb97.versiones.V1_12; +import mc.ajneb97.versiones.V1_13; +import mc.ajneb97.versiones.V1_13_R2; +import mc.ajneb97.versiones.V1_14; +import mc.ajneb97.versiones.V1_15; +import mc.ajneb97.versiones.V1_16; +import mc.ajneb97.versiones.V1_16_R2; +import mc.ajneb97.versiones.V1_16_R3; +import mc.ajneb97.versiones.V1_17; +import mc.ajneb97.versiones.V1_8_R1; +import mc.ajneb97.versiones.V1_8_R2; +import mc.ajneb97.versiones.V1_8_R3; +import mc.ajneb97.versiones.V1_9_R1; +import mc.ajneb97.versiones.V1_9_R2; + +public class Utilidades { + + public static int getNumeroAleatorio(int min, int max) { + Random r = new Random(); + int numero = r.nextInt((max - min) + 1) + min; + return numero; + } + + @SuppressWarnings("deprecation") + public static ItemStack crearItem(FileConfiguration config,String path){ + String id = config.getString(path+".item"); + String[] idsplit = new String[2]; + int DataValue = 0; + ItemStack stack = null; + if(id.contains(":")){ + idsplit = id.split(":"); + String stringDataValue = idsplit[1]; + DataValue = Integer.valueOf(stringDataValue); + Material mat = Material.getMaterial(idsplit[0].toUpperCase()); + stack = new ItemStack(mat,1,(short)DataValue); + }else{ + Material mat = Material.getMaterial(id.toUpperCase()); + stack = new ItemStack(mat,1); + } + ItemMeta meta = stack.getItemMeta(); + if(config.contains(path+".name")) { + meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', config.getString(path+".name"))); + } + if(config.contains(path+".lore")) { + List lore = config.getStringList(path+".lore"); + for(int c=0;c= 0 && segundos <= 9) { + segundosMsg = "0"+segundos; + }else { + segundosMsg = segundos+""; + } + + if(minutos >= 0 && minutos <= 9) { + minutosMsg = "0"+minutos; + }else { + minutosMsg = minutos+""; + } + + return minutosMsg+":"+segundosMsg; + } + + public static String getTiempoJugado(long millis) { + long second = (millis / 1000) % 60; + long minute = (millis / (1000 * 60)) % 60; + long hour = (millis / (1000 * 60 * 60)) % 24; + + String time = String.format("%02d:%02d:%02d", hour, minute, second); + return time; + } + + public static ItemStack getCabeza(ItemStack item, String id,String textura){ + String packageName = Bukkit.getServer().getClass().getPackage().getName(); + if(packageName.contains("1_17")){ + V1_17 u = new V1_17(); + ItemStack stack = u.getCabeza(item,id,textura); + return stack; + } + if(packageName.contains("1_16_R3")){ + V1_16_R3 u = new V1_16_R3(); + ItemStack stack = u.getCabeza(item,id,textura); + return stack; + } + if(packageName.contains("1_16_R2")){ + V1_16_R2 u = new V1_16_R2(); + ItemStack stack = u.getCabeza(item,id,textura); + return stack; + } + if(packageName.contains("1_16_R1")){ + V1_16 u = new V1_16(); + ItemStack stack = u.getCabeza(item,id,textura); + return stack; + } + if(packageName.contains("1_15_R1")){ + V1_15 u = new V1_15(); + ItemStack stack = u.getCabeza(item,id,textura); + return stack; + } + else if(packageName.contains("1_14_R1")){ + V1_14 u = new V1_14(); + ItemStack stack = u.getCabeza(item,id,textura); + return stack; + } + else if(packageName.contains("1_13_R2")){ + V1_13_R2 u = new V1_13_R2(); + ItemStack stack = u.getCabeza(item,id,textura); + return stack; + } + else if(packageName.contains("1_13_R1")){ + V1_13 u = new V1_13(); + ItemStack stack = u.getCabeza(item,id,textura); + return stack; + } + else if(packageName.contains("1_12_R1")){ + V1_12 u = new V1_12(); + ItemStack stack = u.getCabeza(item,id,textura); + return stack; + } + else if(packageName.contains("1_11_R1")){ + V1_11 u = new V1_11(); + ItemStack stack = u.getCabeza(item,id,textura); + return stack; + } + else if(packageName.contains("1_10_R1")){ + V1_10 u = new V1_10(); + ItemStack stack = u.getCabeza(item,id,textura); + return stack; + } + else if(packageName.contains("1_9_R2")){ + V1_9_R2 u = new V1_9_R2(); + ItemStack stack = u.getCabeza(item,id,textura); + return stack; + } + else if(packageName.contains("1_9_R1")){ + V1_9_R1 u = new V1_9_R1(); + ItemStack stack = u.getCabeza(item,id,textura); + return stack; + } + else if(packageName.contains("1_8_R3")){ + V1_8_R3 u = new V1_8_R3(); + ItemStack stack = u.getCabeza(item,id,textura); + return stack; + } + else if(packageName.contains("1_8_R2")){ + V1_8_R2 u = new V1_8_R2(); + ItemStack stack = u.getCabeza(item,id,textura); + return stack; + } + else if(packageName.contains("1_8_R1")){ + V1_8_R1 u = new V1_8_R1(); + ItemStack stack = u.getCabeza(item,id,textura); + return stack; + } + else{ + return item; + } + } + + public static boolean pasaConfigInventario(Player jugador,FileConfiguration config) { + if(config.getString("Config.empty_inventory_to_join").equals("true")) { + PlayerInventory inv = jugador.getInventory(); + for(ItemStack item : inv.getContents()) { + if(item != null && !item.getType().equals(Material.AIR)) { + return false; + } + } + for(ItemStack item : inv.getArmorContents()) { + if(item != null && !item.getType().equals(Material.AIR)) { + return false; + } + } + return true; + }else { + return true; + } + } + + public static double eval(final String str) { + return new Object() { + int pos = -1, ch; + + void nextChar() { + ch = (++pos < str.length()) ? str.charAt(pos) : -1; + } + + boolean eat(int charToEat) { + while (ch == ' ') nextChar(); + if (ch == charToEat) { + nextChar(); + return true; + } + return false; + } + + double parse() { + nextChar(); + double x = parseExpression(); + if (pos < str.length()) throw new RuntimeException("Unexpected: " + (char)ch); + return x; + } + + // Grammar: + // expression = term | expression `+` term | expression `-` term + // term = factor | term `*` factor | term `/` factor + // factor = `+` factor | `-` factor | `(` expression `)` + // | number | functionName factor | factor `^` factor + + double parseExpression() { + double x = parseTerm(); + for (;;) { + if (eat('+')) x += parseTerm(); // addition + else if (eat('-')) x -= parseTerm(); // subtraction + else return x; + } + } + + double parseTerm() { + double x = parseFactor(); + for (;;) { + if (eat('*')) x *= parseFactor(); // multiplication + else if (eat('/')) x /= parseFactor(); // division + else return x; + } + } + + double parseFactor() { + if (eat('+')) return parseFactor(); // unary plus + if (eat('-')) return -parseFactor(); // unary minus + + double x; + int startPos = this.pos; + if (eat('(')) { // parentheses + x = parseExpression(); + eat(')'); + } else if ((ch >= '0' && ch <= '9') || ch == '.') { // numbers + while ((ch >= '0' && ch <= '9') || ch == '.') nextChar(); + x = Double.parseDouble(str.substring(startPos, this.pos)); + } else if (ch >= 'a' && ch <= 'z') { // functions + while (ch >= 'a' && ch <= 'z') nextChar(); + String func = str.substring(startPos, this.pos); + x = parseFactor(); + if (func.equals("sqrt")) x = Math.sqrt(x); + else if (func.equals("sin")) x = Math.sin(Math.toRadians(x)); + else if (func.equals("cos")) x = Math.cos(Math.toRadians(x)); + else if (func.equals("tan")) x = Math.tan(Math.toRadians(x)); + else throw new RuntimeException("Unknown function: " + func); + } else { + throw new RuntimeException("Unexpected: " + (char)ch); + } + + if (eat('^')) x = Math.pow(x, parseFactor()); // exponentiation + + return x; + } + }.parse(); + } +} diff --git a/src/mc/ajneb97/versiones/V1_10.java b/src/mc/ajneb97/versiones/V1_10.java new file mode 100644 index 0000000..9fac9b8 --- /dev/null +++ b/src/mc/ajneb97/versiones/V1_10.java @@ -0,0 +1,86 @@ +package mc.ajneb97.versiones; + +import java.util.ArrayList; +import java.util.List; + +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.SkullType; +import org.bukkit.block.Skull; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +public class V1_10 { + + public void generarParticula(String particle, Location loc, float xOffset, float yOffset, float zOffset, float speed, int count, Player player){ + net.minecraft.server.v1_10_R1.EnumParticle enumParticle = net.minecraft.server.v1_10_R1.EnumParticle.valueOf(particle); + float x = (float)loc.getX(); + float y = (float)loc.getY(); + float z = (float)loc.getZ(); + + net.minecraft.server.v1_10_R1.PacketPlayOutWorldParticles packet = new net.minecraft.server.v1_10_R1.PacketPlayOutWorldParticles(enumParticle, false, x, y, z, xOffset, + yOffset, zOffset, speed, count, null); + + ((org.bukkit.craftbukkit.v1_10_R1.entity.CraftPlayer)player).getHandle().playerConnection.sendPacket(packet); + } + + @SuppressWarnings("deprecation") + public void setSkullBlock(Location locBloque,String id,String textura,int rot) { + net.minecraft.server.v1_10_R1.BlockPosition locDestino = new net.minecraft.server.v1_10_R1.BlockPosition(locBloque.getX(),locBloque.getY(),locBloque.getZ()); + locBloque.getBlock().setTypeIdAndData(144, (byte) 1, true); + + Skull skullBlock = (Skull) locBloque.getBlock().getState(); + skullBlock.setSkullType(SkullType.PLAYER); + skullBlock.update(); + + + net.minecraft.server.v1_10_R1.TileEntity te = ((org.bukkit.craftbukkit.v1_10_R1.CraftWorld)locBloque.getWorld()).getHandle().getTileEntity(locDestino); + net.minecraft.server.v1_10_R1.NBTTagCompound compound = new net.minecraft.server.v1_10_R1.NBTTagCompound(); + + te.save(compound); + net.minecraft.server.v1_10_R1.NBTTagCompound compoundSeleccionada = new net.minecraft.server.v1_10_R1.NBTTagCompound(); + net.minecraft.server.v1_10_R1.NBTTagCompound compoundOwner = new net.minecraft.server.v1_10_R1.NBTTagCompound(); + net.minecraft.server.v1_10_R1.NBTTagCompound compoundProperties = new net.minecraft.server.v1_10_R1.NBTTagCompound(); + net.minecraft.server.v1_10_R1.NBTTagList compoundTextures = new net.minecraft.server.v1_10_R1.NBTTagList(); + net.minecraft.server.v1_10_R1.NBTTagCompound compoundValue = new net.minecraft.server.v1_10_R1.NBTTagCompound(); + compoundValue.setString("Value", textura); + compoundTextures.add(compoundValue); + compoundProperties.set("textures", compoundTextures); + compoundOwner.set("Properties", compoundProperties); + compoundOwner.setString("Id", id); + compoundSeleccionada.setString("id", "Skull"); + compoundSeleccionada.set("Owner", compoundOwner); + compoundSeleccionada.setByte("Rot", (byte)rot); + compoundSeleccionada.setInt("x", locDestino.getX()); + compoundSeleccionada.setInt("y", locDestino.getY()); + compoundSeleccionada.setInt("z", locDestino.getZ()); + compoundSeleccionada.setByte("SkullType", (byte) 3); + te.a(compoundSeleccionada); + te.update(); + } + + public ItemStack getCabeza(ItemStack item, String id,String textura) { + net.minecraft.server.v1_10_R1.ItemStack cabeza = org.bukkit.craftbukkit.v1_10_R1.inventory.CraftItemStack.asNMSCopy(item); + net.minecraft.server.v1_10_R1.NBTTagCompound tag = cabeza.hasTag() ? cabeza.getTag() : new net.minecraft.server.v1_10_R1.NBTTagCompound(); + net.minecraft.server.v1_10_R1.NBTTagCompound skullOwnerCompound = new net.minecraft.server.v1_10_R1.NBTTagCompound(); + net.minecraft.server.v1_10_R1.NBTTagCompound propiedades = new net.minecraft.server.v1_10_R1.NBTTagCompound(); + + + net.minecraft.server.v1_10_R1.NBTTagList texturas = new net.minecraft.server.v1_10_R1.NBTTagList(); + net.minecraft.server.v1_10_R1.NBTTagCompound texturasObjeto = new net.minecraft.server.v1_10_R1.NBTTagCompound(); + texturasObjeto.setString("Value", textura); + texturas.add(texturasObjeto); + propiedades.set("textures", texturas); + skullOwnerCompound.set("Properties", propiedades); + + skullOwnerCompound.setString("Id", id); + + tag.set("SkullOwner", skullOwnerCompound); + cabeza.setTag(tag); + + + return org.bukkit.craftbukkit.v1_10_R1.inventory.CraftItemStack.asBukkitCopy(cabeza); + } +} diff --git a/src/mc/ajneb97/versiones/V1_11.java b/src/mc/ajneb97/versiones/V1_11.java new file mode 100644 index 0000000..ead6b26 --- /dev/null +++ b/src/mc/ajneb97/versiones/V1_11.java @@ -0,0 +1,86 @@ +package mc.ajneb97.versiones; + +import java.util.ArrayList; +import java.util.List; + +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.SkullType; +import org.bukkit.block.Skull; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +public class V1_11 { + + public void generarParticula(String particle, Location loc, float xOffset, float yOffset, float zOffset, float speed, int count, Player player){ + net.minecraft.server.v1_11_R1.EnumParticle enumParticle = net.minecraft.server.v1_11_R1.EnumParticle.valueOf(particle); + float x = (float)loc.getX(); + float y = (float)loc.getY(); + float z = (float)loc.getZ(); + + net.minecraft.server.v1_11_R1.PacketPlayOutWorldParticles packet = new net.minecraft.server.v1_11_R1.PacketPlayOutWorldParticles(enumParticle, false, x, y, z, xOffset, + yOffset, zOffset, speed, count, null); + + ((org.bukkit.craftbukkit.v1_11_R1.entity.CraftPlayer)player).getHandle().playerConnection.sendPacket(packet); + } + + @SuppressWarnings("deprecation") + public void setSkullBlock(Location locBloque,String id,String textura,int rot) { + net.minecraft.server.v1_11_R1.BlockPosition locDestino = new net.minecraft.server.v1_11_R1.BlockPosition(locBloque.getX(),locBloque.getY(),locBloque.getZ()); + locBloque.getBlock().setTypeIdAndData(144, (byte) 1, true); + + Skull skullBlock = (Skull) locBloque.getBlock().getState(); + skullBlock.setSkullType(SkullType.PLAYER); + skullBlock.update(); + + + net.minecraft.server.v1_11_R1.TileEntity te = ((org.bukkit.craftbukkit.v1_11_R1.CraftWorld)locBloque.getWorld()).getHandle().getTileEntity(locDestino); + net.minecraft.server.v1_11_R1.NBTTagCompound compound = new net.minecraft.server.v1_11_R1.NBTTagCompound(); + + te.save(compound); + net.minecraft.server.v1_11_R1.NBTTagCompound compoundSeleccionada = new net.minecraft.server.v1_11_R1.NBTTagCompound(); + net.minecraft.server.v1_11_R1.NBTTagCompound compoundOwner = new net.minecraft.server.v1_11_R1.NBTTagCompound(); + net.minecraft.server.v1_11_R1.NBTTagCompound compoundProperties = new net.minecraft.server.v1_11_R1.NBTTagCompound(); + net.minecraft.server.v1_11_R1.NBTTagList compoundTextures = new net.minecraft.server.v1_11_R1.NBTTagList(); + net.minecraft.server.v1_11_R1.NBTTagCompound compoundValue = new net.minecraft.server.v1_11_R1.NBTTagCompound(); + compoundValue.setString("Value", textura); + compoundTextures.add(compoundValue); + compoundProperties.set("textures", compoundTextures); + compoundOwner.set("Properties", compoundProperties); + compoundOwner.setString("Id", id); + compoundSeleccionada.setString("id", "Skull"); + compoundSeleccionada.set("Owner", compoundOwner); + compoundSeleccionada.setByte("Rot", (byte)rot); + compoundSeleccionada.setInt("x", locDestino.getX()); + compoundSeleccionada.setInt("y", locDestino.getY()); + compoundSeleccionada.setInt("z", locDestino.getZ()); + compoundSeleccionada.setByte("SkullType", (byte) 3); + te.a(compoundSeleccionada); + te.update(); + } + + public ItemStack getCabeza(ItemStack item, String id,String textura) { + net.minecraft.server.v1_11_R1.ItemStack cabeza = org.bukkit.craftbukkit.v1_11_R1.inventory.CraftItemStack.asNMSCopy(item); + net.minecraft.server.v1_11_R1.NBTTagCompound tag = cabeza.hasTag() ? cabeza.getTag() : new net.minecraft.server.v1_11_R1.NBTTagCompound(); + net.minecraft.server.v1_11_R1.NBTTagCompound skullOwnerCompound = new net.minecraft.server.v1_11_R1.NBTTagCompound(); + net.minecraft.server.v1_11_R1.NBTTagCompound propiedades = new net.minecraft.server.v1_11_R1.NBTTagCompound(); + + + net.minecraft.server.v1_11_R1.NBTTagList texturas = new net.minecraft.server.v1_11_R1.NBTTagList(); + net.minecraft.server.v1_11_R1.NBTTagCompound texturasObjeto = new net.minecraft.server.v1_11_R1.NBTTagCompound(); + texturasObjeto.setString("Value", textura); + texturas.add(texturasObjeto); + propiedades.set("textures", texturas); + skullOwnerCompound.set("Properties", propiedades); + + skullOwnerCompound.setString("Id", id); + + tag.set("SkullOwner", skullOwnerCompound); + cabeza.setTag(tag); + + + return org.bukkit.craftbukkit.v1_11_R1.inventory.CraftItemStack.asBukkitCopy(cabeza); + } +} diff --git a/src/mc/ajneb97/versiones/V1_12.java b/src/mc/ajneb97/versiones/V1_12.java new file mode 100644 index 0000000..849ff02 --- /dev/null +++ b/src/mc/ajneb97/versiones/V1_12.java @@ -0,0 +1,86 @@ +package mc.ajneb97.versiones; + +import java.util.ArrayList; +import java.util.List; + +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.SkullType; +import org.bukkit.block.Skull; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +public class V1_12 { + + public void generarParticula(String particle, Location loc, float xOffset, float yOffset, float zOffset, float speed, int count, Player player){ + net.minecraft.server.v1_12_R1.EnumParticle enumParticle = net.minecraft.server.v1_12_R1.EnumParticle.valueOf(particle); + float x = (float)loc.getX(); + float y = (float)loc.getY(); + float z = (float)loc.getZ(); + + net.minecraft.server.v1_12_R1.PacketPlayOutWorldParticles packet = new net.minecraft.server.v1_12_R1.PacketPlayOutWorldParticles(enumParticle, false, x, y, z, xOffset, + yOffset, zOffset, speed, count, null); + + ((org.bukkit.craftbukkit.v1_12_R1.entity.CraftPlayer)player).getHandle().playerConnection.sendPacket(packet); + } + + @SuppressWarnings("deprecation") + public void setSkullBlock(Location locBloque,String id,String textura,int rot) { + net.minecraft.server.v1_12_R1.BlockPosition locDestino = new net.minecraft.server.v1_12_R1.BlockPosition(locBloque.getX(),locBloque.getY(),locBloque.getZ()); + locBloque.getBlock().setTypeIdAndData(144, (byte) 1, true); + + Skull skullBlock = (Skull) locBloque.getBlock().getState(); + skullBlock.setSkullType(SkullType.PLAYER); + skullBlock.update(); + + + net.minecraft.server.v1_12_R1.TileEntity te = ((org.bukkit.craftbukkit.v1_12_R1.CraftWorld)locBloque.getWorld()).getHandle().getTileEntity(locDestino); + net.minecraft.server.v1_12_R1.NBTTagCompound compound = new net.minecraft.server.v1_12_R1.NBTTagCompound(); + + te.save(compound); + net.minecraft.server.v1_12_R1.NBTTagCompound compoundSeleccionada = new net.minecraft.server.v1_12_R1.NBTTagCompound(); + net.minecraft.server.v1_12_R1.NBTTagCompound compoundOwner = new net.minecraft.server.v1_12_R1.NBTTagCompound(); + net.minecraft.server.v1_12_R1.NBTTagCompound compoundProperties = new net.minecraft.server.v1_12_R1.NBTTagCompound(); + net.minecraft.server.v1_12_R1.NBTTagList compoundTextures = new net.minecraft.server.v1_12_R1.NBTTagList(); + net.minecraft.server.v1_12_R1.NBTTagCompound compoundValue = new net.minecraft.server.v1_12_R1.NBTTagCompound(); + compoundValue.setString("Value", textura); + compoundTextures.add(compoundValue); + compoundProperties.set("textures", compoundTextures); + compoundOwner.set("Properties", compoundProperties); + compoundOwner.setString("Id", id); + compoundSeleccionada.setString("id", "Skull"); + compoundSeleccionada.set("Owner", compoundOwner); + compoundSeleccionada.setByte("Rot", (byte)rot); + compoundSeleccionada.setInt("x", locDestino.getX()); + compoundSeleccionada.setInt("y", locDestino.getY()); + compoundSeleccionada.setInt("z", locDestino.getZ()); + compoundSeleccionada.setByte("SkullType", (byte) 3); + te.load(compoundSeleccionada); + te.update(); + } + + public ItemStack getCabeza(ItemStack item, String id,String textura) { + net.minecraft.server.v1_12_R1.ItemStack cabeza = org.bukkit.craftbukkit.v1_12_R1.inventory.CraftItemStack.asNMSCopy(item); + net.minecraft.server.v1_12_R1.NBTTagCompound tag = cabeza.hasTag() ? cabeza.getTag() : new net.minecraft.server.v1_12_R1.NBTTagCompound(); + net.minecraft.server.v1_12_R1.NBTTagCompound skullOwnerCompound = new net.minecraft.server.v1_12_R1.NBTTagCompound(); + net.minecraft.server.v1_12_R1.NBTTagCompound propiedades = new net.minecraft.server.v1_12_R1.NBTTagCompound(); + + + net.minecraft.server.v1_12_R1.NBTTagList texturas = new net.minecraft.server.v1_12_R1.NBTTagList(); + net.minecraft.server.v1_12_R1.NBTTagCompound texturasObjeto = new net.minecraft.server.v1_12_R1.NBTTagCompound(); + texturasObjeto.setString("Value", textura); + texturas.add(texturasObjeto); + propiedades.set("textures", texturas); + skullOwnerCompound.set("Properties", propiedades); + + skullOwnerCompound.setString("Id", id); + + tag.set("SkullOwner", skullOwnerCompound); + cabeza.setTag(tag); + + + return org.bukkit.craftbukkit.v1_12_R1.inventory.CraftItemStack.asBukkitCopy(cabeza); + } +} diff --git a/src/mc/ajneb97/versiones/V1_13.java b/src/mc/ajneb97/versiones/V1_13.java new file mode 100644 index 0000000..eaf64f3 --- /dev/null +++ b/src/mc/ajneb97/versiones/V1_13.java @@ -0,0 +1,81 @@ +package mc.ajneb97.versiones; + +import java.util.ArrayList; +import java.util.List; + +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.Particle; +import org.bukkit.SkullType; +import org.bukkit.block.BlockFace; +import org.bukkit.block.Skull; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +public class V1_13 { + + public void generarParticula(String particle, Location loc, float xOffset, float yOffset, float zOffset, float speed, int count, Player player){ + player.spawnParticle(Particle.valueOf(particle),loc,count,xOffset,yOffset,zOffset,speed); + } + + @SuppressWarnings("deprecation") + public void setSkullBlock(Location locBloque,String id,String textura,int rot) { + net.minecraft.server.v1_13_R1.BlockPosition locDestino = new net.minecraft.server.v1_13_R1.BlockPosition(locBloque.getX(),locBloque.getY(),locBloque.getZ()); + locBloque.getBlock().setType(Material.valueOf("PLAYER_HEAD")); + + Skull skullBlock = (Skull) locBloque.getBlock().getState(); + if(rot == 8) { + skullBlock.setRotation(BlockFace.NORTH); + } + skullBlock.update(); + + + net.minecraft.server.v1_13_R1.TileEntity te = ((org.bukkit.craftbukkit.v1_13_R1.CraftWorld)locBloque.getWorld()).getHandle().getTileEntity(locDestino); + net.minecraft.server.v1_13_R1.NBTTagCompound compound = new net.minecraft.server.v1_13_R1.NBTTagCompound(); + + te.save(compound); + net.minecraft.server.v1_13_R1.NBTTagCompound compoundSeleccionada = new net.minecraft.server.v1_13_R1.NBTTagCompound(); + net.minecraft.server.v1_13_R1.NBTTagCompound compoundOwner = new net.minecraft.server.v1_13_R1.NBTTagCompound(); + net.minecraft.server.v1_13_R1.NBTTagCompound compoundProperties = new net.minecraft.server.v1_13_R1.NBTTagCompound(); + net.minecraft.server.v1_13_R1.NBTTagList compoundTextures = new net.minecraft.server.v1_13_R1.NBTTagList(); + net.minecraft.server.v1_13_R1.NBTTagCompound compoundValue = new net.minecraft.server.v1_13_R1.NBTTagCompound(); + compoundValue.setString("Value", textura); + compoundTextures.add(compoundValue); + compoundProperties.set("textures", compoundTextures); + compoundOwner.set("Properties", compoundProperties); + compoundOwner.setString("Id", id); + compoundSeleccionada.setString("id", "Skull"); + compoundSeleccionada.set("Owner", compoundOwner); + compoundSeleccionada.setInt("x", locDestino.getX()); + compoundSeleccionada.setInt("y", locDestino.getY()); + compoundSeleccionada.setInt("z", locDestino.getZ()); + compoundSeleccionada.setByte("SkullType", (byte) 3); + te.load(compoundSeleccionada); + te.update(); + } + + public ItemStack getCabeza(ItemStack item, String id,String textura) { + net.minecraft.server.v1_13_R1.ItemStack cabeza = org.bukkit.craftbukkit.v1_13_R1.inventory.CraftItemStack.asNMSCopy(item); + net.minecraft.server.v1_13_R1.NBTTagCompound tag = cabeza.hasTag() ? cabeza.getTag() : new net.minecraft.server.v1_13_R1.NBTTagCompound(); + net.minecraft.server.v1_13_R1.NBTTagCompound skullOwnerCompound = new net.minecraft.server.v1_13_R1.NBTTagCompound(); + net.minecraft.server.v1_13_R1.NBTTagCompound propiedades = new net.minecraft.server.v1_13_R1.NBTTagCompound(); + + + net.minecraft.server.v1_13_R1.NBTTagList texturas = new net.minecraft.server.v1_13_R1.NBTTagList(); + net.minecraft.server.v1_13_R1.NBTTagCompound texturasObjeto = new net.minecraft.server.v1_13_R1.NBTTagCompound(); + texturasObjeto.setString("Value", textura); + texturas.add(texturasObjeto); + propiedades.set("textures", texturas); + skullOwnerCompound.set("Properties", propiedades); + + skullOwnerCompound.setString("Id", id); + + tag.set("SkullOwner", skullOwnerCompound); + cabeza.setTag(tag); + + + return org.bukkit.craftbukkit.v1_13_R1.inventory.CraftItemStack.asBukkitCopy(cabeza); + } +} diff --git a/src/mc/ajneb97/versiones/V1_13_R2.java b/src/mc/ajneb97/versiones/V1_13_R2.java new file mode 100644 index 0000000..5563630 --- /dev/null +++ b/src/mc/ajneb97/versiones/V1_13_R2.java @@ -0,0 +1,81 @@ +package mc.ajneb97.versiones; + +import java.util.ArrayList; +import java.util.List; + +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.Particle; +import org.bukkit.SkullType; +import org.bukkit.block.BlockFace; +import org.bukkit.block.Skull; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +public class V1_13_R2 { + + public void generarParticula(String particle, Location loc, float xOffset, float yOffset, float zOffset, float speed, int count, Player player){ + player.spawnParticle(Particle.valueOf(particle),loc,count,xOffset,yOffset,zOffset,speed); + } + + @SuppressWarnings("deprecation") + public void setSkullBlock(Location locBloque,String id,String textura,int rot) { + net.minecraft.server.v1_13_R2.BlockPosition locDestino = new net.minecraft.server.v1_13_R2.BlockPosition(locBloque.getX(),locBloque.getY(),locBloque.getZ()); + locBloque.getBlock().setType(Material.valueOf("PLAYER_HEAD")); + + Skull skullBlock = (Skull) locBloque.getBlock().getState(); + if(rot == 8) { + skullBlock.setRotation(BlockFace.NORTH); + } + skullBlock.update(); + + + net.minecraft.server.v1_13_R2.TileEntity te = ((org.bukkit.craftbukkit.v1_13_R2.CraftWorld)locBloque.getWorld()).getHandle().getTileEntity(locDestino); + net.minecraft.server.v1_13_R2.NBTTagCompound compound = new net.minecraft.server.v1_13_R2.NBTTagCompound(); + + te.save(compound); + net.minecraft.server.v1_13_R2.NBTTagCompound compoundSeleccionada = new net.minecraft.server.v1_13_R2.NBTTagCompound(); + net.minecraft.server.v1_13_R2.NBTTagCompound compoundOwner = new net.minecraft.server.v1_13_R2.NBTTagCompound(); + net.minecraft.server.v1_13_R2.NBTTagCompound compoundProperties = new net.minecraft.server.v1_13_R2.NBTTagCompound(); + net.minecraft.server.v1_13_R2.NBTTagList compoundTextures = new net.minecraft.server.v1_13_R2.NBTTagList(); + net.minecraft.server.v1_13_R2.NBTTagCompound compoundValue = new net.minecraft.server.v1_13_R2.NBTTagCompound(); + compoundValue.setString("Value", textura); + compoundTextures.add(compoundValue); + compoundProperties.set("textures", compoundTextures); + compoundOwner.set("Properties", compoundProperties); + compoundOwner.setString("Id", id); + compoundSeleccionada.setString("id", "Skull"); + compoundSeleccionada.set("Owner", compoundOwner); + compoundSeleccionada.setInt("x", locDestino.getX()); + compoundSeleccionada.setInt("y", locDestino.getY()); + compoundSeleccionada.setInt("z", locDestino.getZ()); + compoundSeleccionada.setByte("SkullType", (byte) 3); + te.load(compoundSeleccionada); + te.update(); + } + + public ItemStack getCabeza(ItemStack item, String id,String textura) { + net.minecraft.server.v1_13_R2.ItemStack cabeza = org.bukkit.craftbukkit.v1_13_R2.inventory.CraftItemStack.asNMSCopy(item); + net.minecraft.server.v1_13_R2.NBTTagCompound tag = cabeza.hasTag() ? cabeza.getTag() : new net.minecraft.server.v1_13_R2.NBTTagCompound(); + net.minecraft.server.v1_13_R2.NBTTagCompound skullOwnerCompound = new net.minecraft.server.v1_13_R2.NBTTagCompound(); + net.minecraft.server.v1_13_R2.NBTTagCompound propiedades = new net.minecraft.server.v1_13_R2.NBTTagCompound(); + + + net.minecraft.server.v1_13_R2.NBTTagList texturas = new net.minecraft.server.v1_13_R2.NBTTagList(); + net.minecraft.server.v1_13_R2.NBTTagCompound texturasObjeto = new net.minecraft.server.v1_13_R2.NBTTagCompound(); + texturasObjeto.setString("Value", textura); + texturas.add(texturasObjeto); + propiedades.set("textures", texturas); + skullOwnerCompound.set("Properties", propiedades); + + skullOwnerCompound.setString("Id", id); + + tag.set("SkullOwner", skullOwnerCompound); + cabeza.setTag(tag); + + + return org.bukkit.craftbukkit.v1_13_R2.inventory.CraftItemStack.asBukkitCopy(cabeza); + } +} diff --git a/src/mc/ajneb97/versiones/V1_14.java b/src/mc/ajneb97/versiones/V1_14.java new file mode 100644 index 0000000..ebea3db --- /dev/null +++ b/src/mc/ajneb97/versiones/V1_14.java @@ -0,0 +1,83 @@ +package mc.ajneb97.versiones; + +import java.util.ArrayList; +import java.util.List; + +import org.bukkit.Bukkit; +import org.bukkit.Color; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.Particle; +import org.bukkit.SkullType; +import org.bukkit.block.BlockFace; +import org.bukkit.block.Skull; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +public class V1_14 { + + public void generarParticula(String particle, Location loc, float xOffset, float yOffset, float zOffset, float speed, int count, Player player){ + player.spawnParticle(Particle.valueOf(particle),loc,count,xOffset,yOffset,zOffset,speed); + } + + @SuppressWarnings("deprecation") + public void setSkullBlock(Location locBloque,String id,String textura,int rot) { + net.minecraft.server.v1_14_R1.BlockPosition locDestino = new net.minecraft.server.v1_14_R1.BlockPosition(locBloque.getX(),locBloque.getY(),locBloque.getZ()); + locBloque.getBlock().setType(Material.valueOf("PLAYER_HEAD")); + + Skull skullBlock = (Skull) locBloque.getBlock().getState(); + //skullBlock.setSkullType(SkullType.PLAYER); + if(rot == 8) { + skullBlock.setRotation(BlockFace.NORTH); + } + skullBlock.update(); + + + net.minecraft.server.v1_14_R1.TileEntity te = ((org.bukkit.craftbukkit.v1_14_R1.CraftWorld)locBloque.getWorld()).getHandle().getTileEntity(locDestino); + net.minecraft.server.v1_14_R1.NBTTagCompound compound = new net.minecraft.server.v1_14_R1.NBTTagCompound(); + + te.save(compound); + net.minecraft.server.v1_14_R1.NBTTagCompound compoundSeleccionada = new net.minecraft.server.v1_14_R1.NBTTagCompound(); + net.minecraft.server.v1_14_R1.NBTTagCompound compoundOwner = new net.minecraft.server.v1_14_R1.NBTTagCompound(); + net.minecraft.server.v1_14_R1.NBTTagCompound compoundProperties = new net.minecraft.server.v1_14_R1.NBTTagCompound(); + net.minecraft.server.v1_14_R1.NBTTagList compoundTextures = new net.minecraft.server.v1_14_R1.NBTTagList(); + net.minecraft.server.v1_14_R1.NBTTagCompound compoundValue = new net.minecraft.server.v1_14_R1.NBTTagCompound(); + compoundValue.setString("Value", textura); + compoundTextures.add(compoundValue); + compoundProperties.set("textures", compoundTextures); + compoundOwner.set("Properties", compoundProperties); + compoundOwner.setString("Id", id); + compoundSeleccionada.setString("id", "Skull"); + compoundSeleccionada.set("Owner", compoundOwner); + compoundSeleccionada.setInt("x", locDestino.getX()); + compoundSeleccionada.setInt("y", locDestino.getY()); + compoundSeleccionada.setInt("z", locDestino.getZ()); + compoundSeleccionada.setByte("SkullType", (byte) 3); + te.load(compoundSeleccionada); + te.update(); + } + + public ItemStack getCabeza(ItemStack item, String id,String textura) { + net.minecraft.server.v1_14_R1.ItemStack cabeza = org.bukkit.craftbukkit.v1_14_R1.inventory.CraftItemStack.asNMSCopy(item); + net.minecraft.server.v1_14_R1.NBTTagCompound tag = cabeza.hasTag() ? cabeza.getTag() : new net.minecraft.server.v1_14_R1.NBTTagCompound(); + net.minecraft.server.v1_14_R1.NBTTagCompound skullOwnerCompound = new net.minecraft.server.v1_14_R1.NBTTagCompound(); + net.minecraft.server.v1_14_R1.NBTTagCompound propiedades = new net.minecraft.server.v1_14_R1.NBTTagCompound(); + + + net.minecraft.server.v1_14_R1.NBTTagList texturas = new net.minecraft.server.v1_14_R1.NBTTagList(); + net.minecraft.server.v1_14_R1.NBTTagCompound texturasObjeto = new net.minecraft.server.v1_14_R1.NBTTagCompound(); + texturasObjeto.setString("Value", textura); + texturas.add(texturasObjeto); + propiedades.set("textures", texturas); + skullOwnerCompound.set("Properties", propiedades); + + skullOwnerCompound.setString("Id", id); + + tag.set("SkullOwner", skullOwnerCompound); + cabeza.setTag(tag); + + + return org.bukkit.craftbukkit.v1_14_R1.inventory.CraftItemStack.asBukkitCopy(cabeza); + } +} diff --git a/src/mc/ajneb97/versiones/V1_15.java b/src/mc/ajneb97/versiones/V1_15.java new file mode 100644 index 0000000..3534bb4 --- /dev/null +++ b/src/mc/ajneb97/versiones/V1_15.java @@ -0,0 +1,86 @@ +package mc.ajneb97.versiones; + +import java.util.ArrayList; +import java.util.List; + +import org.bukkit.Bukkit; +import org.bukkit.Color; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.Particle; +import org.bukkit.SkullType; +import org.bukkit.block.BlockFace; +import org.bukkit.block.Skull; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +public class V1_15 { + + public void generarParticula(String particle, Location loc, float xOffset, float yOffset, float zOffset, float speed, int count, Player player){ + player.spawnParticle(Particle.valueOf(particle),loc,count,xOffset,yOffset,zOffset,speed); + } + + + @SuppressWarnings("deprecation") + public void setSkullBlock(Location locBloque,String id,String textura,int rot) { + net.minecraft.server.v1_15_R1.BlockPosition locDestino = new net.minecraft.server.v1_15_R1.BlockPosition(locBloque.getX(),locBloque.getY(),locBloque.getZ()); + locBloque.getBlock().setType(Material.valueOf("PLAYER_HEAD")); + + Skull skullBlock = (Skull) locBloque.getBlock().getState(); + //skullBlock.setSkullType(SkullType.PLAYER); + if(rot == 8) { + skullBlock.setRotation(BlockFace.NORTH); + } + skullBlock.update(); + + + + + net.minecraft.server.v1_15_R1.TileEntity te = ((org.bukkit.craftbukkit.v1_15_R1.CraftWorld)locBloque.getWorld()).getHandle().getTileEntity(locDestino); + net.minecraft.server.v1_15_R1.NBTTagCompound compound = new net.minecraft.server.v1_15_R1.NBTTagCompound(); + + te.save(compound); + net.minecraft.server.v1_15_R1.NBTTagCompound compoundSeleccionada = new net.minecraft.server.v1_15_R1.NBTTagCompound(); + net.minecraft.server.v1_15_R1.NBTTagCompound compoundOwner = new net.minecraft.server.v1_15_R1.NBTTagCompound(); + net.minecraft.server.v1_15_R1.NBTTagCompound compoundProperties = new net.minecraft.server.v1_15_R1.NBTTagCompound(); + net.minecraft.server.v1_15_R1.NBTTagList compoundTextures = new net.minecraft.server.v1_15_R1.NBTTagList(); + net.minecraft.server.v1_15_R1.NBTTagCompound compoundValue = new net.minecraft.server.v1_15_R1.NBTTagCompound(); + compoundValue.setString("Value", textura); + compoundTextures.add(compoundValue); + compoundProperties.set("textures", compoundTextures); + compoundOwner.set("Properties", compoundProperties); + compoundOwner.setString("Id", id); + compoundSeleccionada.setString("id", "Skull"); + compoundSeleccionada.set("Owner", compoundOwner); + compoundSeleccionada.setInt("x", locDestino.getX()); + compoundSeleccionada.setInt("y", locDestino.getY()); + compoundSeleccionada.setInt("z", locDestino.getZ()); + compoundSeleccionada.setByte("SkullType", (byte) 3); + te.load(compoundSeleccionada); + te.update(); + } + + public ItemStack getCabeza(ItemStack item, String id,String textura) { + net.minecraft.server.v1_15_R1.ItemStack cabeza = org.bukkit.craftbukkit.v1_15_R1.inventory.CraftItemStack.asNMSCopy(item); + net.minecraft.server.v1_15_R1.NBTTagCompound tag = cabeza.hasTag() ? cabeza.getTag() : new net.minecraft.server.v1_15_R1.NBTTagCompound(); + net.minecraft.server.v1_15_R1.NBTTagCompound skullOwnerCompound = new net.minecraft.server.v1_15_R1.NBTTagCompound(); + net.minecraft.server.v1_15_R1.NBTTagCompound propiedades = new net.minecraft.server.v1_15_R1.NBTTagCompound(); + + + net.minecraft.server.v1_15_R1.NBTTagList texturas = new net.minecraft.server.v1_15_R1.NBTTagList(); + net.minecraft.server.v1_15_R1.NBTTagCompound texturasObjeto = new net.minecraft.server.v1_15_R1.NBTTagCompound(); + texturasObjeto.setString("Value", textura); + texturas.add(texturasObjeto); + propiedades.set("textures", texturas); + skullOwnerCompound.set("Properties", propiedades); + + skullOwnerCompound.setString("Id", id); + + tag.set("SkullOwner", skullOwnerCompound); + cabeza.setTag(tag); + + + return org.bukkit.craftbukkit.v1_15_R1.inventory.CraftItemStack.asBukkitCopy(cabeza); + } +} diff --git a/src/mc/ajneb97/versiones/V1_16.java b/src/mc/ajneb97/versiones/V1_16.java new file mode 100644 index 0000000..9e6f3c4 --- /dev/null +++ b/src/mc/ajneb97/versiones/V1_16.java @@ -0,0 +1,71 @@ +package mc.ajneb97.versiones; + +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +import org.bukkit.Bukkit; +import org.bukkit.Color; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.Particle; +import org.bukkit.SkullType; +import org.bukkit.block.BlockFace; +import org.bukkit.block.Skull; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.SkullMeta; + +import com.mojang.authlib.GameProfile; +import com.mojang.authlib.properties.Property; + +public class V1_16 { + + public void generarParticula(String particle, Location loc, float xOffset, float yOffset, float zOffset, float speed, int count, Player player){ + player.spawnParticle(Particle.valueOf(particle),loc,count,xOffset,yOffset,zOffset,speed); + } + + + @SuppressWarnings("deprecation") + public void setSkullBlock(Location locBloque,String id,String textura,int rot) { + locBloque.getBlock().setType(Material.valueOf("PLAYER_HEAD")); + Skull skullBlock = (Skull) locBloque.getBlock().getState(); + //skullBlock.setSkullType(SkullType.PLAYER); + if(rot == 8) { + skullBlock.setRotation(BlockFace.NORTH); + } + GameProfile profile = new GameProfile(UUID.randomUUID(), null); + profile.getProperties().put("textures", new Property("textures", textura)); + + try { + Field profileField = skullBlock.getClass().getDeclaredField("profile"); + profileField.setAccessible(true); + profileField.set(skullBlock, profile); + }catch (NoSuchFieldException | IllegalAccessException e) { e.printStackTrace(); } + + skullBlock.update(); + } + + public ItemStack getCabeza(ItemStack item, String id,String textura) { + if (textura.isEmpty()) return item; + + SkullMeta skullMeta = (SkullMeta) item.getItemMeta(); + GameProfile profile = new GameProfile(UUID.randomUUID(), null); + profile.getProperties().put("textures", new Property("textures", textura)); + + try { + Method mtd = skullMeta.getClass().getDeclaredMethod("setProfile", GameProfile.class); + mtd.setAccessible(true); + mtd.invoke(skullMeta, profile); + } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException ex) { + ex.printStackTrace(); + } + + item.setItemMeta(skullMeta); + return item; + } +} diff --git a/src/mc/ajneb97/versiones/V1_16_R2.java b/src/mc/ajneb97/versiones/V1_16_R2.java new file mode 100644 index 0000000..1a0c55d --- /dev/null +++ b/src/mc/ajneb97/versiones/V1_16_R2.java @@ -0,0 +1,71 @@ +package mc.ajneb97.versiones; + +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +import org.bukkit.Bukkit; +import org.bukkit.Color; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.Particle; +import org.bukkit.SkullType; +import org.bukkit.block.BlockFace; +import org.bukkit.block.Skull; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.SkullMeta; + +import com.mojang.authlib.GameProfile; +import com.mojang.authlib.properties.Property; + +public class V1_16_R2 { + + public void generarParticula(String particle, Location loc, float xOffset, float yOffset, float zOffset, float speed, int count, Player player){ + player.spawnParticle(Particle.valueOf(particle),loc,count,xOffset,yOffset,zOffset,speed); + } + + + @SuppressWarnings("deprecation") + public void setSkullBlock(Location locBloque,String id,String textura,int rot) { + locBloque.getBlock().setType(Material.valueOf("PLAYER_HEAD")); + Skull skullBlock = (Skull) locBloque.getBlock().getState(); + //skullBlock.setSkullType(SkullType.PLAYER); + if(rot == 8) { + skullBlock.setRotation(BlockFace.NORTH); + } + GameProfile profile = new GameProfile(UUID.randomUUID(), null); + profile.getProperties().put("textures", new Property("textures", textura)); + + try { + Field profileField = skullBlock.getClass().getDeclaredField("profile"); + profileField.setAccessible(true); + profileField.set(skullBlock, profile); + }catch (NoSuchFieldException | IllegalAccessException e) { e.printStackTrace(); } + + skullBlock.update(); + } + + public ItemStack getCabeza(ItemStack item, String id,String textura) { + if (textura.isEmpty()) return item; + + SkullMeta skullMeta = (SkullMeta) item.getItemMeta(); + GameProfile profile = new GameProfile(UUID.randomUUID(), null); + profile.getProperties().put("textures", new Property("textures", textura)); + + try { + Method mtd = skullMeta.getClass().getDeclaredMethod("setProfile", GameProfile.class); + mtd.setAccessible(true); + mtd.invoke(skullMeta, profile); + } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException ex) { + ex.printStackTrace(); + } + + item.setItemMeta(skullMeta); + return item; + } +} diff --git a/src/mc/ajneb97/versiones/V1_16_R3.java b/src/mc/ajneb97/versiones/V1_16_R3.java new file mode 100644 index 0000000..c47a46f --- /dev/null +++ b/src/mc/ajneb97/versiones/V1_16_R3.java @@ -0,0 +1,71 @@ +package mc.ajneb97.versiones; + +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +import org.bukkit.Bukkit; +import org.bukkit.Color; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.Particle; +import org.bukkit.SkullType; +import org.bukkit.block.BlockFace; +import org.bukkit.block.Skull; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.SkullMeta; + +import com.mojang.authlib.GameProfile; +import com.mojang.authlib.properties.Property; + +public class V1_16_R3 { + + public void generarParticula(String particle, Location loc, float xOffset, float yOffset, float zOffset, float speed, int count, Player player){ + player.spawnParticle(Particle.valueOf(particle),loc,count,xOffset,yOffset,zOffset,speed); + } + + + @SuppressWarnings("deprecation") + public void setSkullBlock(Location locBloque,String id,String textura,int rot) { + locBloque.getBlock().setType(Material.valueOf("PLAYER_HEAD")); + Skull skullBlock = (Skull) locBloque.getBlock().getState(); + //skullBlock.setSkullType(SkullType.PLAYER); + if(rot == 8) { + skullBlock.setRotation(BlockFace.NORTH); + } + GameProfile profile = new GameProfile(UUID.randomUUID(), null); + profile.getProperties().put("textures", new Property("textures", textura)); + + try { + Field profileField = skullBlock.getClass().getDeclaredField("profile"); + profileField.setAccessible(true); + profileField.set(skullBlock, profile); + }catch (NoSuchFieldException | IllegalAccessException e) { e.printStackTrace(); } + + skullBlock.update(); + } + + public ItemStack getCabeza(ItemStack item, String id,String textura) { + if (textura.isEmpty()) return item; + + SkullMeta skullMeta = (SkullMeta) item.getItemMeta(); + GameProfile profile = new GameProfile(UUID.randomUUID(), null); + profile.getProperties().put("textures", new Property("textures", textura)); + + try { + Method mtd = skullMeta.getClass().getDeclaredMethod("setProfile", GameProfile.class); + mtd.setAccessible(true); + mtd.invoke(skullMeta, profile); + } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException ex) { + ex.printStackTrace(); + } + + item.setItemMeta(skullMeta); + return item; + } +} diff --git a/src/mc/ajneb97/versiones/V1_17.java b/src/mc/ajneb97/versiones/V1_17.java new file mode 100644 index 0000000..2098b0a --- /dev/null +++ b/src/mc/ajneb97/versiones/V1_17.java @@ -0,0 +1,71 @@ +package mc.ajneb97.versiones; + +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +import org.bukkit.Bukkit; +import org.bukkit.Color; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.Particle; +import org.bukkit.SkullType; +import org.bukkit.block.BlockFace; +import org.bukkit.block.Skull; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.SkullMeta; + +import com.mojang.authlib.GameProfile; +import com.mojang.authlib.properties.Property; + +public class V1_17 { + + public void generarParticula(String particle, Location loc, float xOffset, float yOffset, float zOffset, float speed, int count, Player player){ + player.spawnParticle(Particle.valueOf(particle),loc,count,xOffset,yOffset,zOffset,speed); + } + + + @SuppressWarnings("deprecation") + public void setSkullBlock(Location locBloque,String id,String textura,int rot) { + locBloque.getBlock().setType(Material.valueOf("PLAYER_HEAD")); + Skull skullBlock = (Skull) locBloque.getBlock().getState(); + //skullBlock.setSkullType(SkullType.PLAYER); + if(rot == 8) { + skullBlock.setRotation(BlockFace.NORTH); + } + GameProfile profile = new GameProfile(UUID.randomUUID(), null); + profile.getProperties().put("textures", new Property("textures", textura)); + + try { + Field profileField = skullBlock.getClass().getDeclaredField("profile"); + profileField.setAccessible(true); + profileField.set(skullBlock, profile); + }catch (NoSuchFieldException | IllegalAccessException e) { e.printStackTrace(); } + + skullBlock.update(); + } + + public ItemStack getCabeza(ItemStack item, String id,String textura) { + if (textura.isEmpty()) return item; + + SkullMeta skullMeta = (SkullMeta) item.getItemMeta(); + GameProfile profile = new GameProfile(UUID.randomUUID(), null); + profile.getProperties().put("textures", new Property("textures", textura)); + + try { + Method mtd = skullMeta.getClass().getDeclaredMethod("setProfile", GameProfile.class); + mtd.setAccessible(true); + mtd.invoke(skullMeta, profile); + } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException ex) { + ex.printStackTrace(); + } + + item.setItemMeta(skullMeta); + return item; + } +} diff --git a/src/mc/ajneb97/versiones/V1_8_R1.java b/src/mc/ajneb97/versiones/V1_8_R1.java new file mode 100644 index 0000000..edbf45b --- /dev/null +++ b/src/mc/ajneb97/versiones/V1_8_R1.java @@ -0,0 +1,86 @@ +package mc.ajneb97.versiones; + +import java.util.ArrayList; +import java.util.List; + +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.SkullType; +import org.bukkit.block.Skull; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +public class V1_8_R1 { + + public void generarParticula(String particle, Location loc, float xOffset, float yOffset, float zOffset, float speed, int count, Player player){ + net.minecraft.server.v1_8_R1.EnumParticle enumParticle = net.minecraft.server.v1_8_R1.EnumParticle.valueOf(particle); + float x = (float)loc.getX(); + float y = (float)loc.getY(); + float z = (float)loc.getZ(); + + net.minecraft.server.v1_8_R1.PacketPlayOutWorldParticles packet = new net.minecraft.server.v1_8_R1.PacketPlayOutWorldParticles(enumParticle, false, x, y, z, xOffset, + yOffset, zOffset, speed, count, null); + + ((org.bukkit.craftbukkit.v1_8_R1.entity.CraftPlayer)player).getHandle().playerConnection.sendPacket(packet); + } + + @SuppressWarnings("deprecation") + public void setSkullBlock(Location locBloque,String id,String textura,int rot) { + net.minecraft.server.v1_8_R1.BlockPosition locDestino = new net.minecraft.server.v1_8_R1.BlockPosition(locBloque.getX(),locBloque.getY(),locBloque.getZ()); + locBloque.getBlock().setTypeIdAndData(144, (byte) 1, true); + + Skull skullBlock = (Skull) locBloque.getBlock().getState(); + skullBlock.setSkullType(SkullType.PLAYER); + skullBlock.update(); + + + net.minecraft.server.v1_8_R1.TileEntity te = ((org.bukkit.craftbukkit.v1_8_R1.CraftWorld)locBloque.getWorld()).getHandle().getTileEntity(locDestino); + net.minecraft.server.v1_8_R1.NBTTagCompound compound = new net.minecraft.server.v1_8_R1.NBTTagCompound(); + + te.b(compound); + net.minecraft.server.v1_8_R1.NBTTagCompound compoundSeleccionada = new net.minecraft.server.v1_8_R1.NBTTagCompound(); + net.minecraft.server.v1_8_R1.NBTTagCompound compoundOwner = new net.minecraft.server.v1_8_R1.NBTTagCompound(); + net.minecraft.server.v1_8_R1.NBTTagCompound compoundProperties = new net.minecraft.server.v1_8_R1.NBTTagCompound(); + net.minecraft.server.v1_8_R1.NBTTagList compoundTextures = new net.minecraft.server.v1_8_R1.NBTTagList(); + net.minecraft.server.v1_8_R1.NBTTagCompound compoundValue = new net.minecraft.server.v1_8_R1.NBTTagCompound(); + compoundValue.setString("Value", textura); + compoundTextures.add(compoundValue); + compoundProperties.set("textures", compoundTextures); + compoundOwner.set("Properties", compoundProperties); + compoundOwner.setString("Id", id); + compoundSeleccionada.setString("id", "Skull"); + compoundSeleccionada.set("Owner", compoundOwner); + compoundSeleccionada.setByte("Rot", (byte)rot); + compoundSeleccionada.setInt("x", locDestino.getX()); + compoundSeleccionada.setInt("y", locDestino.getY()); + compoundSeleccionada.setInt("z", locDestino.getZ()); + compoundSeleccionada.setByte("SkullType", (byte) 3); + te.a(compoundSeleccionada); + te.update(); + } + + public ItemStack getCabeza(ItemStack item, String id,String textura) { + net.minecraft.server.v1_8_R1.ItemStack cabeza = org.bukkit.craftbukkit.v1_8_R1.inventory.CraftItemStack.asNMSCopy(item); + net.minecraft.server.v1_8_R1.NBTTagCompound tag = cabeza.hasTag() ? cabeza.getTag() : new net.minecraft.server.v1_8_R1.NBTTagCompound(); + net.minecraft.server.v1_8_R1.NBTTagCompound skullOwnerCompound = new net.minecraft.server.v1_8_R1.NBTTagCompound(); + net.minecraft.server.v1_8_R1.NBTTagCompound propiedades = new net.minecraft.server.v1_8_R1.NBTTagCompound(); + + + net.minecraft.server.v1_8_R1.NBTTagList texturas = new net.minecraft.server.v1_8_R1.NBTTagList(); + net.minecraft.server.v1_8_R1.NBTTagCompound texturasObjeto = new net.minecraft.server.v1_8_R1.NBTTagCompound(); + texturasObjeto.setString("Value", textura); + texturas.add(texturasObjeto); + propiedades.set("textures", texturas); + skullOwnerCompound.set("Properties", propiedades); + + skullOwnerCompound.setString("Id", id); + + tag.set("SkullOwner", skullOwnerCompound); + cabeza.setTag(tag); + + + return org.bukkit.craftbukkit.v1_8_R1.inventory.CraftItemStack.asBukkitCopy(cabeza); + } +} diff --git a/src/mc/ajneb97/versiones/V1_8_R2.java b/src/mc/ajneb97/versiones/V1_8_R2.java new file mode 100644 index 0000000..0b6b33e --- /dev/null +++ b/src/mc/ajneb97/versiones/V1_8_R2.java @@ -0,0 +1,86 @@ +package mc.ajneb97.versiones; + +import java.util.ArrayList; +import java.util.List; + +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.SkullType; +import org.bukkit.block.Skull; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +public class V1_8_R2 { + + public void generarParticula(String particle, Location loc, float xOffset, float yOffset, float zOffset, float speed, int count, Player player){ + net.minecraft.server.v1_8_R2.EnumParticle enumParticle = net.minecraft.server.v1_8_R2.EnumParticle.valueOf(particle); + float x = (float)loc.getX(); + float y = (float)loc.getY(); + float z = (float)loc.getZ(); + + net.minecraft.server.v1_8_R2.PacketPlayOutWorldParticles packet = new net.minecraft.server.v1_8_R2.PacketPlayOutWorldParticles(enumParticle, false, x, y, z, xOffset, + yOffset, zOffset, speed, count, null); + + ((org.bukkit.craftbukkit.v1_8_R2.entity.CraftPlayer)player).getHandle().playerConnection.sendPacket(packet); + } + + @SuppressWarnings("deprecation") + public void setSkullBlock(Location locBloque,String id,String textura,int rot) { + net.minecraft.server.v1_8_R2.BlockPosition locDestino = new net.minecraft.server.v1_8_R2.BlockPosition(locBloque.getX(),locBloque.getY(),locBloque.getZ()); + locBloque.getBlock().setTypeIdAndData(144, (byte) 1, true); + + Skull skullBlock = (Skull) locBloque.getBlock().getState(); + skullBlock.setSkullType(SkullType.PLAYER); + skullBlock.update(); + + + net.minecraft.server.v1_8_R2.TileEntity te = ((org.bukkit.craftbukkit.v1_8_R2.CraftWorld)locBloque.getWorld()).getHandle().getTileEntity(locDestino); + net.minecraft.server.v1_8_R2.NBTTagCompound compound = new net.minecraft.server.v1_8_R2.NBTTagCompound(); + + te.b(compound); + net.minecraft.server.v1_8_R2.NBTTagCompound compoundSeleccionada = new net.minecraft.server.v1_8_R2.NBTTagCompound(); + net.minecraft.server.v1_8_R2.NBTTagCompound compoundOwner = new net.minecraft.server.v1_8_R2.NBTTagCompound(); + net.minecraft.server.v1_8_R2.NBTTagCompound compoundProperties = new net.minecraft.server.v1_8_R2.NBTTagCompound(); + net.minecraft.server.v1_8_R2.NBTTagList compoundTextures = new net.minecraft.server.v1_8_R2.NBTTagList(); + net.minecraft.server.v1_8_R2.NBTTagCompound compoundValue = new net.minecraft.server.v1_8_R2.NBTTagCompound(); + compoundValue.setString("Value", textura); + compoundTextures.add(compoundValue); + compoundProperties.set("textures", compoundTextures); + compoundOwner.set("Properties", compoundProperties); + compoundOwner.setString("Id", id); + compoundSeleccionada.setString("id", "Skull"); + compoundSeleccionada.set("Owner", compoundOwner); + compoundSeleccionada.setByte("Rot", (byte)rot); + compoundSeleccionada.setInt("x", locDestino.getX()); + compoundSeleccionada.setInt("y", locDestino.getY()); + compoundSeleccionada.setInt("z", locDestino.getZ()); + compoundSeleccionada.setByte("SkullType", (byte) 3); + te.a(compoundSeleccionada); + te.update(); + } + + public ItemStack getCabeza(ItemStack item, String id,String textura) { + net.minecraft.server.v1_8_R2.ItemStack cabeza = org.bukkit.craftbukkit.v1_8_R2.inventory.CraftItemStack.asNMSCopy(item); + net.minecraft.server.v1_8_R2.NBTTagCompound tag = cabeza.hasTag() ? cabeza.getTag() : new net.minecraft.server.v1_8_R2.NBTTagCompound(); + net.minecraft.server.v1_8_R2.NBTTagCompound skullOwnerCompound = new net.minecraft.server.v1_8_R2.NBTTagCompound(); + net.minecraft.server.v1_8_R2.NBTTagCompound propiedades = new net.minecraft.server.v1_8_R2.NBTTagCompound(); + + + net.minecraft.server.v1_8_R2.NBTTagList texturas = new net.minecraft.server.v1_8_R2.NBTTagList(); + net.minecraft.server.v1_8_R2.NBTTagCompound texturasObjeto = new net.minecraft.server.v1_8_R2.NBTTagCompound(); + texturasObjeto.setString("Value", textura); + texturas.add(texturasObjeto); + propiedades.set("textures", texturas); + skullOwnerCompound.set("Properties", propiedades); + + skullOwnerCompound.setString("Id", id); + + tag.set("SkullOwner", skullOwnerCompound); + cabeza.setTag(tag); + + + return org.bukkit.craftbukkit.v1_8_R2.inventory.CraftItemStack.asBukkitCopy(cabeza); + } +} diff --git a/src/mc/ajneb97/versiones/V1_8_R3.java b/src/mc/ajneb97/versiones/V1_8_R3.java new file mode 100644 index 0000000..35cc0c1 --- /dev/null +++ b/src/mc/ajneb97/versiones/V1_8_R3.java @@ -0,0 +1,133 @@ +package mc.ajneb97.versiones; + +import java.util.ArrayList; +import java.util.List; + +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.SkullType; +import org.bukkit.block.Skull; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +public class V1_8_R3 { + + /*BARRIER + BLOCK_CRACK + BLOCK_DUST + CLOUD + CRIT + CRIT_MAGIC + DAMAGE_INDICATOR + DRAGON_BREATH + DRIP_LAVA + DRIP_WATER + ENCHANTMENT_TABLE + END_ROD + EXPLOSION_HUGE + EXPLOSION_LARGE + EXPLOSION_NORMAL + FIREWORKS_SPARK + FLAME + FOOTSTEP + HEART + ITEM_CRACK + ITEM_TAKE + LAVA + MOB_APPEARANCE + NOTE + PORTAL + REDSTONE + SLIME + SMOKE_LARGE + SMOKE_NORMAL + SNOW_SHOVEL + SNOWBALL + SPELL + SPELL_INSTANT + SPELL_MOB + SPELL_MOB_AMBIENT + SPELL_WITCH + SUSPENDED + SUSPENDED_DEPTH + SWEEP_ATTACK + TOWN_AURA + VILLAGER_ANGRY + VILLAGER_HAPPY + WATER_BUBBLE + WATER_DROP + WATER_SPLASH + WATER_WAKE */ + + public void generarParticula(String particle, Location loc, float xOffset, float yOffset, float zOffset, float speed, int count, Player player){ + net.minecraft.server.v1_8_R3.EnumParticle enumParticle = net.minecraft.server.v1_8_R3.EnumParticle.valueOf(particle); + float x = (float)loc.getX(); + float y = (float)loc.getY(); + float z = (float)loc.getZ(); + + net.minecraft.server.v1_8_R3.PacketPlayOutWorldParticles packet = new net.minecraft.server.v1_8_R3.PacketPlayOutWorldParticles(enumParticle, false, x, y, z, xOffset, + yOffset, zOffset, speed, count, null); + + ((org.bukkit.craftbukkit.v1_8_R3.entity.CraftPlayer)player).getHandle().playerConnection.sendPacket(packet); + } + + @SuppressWarnings("deprecation") + public void setSkullBlock(Location locBloque,String id,String textura,int rot) { + net.minecraft.server.v1_8_R3.BlockPosition locDestino = new net.minecraft.server.v1_8_R3.BlockPosition(locBloque.getX(),locBloque.getY(),locBloque.getZ()); + locBloque.getBlock().setTypeIdAndData(144, (byte) 1, true); + + Skull skullBlock = (Skull) locBloque.getBlock().getState(); + skullBlock.setSkullType(SkullType.PLAYER); + skullBlock.update(); + + + net.minecraft.server.v1_8_R3.TileEntity te = ((org.bukkit.craftbukkit.v1_8_R3.CraftWorld)locBloque.getWorld()).getHandle().getTileEntity(locDestino); + net.minecraft.server.v1_8_R3.NBTTagCompound compound = new net.minecraft.server.v1_8_R3.NBTTagCompound(); + + te.b(compound); + net.minecraft.server.v1_8_R3.NBTTagCompound compoundSeleccionada = new net.minecraft.server.v1_8_R3.NBTTagCompound(); + net.minecraft.server.v1_8_R3.NBTTagCompound compoundOwner = new net.minecraft.server.v1_8_R3.NBTTagCompound(); + net.minecraft.server.v1_8_R3.NBTTagCompound compoundProperties = new net.minecraft.server.v1_8_R3.NBTTagCompound(); + net.minecraft.server.v1_8_R3.NBTTagList compoundTextures = new net.minecraft.server.v1_8_R3.NBTTagList(); + net.minecraft.server.v1_8_R3.NBTTagCompound compoundValue = new net.minecraft.server.v1_8_R3.NBTTagCompound(); + compoundValue.setString("Value", textura); + compoundTextures.add(compoundValue); + compoundProperties.set("textures", compoundTextures); + compoundOwner.set("Properties", compoundProperties); + compoundOwner.setString("Id", id); + compoundSeleccionada.setString("id", "Skull"); + compoundSeleccionada.set("Owner", compoundOwner); + compoundSeleccionada.setByte("Rot", (byte)rot); + compoundSeleccionada.setInt("x", locDestino.getX()); + compoundSeleccionada.setInt("y", locDestino.getY()); + compoundSeleccionada.setInt("z", locDestino.getZ()); + compoundSeleccionada.setByte("SkullType", (byte) 3); + te.a(compoundSeleccionada); + te.update(); + } + + public ItemStack getCabeza(ItemStack item, String id,String textura) { + net.minecraft.server.v1_8_R3.ItemStack cabeza = org.bukkit.craftbukkit.v1_8_R3.inventory.CraftItemStack.asNMSCopy(item); + net.minecraft.server.v1_8_R3.NBTTagCompound tag = cabeza.hasTag() ? cabeza.getTag() : new net.minecraft.server.v1_8_R3.NBTTagCompound(); + net.minecraft.server.v1_8_R3.NBTTagCompound skullOwnerCompound = new net.minecraft.server.v1_8_R3.NBTTagCompound(); + net.minecraft.server.v1_8_R3.NBTTagCompound propiedades = new net.minecraft.server.v1_8_R3.NBTTagCompound(); + + + net.minecraft.server.v1_8_R3.NBTTagList texturas = new net.minecraft.server.v1_8_R3.NBTTagList(); + net.minecraft.server.v1_8_R3.NBTTagCompound texturasObjeto = new net.minecraft.server.v1_8_R3.NBTTagCompound(); + texturasObjeto.setString("Value", textura); + texturas.add(texturasObjeto); + propiedades.set("textures", texturas); + skullOwnerCompound.set("Properties", propiedades); + + skullOwnerCompound.setString("Id", id); + + tag.set("SkullOwner", skullOwnerCompound); + cabeza.setTag(tag); + + + return org.bukkit.craftbukkit.v1_8_R3.inventory.CraftItemStack.asBukkitCopy(cabeza); + } +} diff --git a/src/mc/ajneb97/versiones/V1_9_R1.java b/src/mc/ajneb97/versiones/V1_9_R1.java new file mode 100644 index 0000000..027505c --- /dev/null +++ b/src/mc/ajneb97/versiones/V1_9_R1.java @@ -0,0 +1,86 @@ +package mc.ajneb97.versiones; + +import java.util.ArrayList; +import java.util.List; + +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.SkullType; +import org.bukkit.block.Skull; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +public class V1_9_R1 { + + public void generarParticula(String particle, Location loc, float xOffset, float yOffset, float zOffset, float speed, int count, Player player){ + net.minecraft.server.v1_9_R1.EnumParticle enumParticle = net.minecraft.server.v1_9_R1.EnumParticle.valueOf(particle); + float x = (float)loc.getX(); + float y = (float)loc.getY(); + float z = (float)loc.getZ(); + + net.minecraft.server.v1_9_R1.PacketPlayOutWorldParticles packet = new net.minecraft.server.v1_9_R1.PacketPlayOutWorldParticles(enumParticle, false, x, y, z, xOffset, + yOffset, zOffset, speed, count, null); + + ((org.bukkit.craftbukkit.v1_9_R1.entity.CraftPlayer)player).getHandle().playerConnection.sendPacket(packet); + } + + @SuppressWarnings("deprecation") + public void setSkullBlock(Location locBloque,String id,String textura,int rot) { + net.minecraft.server.v1_9_R1.BlockPosition locDestino = new net.minecraft.server.v1_9_R1.BlockPosition(locBloque.getX(),locBloque.getY(),locBloque.getZ()); + locBloque.getBlock().setTypeIdAndData(144, (byte) 1, true); + + Skull skullBlock = (Skull) locBloque.getBlock().getState(); + skullBlock.setSkullType(SkullType.PLAYER); + skullBlock.update(); + + + net.minecraft.server.v1_9_R1.TileEntity te = ((org.bukkit.craftbukkit.v1_9_R1.CraftWorld)locBloque.getWorld()).getHandle().getTileEntity(locDestino); + net.minecraft.server.v1_9_R1.NBTTagCompound compound = new net.minecraft.server.v1_9_R1.NBTTagCompound(); + + te.save(compound); + net.minecraft.server.v1_9_R1.NBTTagCompound compoundSeleccionada = new net.minecraft.server.v1_9_R1.NBTTagCompound(); + net.minecraft.server.v1_9_R1.NBTTagCompound compoundOwner = new net.minecraft.server.v1_9_R1.NBTTagCompound(); + net.minecraft.server.v1_9_R1.NBTTagCompound compoundProperties = new net.minecraft.server.v1_9_R1.NBTTagCompound(); + net.minecraft.server.v1_9_R1.NBTTagList compoundTextures = new net.minecraft.server.v1_9_R1.NBTTagList(); + net.minecraft.server.v1_9_R1.NBTTagCompound compoundValue = new net.minecraft.server.v1_9_R1.NBTTagCompound(); + compoundValue.setString("Value", textura); + compoundTextures.add(compoundValue); + compoundProperties.set("textures", compoundTextures); + compoundOwner.set("Properties", compoundProperties); + compoundOwner.setString("Id", id); + compoundSeleccionada.setString("id", "Skull"); + compoundSeleccionada.set("Owner", compoundOwner); + compoundSeleccionada.setByte("Rot", (byte)rot); + compoundSeleccionada.setInt("x", locDestino.getX()); + compoundSeleccionada.setInt("y", locDestino.getY()); + compoundSeleccionada.setInt("z", locDestino.getZ()); + compoundSeleccionada.setByte("SkullType", (byte) 3); + te.a(compoundSeleccionada); + te.update(); + } + + public ItemStack getCabeza(ItemStack item, String id,String textura) { + net.minecraft.server.v1_9_R1.ItemStack cabeza = org.bukkit.craftbukkit.v1_9_R1.inventory.CraftItemStack.asNMSCopy(item); + net.minecraft.server.v1_9_R1.NBTTagCompound tag = cabeza.hasTag() ? cabeza.getTag() : new net.minecraft.server.v1_9_R1.NBTTagCompound(); + net.minecraft.server.v1_9_R1.NBTTagCompound skullOwnerCompound = new net.minecraft.server.v1_9_R1.NBTTagCompound(); + net.minecraft.server.v1_9_R1.NBTTagCompound propiedades = new net.minecraft.server.v1_9_R1.NBTTagCompound(); + + + net.minecraft.server.v1_9_R1.NBTTagList texturas = new net.minecraft.server.v1_9_R1.NBTTagList(); + net.minecraft.server.v1_9_R1.NBTTagCompound texturasObjeto = new net.minecraft.server.v1_9_R1.NBTTagCompound(); + texturasObjeto.setString("Value", textura); + texturas.add(texturasObjeto); + propiedades.set("textures", texturas); + skullOwnerCompound.set("Properties", propiedades); + + skullOwnerCompound.setString("Id", id); + + tag.set("SkullOwner", skullOwnerCompound); + cabeza.setTag(tag); + + + return org.bukkit.craftbukkit.v1_9_R1.inventory.CraftItemStack.asBukkitCopy(cabeza); + } +} diff --git a/src/mc/ajneb97/versiones/V1_9_R2.java b/src/mc/ajneb97/versiones/V1_9_R2.java new file mode 100644 index 0000000..bdceab9 --- /dev/null +++ b/src/mc/ajneb97/versiones/V1_9_R2.java @@ -0,0 +1,86 @@ +package mc.ajneb97.versiones; + +import java.util.ArrayList; +import java.util.List; + +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.SkullType; +import org.bukkit.block.Skull; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +public class V1_9_R2 { + + public void generarParticula(String particle, Location loc, float xOffset, float yOffset, float zOffset, float speed, int count, Player player){ + net.minecraft.server.v1_9_R2.EnumParticle enumParticle = net.minecraft.server.v1_9_R2.EnumParticle.valueOf(particle); + float x = (float)loc.getX(); + float y = (float)loc.getY(); + float z = (float)loc.getZ(); + + net.minecraft.server.v1_9_R2.PacketPlayOutWorldParticles packet = new net.minecraft.server.v1_9_R2.PacketPlayOutWorldParticles(enumParticle, false, x, y, z, xOffset, + yOffset, zOffset, speed, count, null); + + ((org.bukkit.craftbukkit.v1_9_R2.entity.CraftPlayer)player).getHandle().playerConnection.sendPacket(packet); + } + + @SuppressWarnings("deprecation") + public void setSkullBlock(Location locBloque,String id,String textura,int rot) { + net.minecraft.server.v1_9_R2.BlockPosition locDestino = new net.minecraft.server.v1_9_R2.BlockPosition(locBloque.getX(),locBloque.getY(),locBloque.getZ()); + locBloque.getBlock().setTypeIdAndData(144, (byte) 1, true); + + Skull skullBlock = (Skull) locBloque.getBlock().getState(); + skullBlock.setSkullType(SkullType.PLAYER); + skullBlock.update(); + + + net.minecraft.server.v1_9_R2.TileEntity te = ((org.bukkit.craftbukkit.v1_9_R2.CraftWorld)locBloque.getWorld()).getHandle().getTileEntity(locDestino); + net.minecraft.server.v1_9_R2.NBTTagCompound compound = new net.minecraft.server.v1_9_R2.NBTTagCompound(); + + te.save(compound); + net.minecraft.server.v1_9_R2.NBTTagCompound compoundSeleccionada = new net.minecraft.server.v1_9_R2.NBTTagCompound(); + net.minecraft.server.v1_9_R2.NBTTagCompound compoundOwner = new net.minecraft.server.v1_9_R2.NBTTagCompound(); + net.minecraft.server.v1_9_R2.NBTTagCompound compoundProperties = new net.minecraft.server.v1_9_R2.NBTTagCompound(); + net.minecraft.server.v1_9_R2.NBTTagList compoundTextures = new net.minecraft.server.v1_9_R2.NBTTagList(); + net.minecraft.server.v1_9_R2.NBTTagCompound compoundValue = new net.minecraft.server.v1_9_R2.NBTTagCompound(); + compoundValue.setString("Value", textura); + compoundTextures.add(compoundValue); + compoundProperties.set("textures", compoundTextures); + compoundOwner.set("Properties", compoundProperties); + compoundOwner.setString("Id", id); + compoundSeleccionada.setString("id", "Skull"); + compoundSeleccionada.set("Owner", compoundOwner); + compoundSeleccionada.setByte("Rot", (byte)rot); + compoundSeleccionada.setInt("x", locDestino.getX()); + compoundSeleccionada.setInt("y", locDestino.getY()); + compoundSeleccionada.setInt("z", locDestino.getZ()); + compoundSeleccionada.setByte("SkullType", (byte) 3); + te.a(compoundSeleccionada); + te.update(); + } + + public ItemStack getCabeza(ItemStack item, String id,String textura) { + net.minecraft.server.v1_9_R2.ItemStack cabeza = org.bukkit.craftbukkit.v1_9_R2.inventory.CraftItemStack.asNMSCopy(item); + net.minecraft.server.v1_9_R2.NBTTagCompound tag = cabeza.hasTag() ? cabeza.getTag() : new net.minecraft.server.v1_9_R2.NBTTagCompound(); + net.minecraft.server.v1_9_R2.NBTTagCompound skullOwnerCompound = new net.minecraft.server.v1_9_R2.NBTTagCompound(); + net.minecraft.server.v1_9_R2.NBTTagCompound propiedades = new net.minecraft.server.v1_9_R2.NBTTagCompound(); + + + net.minecraft.server.v1_9_R2.NBTTagList texturas = new net.minecraft.server.v1_9_R2.NBTTagList(); + net.minecraft.server.v1_9_R2.NBTTagCompound texturasObjeto = new net.minecraft.server.v1_9_R2.NBTTagCompound(); + texturasObjeto.setString("Value", textura); + texturas.add(texturasObjeto); + propiedades.set("textures", texturas); + skullOwnerCompound.set("Properties", propiedades); + + skullOwnerCompound.setString("Id", id); + + tag.set("SkullOwner", skullOwnerCompound); + cabeza.setTag(tag); + + + return org.bukkit.craftbukkit.v1_9_R2.inventory.CraftItemStack.asBukkitCopy(cabeza); + } +}