05-14-2013, 03:53 PM
Люди, кто сталкивался с этим? Регестрируешься на бой, делаешь релог, и вауля у тебя в 2 раза больше предметов, чем ставка... т.е ставишь 10 КОЛ, делаешь релог и в инвентаре 20 КОЛ... кто может помочь с фиксом? Хотя бы так, что бы при ставке заберало вещь из инвентаря...
Вот исходы:
FightClub.java
FightClubArena.java
FightClubManagerInstance.java
Вот исходы:
FightClub.java
Код:
public class FightClub extends Functions implements ScriptFile, OnPlayerExitListener, OnTeleportListener
{
private static Logger _log = LoggerFactory.getLogger(FightClub.class);
private static Map<Long, Rate> _ratesMap;
private static List<FightClubArena> _fights;
protected static List<Long> _inBattle;
private static Map<Long, Location> _restoreCoord;
private static List<Long> _inList;
private static StringBuilder _itemsList;
private static Map<String, Integer> _allowedItems;
private static Location _player1loc;
private static Location _player2loc;
private static boolean _isCreateBattle = false;
private static final ArrayList<SimpleSpawner> _spawns_fight_club_manager = new ArrayList<SimpleSpawner>();
private static int FIGHT_CLUB_MANAGER = 112;
private void spawnFightClub()
{
final int FIGHT_CLUB_MANAGER_SPAWN[][] = {
// { 82042, 149711, -3356, 58312 }, // Giran
// { 146408, 28536, -2255, 33600 }, // Aden 1
// { 148504, 28536, -2255, 33600 }, // Aden 2
// { 145800, -57112, -2966, 32500 }, //Goddard 1
// { 150120, -56504, -2966, 32500 }, //Goddard 2
// { 43656, -46792, -784, 17000 }, //Rune
// { 19448, 145048, -3094, 16500 }, //Dion 1
// { 17832, 144312, -3037, 16500 }, //Dion 2
// { 82888, 55304, -1511, 16500 }, //Oren 1
// { 80104, 53608, -1547, 16500 }, //Oren 2
// { -15064, 124296, -3104, 16500 }, //Gludio 1
// { -12184, 122552, -3086, 16500 }, //Gludio 2
// { -82648, 149896, -3115, 33600 }, //Gludin 1
// { -81800, 155368, -3163, 58312 }, //Gludin 2
// { 89272, -141592, -1525, 32500 }, //Shuttgart 1
// { 87672, -140776, -1525, 32500 }, //Shuttgart 2
// { 115496, 218728, -3648, 16500 }, //Heine 1
// { 107384, 217704, -3661, 16500 }, //Heine 2
// { 116808, 75448, -2748, 16500 }, //Hunter's Village
};
SpawnNPCs(FIGHT_CLUB_MANAGER, FIGHT_CLUB_MANAGER_SPAWN, _spawns_fight_club_manager);
}
@Override
public void onLoad()
{
if(!Config.FIGHT_CLUB_ENABLED)
return;
spawnFightClub();
CharListenerList.addGlobal(this);
_ratesMap = new HashMap<Long, Rate>();
_fights = new ArrayList<FightClubArena>();
_restoreCoord = new HashMap<Long, Location>();
_inBattle = new ArrayList<Long>();
_inList = new ArrayList<Long>();
_itemsList = new StringBuilder();
_allowedItems = new HashMap<String, Integer>();
for(int i = 0; i < Config.ALLOWED_RATE_ITEMS.length; i++)
{
String itemName = ItemFunctions.createItem(Integer.parseInt(Config.ALLOWED_RATE_ITEMS[i])).getTemplate().getName();
_itemsList.append(itemName).append(";");
_allowedItems.put(itemName, Integer.parseInt(Config.ALLOWED_RATE_ITEMS[i]));
}
_log.info("Loaded Event: Fight Club");
}
@Override
public void onTeleport(Player player, int x, int y, int z, Reflection reflection)
{
if(player.getTeam() != TeamType.NONE && _inBattle.contains(player.getStoredId()))
removePlayer(player);
}
/**
* Удаляет всю информацию об игроке
* @param player - ссылка на удаляемого игрока
*/
private static void removePlayer(Player player)
{
if(player != null)
{
player.setTeam(TeamType.NONE);
if(_inBattle.contains(player.getStoredId()))
_inBattle.remove(player.getStoredId());
if(_inList.contains(player.getStoredId()))
{
_ratesMap.remove(player.getStoredId());
_inList.remove(player.getStoredId());
}
if(_restoreCoord.containsKey(player.getStoredId()))
_restoreCoord.remove(player.getStoredId());
}
}
public static Location getRestoreLocation(Player player)
{
return _restoreCoord.get(player.getStoredId());
}
public static Player getPlayer(long playerStoredI)
{
return GameObjectsStorage.getAsPlayer(playerStoredI);
}
@Override
public void onPlayerExit(Player player)
{
removePlayer(player);
}
@Override
public void onReload()
{
_isCreateBattle = false;
_fights.clear();
_ratesMap.clear();
_inBattle.clear();
_inList.clear();
onLoad();
}
@Override
public void onShutdown()
{
if(!Config.FIGHT_CLUB_ENABLED)
return;
_isCreateBattle = false;
_fights.clear();
_ratesMap.clear();
_inBattle.clear();
_inList.clear();
}
public static String addApplication(Player player, String item, int count)
{
if(player == null)
return null;
if(!checkPlayer(player, true))
return null;
if(isRegistered(player))
return "reg";
if(getItemCount(player, _allowedItems.get(item)) < count)
{
show(new CustomMessage("scripts.events.fightclub.CancelledItems", player), player);
return "NoItems";
}
final Rate rate = new Rate(player, _allowedItems.get(item), count);
final StringBuilder stRate = new StringBuilder();
stRate.append(_allowedItems.get(item)).append(";").append(count).append(";");
_ratesMap.put(player.getStoredId(), rate);
_inList.add(0, player.getStoredId());
if(Config.FIGHT_CLUB_ANNOUNCE_RATE)
{
final String[] args = { String.valueOf(player.getName()), String.valueOf(player.getLevel()), String.valueOf(rate.getItemCount()), String.valueOf(item) };
sayToAll("scripts.events.fightclub.Announce", args);
if(Config.FIGHT_CLUB_ANNOUNCE_RATE_TO_SCREEN)
sayToAllPlayers("scripts.events.fightclub.Announce", player, item, count, true);
}
player.setVar("FightClubRate", stRate.toString(), -1);
return "OK";
}
public static void backItemsPlayers()
{
for(Player player : getPlayers(_inList))
{
final int itemId = _ratesMap.get(player.getStoredId()).getItemId();
final int itemCount = _ratesMap.get(player.getStoredId()).getItemCount();
if(player.isOnline())
addItem(player, itemId, itemCount);
}
}
public static void backItemsPlayer(Player player)
{
final int itemId = _ratesMap.get(player.getStoredId()).getItemId();
final int itemCount = _ratesMap.get(player.getStoredId()).getItemCount();
if(player.isOnline())
addItem(player, itemId, itemCount);
}
/**
* Отправляет ConfirmDlg
* @param requested - игрок, выставивший заявку. <b>Ему</b> отправляется запрос
* @param requester - игрок, выбравший из списка соперника. <b>От него</b> отправляется запрос
*/
public static boolean requestConfirmation(Player requested, Player requester)
{
if(!checkPlayer(requested, true))
return false;
if(!checkPlayer(requester, true))
return false;
if((requested.getLevel() - requester.getLevel()) > Config.MAXIMUM_LEVEL_DIFFERENCE || (requester.getLevel() - requested.getLevel()) > Config.MAXIMUM_LEVEL_DIFFERENCE)
{
show(new CustomMessage("scripts.events.fightclub.CancelledLevel", requester, Config.MINIMUM_LEVEL_TO_PARRICIPATION, Config.MAXIMUM_LEVEL_TO_PARRICIPATION, Config.MAXIMUM_LEVEL_DIFFERENCE), requester);
return false;
}
Object[] duelists = { requested, requester };
requested.scriptRequest(new CustomMessage("scripts.events.fightclub.AskPlayer", requested, requester.getName(), requester.getLevel()).toString(), "events.FightClub.FightClub:doStart", duelists);
final StringBuilder stRate = new StringBuilder();
final int itemId = _ratesMap.get(requested.getStoredId()).getItemId();
final int itemCount = _ratesMap.get(requested.getStoredId()).getItemCount();
stRate.append(itemId).append(";").append(itemCount).append(";");
requester.setVar("FightClubRate", stRate.toString(), -1);
return true;
}
public static void sayToAll(String address, String[] replacements){
Announcements.getInstance().announceByCustomMessage(address, replacements, ChatType.CRITICAL_ANNOUNCE);}
/**
* Проверка игроков для последующего создания арены для них
* @param requested - игрок, выставивший заявку. <b>Ему</b> отправляется запрос
* @param requester - игрок, выбравший из списка соперника. <b>От него</b> отправляется запрос
*/
public static void doStart(Player requested, Player requester)
{
final int itemId = _ratesMap.get(requested.getStoredId()).getItemId();
final int itemCount = _ratesMap.get(requested.getStoredId()).getItemCount();
if(!checkPrepare(requested, requester, itemId, itemCount))
return;
if(!checkPlayer(requested, false))
return;
if(!checkPlayer(requester, true))
return;
removeItem(requested, itemId, itemCount);
removeItem(requester, itemId, itemCount);
_inList.remove(requested.getStoredId());
_ratesMap.remove(requested.getStoredId());
_restoreCoord.put(requested.getStoredId(), new Location(requested.getX(), requested.getY(), requested.getZ()));
_restoreCoord.put(requester.getStoredId(), new Location(requester.getX(), requester.getY(), requester.getZ()));
_isCreateBattle = true;
createBattle(requested, requester, itemId, itemCount);
}
private static boolean checkPrepare(Player requested, Player requester, int itemId, int itemCount)
{
if(requested.getVar("FightClubRate") == null)
{
show(new CustomMessage("scripts.events.fightclub.CancelledItems", requested), requested);
show(new CustomMessage("scripts.events.fightclub.CancelledOpponent", requester), requester);
return false;
}
if(getItemCount(requester, itemId) < itemCount)
{
show(new CustomMessage("scripts.events.fightclub.CancelledItems", requester), requester);
return false;
}
if(getItemCount(requested, itemId) < itemCount)
{
show(new CustomMessage("scripts.events.fightclub.CancelledItems", requested), requested);
return false;
}
if(requester.getVar("FightClubRate") == null)
{
show(new CustomMessage("scripts.events.fightclub.CancelledItems", requester), requester);
return false;
}
if(_inBattle.contains(requested.getStoredId()))
{
show(new CustomMessage("scripts.events.fightclub.CancelledOpponent", requester), requested);
return false;
}
if(requester.isInOfflineMode())
{
show(new CustomMessage("scripts.events.fightclub.CancelledOffline", requested), requested);
return false;
}
if(requested.isInOfflineMode())
{
show(new CustomMessage("scripts.events.fightclub.CancelledOffline", requester), requester);
return false;
}
return true;
}
private static void createBattle(Player player1, Player player2, int itemId, int itemCount)
{
_inBattle.add(player1.getStoredId());
_inBattle.add(player2.getStoredId());
final FightClubArena _arena = new FightClubArena(player1, player2, itemId, itemCount, new Reflection());
_fights.add(_arena);
}
public static void deleteArena(FightClubArena arena)
{
removePlayer(arena.getPlayer1());
removePlayer(arena.getPlayer2());
arena.getReflection().collapse();
_fights.remove(arena);
}
public static boolean checkPlayer(Player player, boolean first)
{
if(first && player.isDead())
{
show(new CustomMessage("scripts.events.fightclub.CancelledDead", player), player);
return false;
}
if(first && player.getTeam() != TeamType.NONE)
{
show(new CustomMessage("scripts.events.fightclub.CancelledOtherEvent", player), player);
return false;
}
if(player.getLevel() < Config.MINIMUM_LEVEL_TO_PARRICIPATION || player.getLevel() > Config.MAXIMUM_LEVEL_TO_PARRICIPATION)
{
show(new CustomMessage("scripts.events.fightclub.CancelledLevel", player), player);
return false;
}
if(player.isMounted())
{
show(new CustomMessage("scripts.events.fightclub.Cancelled", player), player);
return false;
}
if(player.isCursedWeaponEquipped())
{
show(new CustomMessage("scripts.events.fightclub.Cancelled", player), player);
return false;
}
if(player.isInDuel())
{
show(new CustomMessage("scripts.events.fightclub.CancelledDuel", player), player);
return false;
}
if(player.getOlympiadGame() != null || first && Olympiad.isRegistered(player))
{
show(new CustomMessage("scripts.events.fightclub.CancelledOlympiad", player), player);
return false;
}
if(player.isInParty() && player.getParty().isInDimensionalRift())
{
show(new CustomMessage("scripts.events.fightclub.CancelledOtherEvent", player), player);
return false;
}
if(player.isInObserverMode())
{
show(new CustomMessage("scripts.event.fightclub.CancelledObserver", player), player);
return false;
}
if(player.isTeleporting())
{
show(new CustomMessage("scripts.events.fightclub.CancelledTeleport", player), player);
return false;
}
return true;
}
/**
* Приватный метод. Возващает true, если игрок зарегистрировал ставку
* @param player - ссылка на проверяемого игрока
* @return - true, если зарегистрирован
*/
private static boolean isRegistered(Player player)
{
if(_inList.contains(player.getStoredId()))
return true;
return false;
}
/**
* Возвращает объект класса {@link Rate}, содержащий параметры "заявки"
* <b> Метод для использования в FightClubInstanceManager! </b>
* @param index
* @return объект, содержащий заявку
*/
public static Rate getRateByIndex(int index)
{
return _ratesMap.get(_inList.get(index));
}
/**
* Возвращает объект класса {@link Rate}, содержащий параметры "заявки"
* <b> Метод для использования в FightClubInstanceManager! </b>
* @param index
* @return объект, содержащий заявку
*/
public static Rate getRateByStoredId(long storedId)
{
return _ratesMap.get(storedId);
}
/**
* Возвращает через ; имена предметов,
* разрешенных в качестве ставки.
* <b> Метод для использования в FightClubInstanceManager! </b>
* @return список предметов через ";"
*/
public static String getItemsList()
{
return _itemsList.toString();
}
/**
* <b> Метод для использования в FightClubInstanceManager! </b>
* @param playerObject - ссылка на игрока
* @return true, если игрок зарегистрировал ставку
*/
public static boolean isRegistered(Object playerObject)
{
if(_ratesMap.containsKey(((Player) playerObject).getStoredId()))
return true;
return false;
}
/**
* Удаляет регистрацию игрока в списке через метод {@link #removePlayer(Player)}
* <b> Метод для использования в FightClubInstanceManager! </b>
* @param playerObject ссылка на игрока
*/
public static void deleteRegistration(Player player)
{
//backItemsPlayer(player);
player.unsetVar("FightClubRate");
removePlayer(player);
}
public static boolean isCreateBattle(Object playerObject)
{
return _isCreateBattle;
}
/**
* Возвращает количеств игроков, сделавших свои ставки
* <b> Метод для использования в FightClubInstanceManager! </b>
* @return - количество игроков, сделавших ставки
*/
public static int getRatesCount()
{
return _inList.size();
}
/**
* Телепортирует игроков на сохраненные координаты
* @param player1
* @param player2
*/
public static void teleportPlayersBack(Player player1, Player player2, Object obj)
{
teleportPlayerBack(player1);
teleportPlayerBack(player2);
}
private static void teleportPlayerBack(Player player)
{
if (player == null)
return;
if (player.getPet() != null)
player.getPet().getEffectList().stopAllEffects();
player.setCurrentCp(player.getMaxCp());
player.setCurrentMp(player.getMaxMp());
if(player.isDead())
{
player.setCurrentHp(player.getMaxHp(), true);
player.broadcastPacket(new Revive(player));
}
else
{
player.setCurrentHp(player.getMaxHp(), false);
}
if(Config.REMOVE_CLAN_SKILLS && player.getClan() != null)
{
for(final Skill skill : player.getClan().getAllSkills())
player.addSkill(skill);
}
if(Config.REMOVE_HERO_SKILLS && player.isHero())
Hero.getInstance().addSkills(player);
if ((player != null) && (_restoreCoord.containsKey(player.getStoredId())))
player.teleToLocation(_restoreCoord.get(player.getStoredId()), ReflectionManager.DEFAULT);
}
/**
* Выводит текст по центру экрана. Выводит нескольким игрокам.
* Положение - TOP_CENTER
* @param address - адрес текста
* @param arg - параметр замены (один)
* @param bigFont - большой шрифт
* @param players - СЃРїРёСЃРѕРє РёРіСЂРѕРєРѕРІ
*/
protected static void sayToPlayers(String address, Object arg, boolean bigFont, Player... players)
{
for(Player player : players)
{
final CustomMessage sm = new CustomMessage(address, player, arg);
player.sendPacket(new ExShowScreenMessage(sm.toString(), 3000, ScreenMessageAlign.TOP_CENTER, bigFont));
}
}
protected static void sayToAllPlayers(String address, Player player, String item, int count, boolean bigFont)
{
for(Player _player : GameObjectsStorage.getAllPlayersForIterate())
{
final CustomMessage sm = new CustomMessage(address, _player);
final String[] args = { String.valueOf(player.getName()), String.valueOf(player.getLevel()), String.valueOf(count), String.valueOf(item) };
_player.sendPacket(new ExShowScreenMessage(sm.add(args).toString(), 3000, ScreenMessageAlign.TOP_CENTER, bigFont));
}
}
protected static void sayStartToAllPlayers(String address, Player player1, Player player2, String item, int count, boolean bigFont)
{
for(Player _player : GameObjectsStorage.getAllPlayersForIterate())
{
final CustomMessage sm = new CustomMessage(address, _player);
final String[] args = { String.valueOf(player1.getName()), String.valueOf(player2.getName()), String.valueOf(count * 2), String.valueOf(item) };
_player.sendPacket(new ExShowScreenMessage(sm.add(args).toString(), 3000, ScreenMessageAlign.TOP_CENTER, bigFont));
}
}
/**
* Выводит текст по центру экрана. Выводит нескольким игрокам.
* Положение - TOP_CENTER
* @param address - адрес текста
* @param bigFont - большой шрифт
* @param players - СЃРїРёСЃРѕРє РёРіСЂРѕРєРѕРІ
*/
protected static void sayToPlayers(String address, boolean bigFont, Player... players)
{
for(Player player : players)
{
final CustomMessage sm = new CustomMessage(address, player);
player.sendPacket(new ExShowScreenMessage(sm.toString(), 3000, ScreenMessageAlign.TOP_CENTER, bigFont));
}
}
/**
* Выводит текст по центру экрана. Положение - TOP_CENTER
* @param player - целевой игрок
* @param address - адрес текста
* @param bigFont - большой шрифт
* @param args - параметры замены текста
*/
protected static void sayToPlayer(Player player, String address, boolean bigFont, Object... args)
{
player.sendPacket(new ExShowScreenMessage(new CustomMessage(address, player, args).toString(), 3000, ScreenMessageAlign.TOP_CENTER, bigFont));
}
/**
* Возрождает мёртвых игроков
*/
public static void resurrectPlayers(Player player1, Player player2, Object obj)
{
if(player1.isDead())
{
player1.restoreExp();
player1.setCurrentCp(player1.getMaxCp());
player1.setCurrentHp(player1.getMaxHp(), true);
player1.setCurrentMp(player1.getMaxMp());
player1.broadcastPacket(new Revive(player1));
}
if(player2.isDead())
{
player2.restoreExp();
player2.setCurrentCp(player2.getMaxCp());
player2.setCurrentHp(player2.getMaxHp(), true);
player2.setCurrentMp(player2.getMaxMp());
player2.broadcastPacket(new Revive(player2));
}
}
/**
* Восстанавливает HP/MP/CP участникам
*/
public void healPlayers(Player player1, Player player2, Object obj)
{
player1.setCurrentCp(player1.getMaxCp());
player1.setCurrentHpMp(player1.getMaxHp(), player1.getMaxMp());
player2.setCurrentCp(player2.getMaxCp());
player2.setCurrentHpMp(player2.getMaxHp(), player2.getMaxMp());
}
/**
* Запускает битву между игроками.
* @param player1
* @param player2
*/
protected static void startBattle(Player player1, Player player2)
{
player1.setTeam(TeamType.BLUE);
player2.setTeam(TeamType.RED);
sayToPlayers("scripts.events.fightclub.Start", true, player1, player2);
}
@SuppressWarnings("static-access")
public static void teleportPlayersToColliseum(Player player1, Player player2, Reflection reflection)
{
player1.block();
unRide(player1);
if(Config.UNSUMMON_PETS)
unSummonPet(player1, true);
if(Config.UNSUMMON_SUMMONS)
unSummonPet(player1, false);
if(player1.isInvisible())
player1.setInvisibleType(InvisibleType.NONE);
if(Config.REMOVE_CLAN_SKILLS && player1.getClan() != null)
{
for(final Skill skill : player1.getClan().getAllSkills())
player1.removeSkill(skill);
}
if(Config.REMOVE_HERO_SKILLS && player1.isHero())
Hero.getInstance().removeSkills(player1);
if(Config.CANCEL_BUFF_BEFORE_FIGHT)
{
player1.getEffectList().stopAllEffects();
if(player1.getPet() != null)
player1.getPet().getEffectList().stopAllEffects();
}
player1.teleToLocation(Location.findPointToStay(reflection.getInstancedZone().getTeleportCoords().get(0), 50, 50, reflection.getGeoIndex()), reflection);
player1.unblock();
player2.block();
unRide(player2);
if(Config.UNSUMMON_PETS)
unSummonPet(player2, true);
if(Config.UNSUMMON_SUMMONS)
unSummonPet(player2, false);
if(player2.isInvisible())
player2.setInvisibleType(InvisibleType.NONE);
if(Config.REMOVE_CLAN_SKILLS && player2.getClan() != null)
{
for(final Skill skill : player2.getClan().getAllSkills())
player2.removeSkill(skill);
}
if(Config.REMOVE_HERO_SKILLS && player2.isHero())
Hero.getInstance().removeSkills(player2);
if(Config.CANCEL_BUFF_BEFORE_FIGHT)
{
player2.getEffectList().stopAllEffects();
if(player2.getPet() != null)
player2.getPet().getEffectList().stopAllEffects();
}
player2.teleToLocation(Location.findPointToStay(reflection.getInstancedZone().getTeleportCoords().get(1), 50, 50, reflection.getGeoIndex()), reflection);
player2.unblock();
}
protected static class TeleportTask extends RunnableImpl
{
private Player player;
private Location location;
public TeleportTask(Player player, Location location)
{
this.player = player;
this.location = location;
player.block();
}
@Override
public void runImpl() throws Exception
{
player.teleToLocation(location);
player.unblock();
}
}
private static List<Player> getPlayers(List<Long> list)
{
List<Player> result = new ArrayList<Player>();
for(Long storeId : list)
{
Player player = GameObjectsStorage.getAsPlayer(storeId);
if(player != null)
result.add(player);
}
return result;
}
}
Код:
public class FightClubArena extends FightClub implements OnDeathListener, OnPlayerExitListener
{
protected static final String CLASS_NAME = "events.FightClub.FightClub";
private ScheduledFuture<?> _endTask;
public static ScheduledFuture<?> _startTask;
private boolean _isEnded = false;
private Player _player1;
private Player _player2;
private static int _itemId;
private static int _itemCount;
private static Reflection _reflection;
private InstantZone _instantZone = InstantZoneHolder.getInstance().getInstantZone(Rnd.get(607, 610));
public FightClubArena(Player player1, Player player2, int itemId, int itemCount, Reflection reflection)
{
CharListenerList.addGlobal(this);
_player1 = player1;
_player2 = player2;
_itemId = itemId;
_itemCount = itemCount;
_reflection = reflection;
_reflection.init(_instantZone);
initBattle();
}
/**
* Вызывается при выходе игрока
*/
@Override
public void onPlayerExit(Player player)
{
if((player.getStoredId() == _player1.getStoredId() || player.getStoredId() == _player2.getStoredId()) && !_isEnded)
{
stopEndTask();
setLoose((Player) player);
}
}
/**
* Вызывается при смерти игрока
*/
@Override
public void onDeath(Creature actor, Creature killer)
{
if((actor.getStoredId() == _player1.getStoredId() || actor.getStoredId() == _player2.getStoredId()) && !_isEnded)
{
stopEndTask();
setLoose((Player) actor);
}
}
private void stopEndTask()
{
_endTask.cancel(false);
_endTask = ThreadPoolManager.getInstance().schedule(new EndTask(), 3000);
}
/**
* Запускает таймеры боя
*/
private void initBattle()
{
final Object[] args = { _player1, _player2, _reflection };
_startTask = ThreadPoolManager.getInstance().scheduleAtFixedDelay(new StartTask(_player1, _player2), Config.ARENA_TELEPORT_DELAY * 1000, 1000);
_endTask = ThreadPoolManager.getInstance().schedule(new EndTask(), ((Config.ARENA_TELEPORT_DELAY + Config.FIGHT_TIME)) * 1000);
sayToPlayers("scripts.events.fightclub.TeleportThrough", Config.ARENA_TELEPORT_DELAY, false, _player1, _player2);
executeTask(CLASS_NAME, "resurrectPlayers", args, Config.ARENA_TELEPORT_DELAY * 1000 - 600);
executeTask(CLASS_NAME, "healPlayers", args, Config.ARENA_TELEPORT_DELAY * 1000 - 500);
executeTask(CLASS_NAME, "teleportPlayersToColliseum", args, Config.ARENA_TELEPORT_DELAY * 1000);
}
/**
* Удаляет ауру у игроков
*/
private void removeAura()
{
_player1.setTeam(TeamType.NONE);
_player2.setTeam(TeamType.NONE);
}
/**
* Выдаёт награду
*/
private void giveReward(Player player)
{
final String name = ItemFunctions.createItem(_itemId).getTemplate().getName();
sayToPlayer(player, "scripts.events.fightclub.YouWin", false, _itemCount * 2, name);
addItem(player, _itemId, _itemCount * 2);
}
private static String getItemName()
{
final String name = ItemFunctions.createItem(_itemId).getTemplate().getName();
return name;
}
private static int getItemCount()
{
return _itemCount;
}
/**
* Выводит скорбящее сообщение проигравшему ;)
* @param player
*/
private void setLoose(Player player)
{
if(player.getStoredId() == _player1.getStoredId())
giveReward(_player2);
else if(player.getStoredId() == _player2.getStoredId())
giveReward(_player1);
_player1.unsetVar("FightClubRate");
_player2.unsetVar("FightClubRate");
_isEnded = true;
sayToPlayer(player, "scripts.events.fightclub.YouLoose", false, new Object[0]);
}
/**
* Метод, вызываемый РїСЂРё ничьей. Р-ассчитывает победителя или объявлет ничью.
*/
private void draw()
{
if(!Config.ALLOW_DRAW && _player1.getCurrentCp() != _player1.getMaxCp() || _player2.getCurrentCp() != _player2.getMaxCp() || _player1.getCurrentHp() != _player1.getMaxHp() || _player2.getCurrentHp() != _player2.getMaxHp())
{
if(_player1.getCurrentHp() != _player1.getMaxHp() || _player2.getCurrentHp() != _player2.getMaxHp())
{
if(_player1.getMaxHp() / _player1.getCurrentHp() > _player2.getMaxHp() / _player2.getCurrentHp())
{
giveReward(_player1);
setLoose(_player2);
return;
}
else
{
giveReward(_player2);
setLoose(_player1);
return;
}
}
else
{
if(_player1.getMaxCp() / _player1.getCurrentCp() > _player2.getMaxCp() / _player2.getCurrentCp())
{
giveReward(_player1);
setLoose(_player2);
return;
}
else
{
giveReward(_player2);
setLoose(_player1);
return;
}
}
}
sayToPlayers("scripts.events.fightclub.Draw", true, _player1, _player2);
addItem(_player1, _itemId, _itemCount);
addItem(_player2, _itemId, _itemCount);
}
/**
* Возващает ссылку на первого игрока
* @return - ссылка на игрока
*/
protected Player getPlayer1()
{
return _player1;
}
/**
* Возващает ссылку на второго игрока
* @return - ссылка на игрока
*/
protected Player getPlayer2()
{
return _player2;
}
/**
* Возвращает отражение
* @return - reflection
*/
protected Reflection getReflection()
{
return _reflection;
}
/**
* Вызывает метод суперкласса, удаляющий рефлекшен
* @param arena - ссылка на арену
*/
private void delete(long delay)
{
final FightClubArena[] arg = { this };
executeTask(CLASS_NAME, "deleteArena", arg, delay);
}
protected static class StartTask extends RunnableImpl
{
private Player _player1;
private Player _player2;
private int _second;
public StartTask(Player player1, Player player2)
{
_player1 = player1;
_player2 = player2;
_second = Config.TIME_TO_PREPARATION;
}
@Override
public void runImpl() throws Exception
{
addBuffers();
final String name = ItemFunctions.createItem(_itemId).getTemplate().getName();
switch(_second)
{
case 60:
sayToPlayers("scripts.events.fightclub.TimeToStart", _second, false, _player1, _player2);
break;
case 30:
sayToPlayers("scripts.events.fightclub.TimeToStart", _second, false, _player1, _player2);
break;
case 20:
sayToPlayers("scripts.events.fightclub.TimeToStart", _second, false, _player1, _player2);
break;
case 10:
sayToPlayers("scripts.events.fightclub.TimeToStart", _second, false, _player1, _player2);
break;
case 5:
sayToPlayers("scripts.events.fightclub.TimeToStart", _second, false, _player1, _player2);
break;
case 3:
sayToPlayers("scripts.events.fightclub.TimeToStart", _second, false, _player1, _player2);
break;
case 2:
sayToPlayers("scripts.events.fightclub.TimeToStart", _second, false, _player1, _player2);
break;
case 1:
sayToPlayers("scripts.events.fightclub.TimeToStart", _second, false, _player1, _player2);
break;
case 0:
openDoors();
deleteBuffers();
startBattle(_player1, _player2);
_startTask.cancel(true);
_startTask = null;
if(Config.FIGHT_CLUB_ANNOUNCE_START_TO_SCREEN)
sayStartToAllPlayers("scripts.events.fightclub.AnnounceStartBatle", _player1, _player2, getItemName(), getItemCount(), false);
}
_second -= 1;
}
}
private static String getBufferSpawnGroup(int instancedZoneId)
{
String bufferGroup = null;
switch(instancedZoneId)
{
case 147:
bufferGroup = "olympiad_147_buffers";
break;
case 148:
bufferGroup = "olympiad_148_buffers";
break;
case 149:
bufferGroup = "olympiad_149_buffers";
break;
case 150:
bufferGroup = "olympiad_150_buffers";
break;
}
return bufferGroup;
}
private static void addBuffers()
{
if(getBufferSpawnGroup(_reflection.getInstancedZoneId()) != null)
_reflection.spawnByGroup(getBufferSpawnGroup(_reflection.getInstancedZoneId()));
}
private static void deleteBuffers()
{
_reflection.despawnByGroup(getBufferSpawnGroup(_reflection.getInstancedZoneId()));
}
private class EndTask extends RunnableImpl
{
private final Object[] args = { _player1, _player2, new Object[0] };
@Override
public void runImpl() throws Exception
{
removeAura();
if(!_isEnded)
{
draw();
_isEnded = true;
stopEndTask();
}
sayToPlayers("scripts.events.fightclub.TeleportBack", Config.TIME_TELEPORT_BACK, false, _player1, _player2);
executeTask(CLASS_NAME, "resurrectPlayers", args, Config.TIME_TELEPORT_BACK * 1000 - 300);
executeTask(CLASS_NAME, "healPlayers", args, Config.TIME_TELEPORT_BACK * 1000 - 200);
executeTask(CLASS_NAME, "teleportPlayersBack", args, Config.TIME_TELEPORT_BACK * 1000);
delete((Config.TIME_TELEPORT_BACK + 10) * 1000);
}
}
public static void openDoors()
{
for(DoorInstance door : _reflection.getDoors())
door.openMe();
}
public FightClubArena()
{}
@Override
public void onLoad()
{}
@Override
public void onReload()
{}
@Override
public void onShutdown()
{}
}
Код:
public class FightClubManagerInstance extends NpcInstance
{
private static final long serialVersionUID = 1L;
private static final String HTML_INDEX = "scripts/events/fightclub/index.htm";
private static final String HTML_ACCEPT = "scripts/events/fightclub/accept.htm";
private static final String HTML_MAKEBATTLE = "scripts/events/fightclub/makebattle.htm";
private static final String HTML_INFO = "scripts/events/fightclub/info.htm";
private static final String HTML_DISABLED = "scripts/events/fightclub/disabled.htm";
private static final String HTML_LIST = "scripts/events/fightclub/fightslist.htm";
private static final String HTML_RESULT = "scripts/events/fightclub/result.htm";
public FightClubManagerInstance(int objectId, NpcTemplate template)
{
super(objectId, template);
}
@Override
public void onBypassFeedback(Player player, String command)
{
if(!canBypassCheck(player, this))
return;
if(!Config.FIGHT_CLUB_ENABLED)
{
player.sendPacket(new NpcHtmlMessage(player, this, HtmCache.getInstance().getNotNull(HTML_DISABLED, player), 0));
return;
}
if(command.equalsIgnoreCase("index"))
{
player.sendPacket(new NpcHtmlMessage(player, this, HtmCache.getInstance().getNotNull(HTML_INDEX, player), 0));
}
else if(command.equalsIgnoreCase("makebattle"))
{
player.sendPacket(makeBattleHtml(player));
}
else if(command.equalsIgnoreCase("info"))
{
player.sendPacket(new NpcHtmlMessage(player, this, HtmCache.getInstance().getNotNull(HTML_INFO, player), 0));
}
else
{
final StringTokenizer st = new StringTokenizer(command, " ");
String pageName = st.nextToken();
if(pageName.equalsIgnoreCase("addbattle"))
{
int count = 0;
try
{
count = Integer.parseInt(st.nextToken());
if(count == 0)
{
sendResult(player, player.isLangRus() ? "Ошибка!" : "Error!", player.isLangRus() ? "Вы не ввели количество, или неправильное число." : "You did not enter the number or wrong number.");
return;
}
}
catch(NumberFormatException e)
{
sendResult(player, player.isLangRus() ? "Ошибка!" : "Error!", player.isLangRus() ? "Вы не ввели количество, или неправильное число." : "You did not enter the number or wrong number.");
return;
}
String itemName = StringUtils.EMPTY;
if(st.hasMoreTokens())
{
itemName = st.nextToken();
while(st.hasMoreTokens())
itemName += " " + st.nextToken();
}
Object[] objects = { player, itemName, count };
final String respone = (String) callScripts("addApplication", objects);
if("OK".equalsIgnoreCase(respone))
{
sendResult(player, player.isLangRus() ? "Выполнено!" : "Completed!", (player.isLangRus() ? "Вы создали заявку на участие.<br>Ваша ставка - <font color=\"LEVEL\">" : "You have created an application for participation.<br>Your bet - <font color=\"LEVEL\">") + String.valueOf(objects[2]) + " " + String.valueOf(objects[1]) + (player.isLangRus() ? "</font><br><center>Удачи!</center>" : "</font><br><center>Good luck!</center>"));
}
else if("NoItems".equalsIgnoreCase(respone))
{
sendResult(player, player.isLangRus() ? "Ошибка!" : "Error!", player.isLangRus() ? "У вас недостаточно или отсутствуют требующиеся предметы!" : "You are not required or missing items!");
return;
}
else if("reg".equalsIgnoreCase(respone))
{
sendResult(player, player.isLangRus() ? "Ошибка!" : "Error!", player.isLangRus() ? "Вы уже зарегистрированы! Если вы хотите изменить ставку, удалите старую регистрацию." : "You are already registered! If you wish to bid, remove the old registration.");
return;
}
}
else if(pageName.equalsIgnoreCase("delete"))
{
Object[] playerObject = { player };
if((Boolean) callScripts("isRegistered", playerObject))
{
callScripts("deleteRegistration", playerObject);
sendResult(player, player.isLangRus() ? "Выполнено!" : "Completed!", player.isLangRus() ? "<center>Вы удалены из списка регистрации.</center>" : "<center>You are removed from the list of registration.</center>");
}
else
sendResult(player, player.isLangRus() ? "Ошибка!" : "Error!", player.isLangRus() ? "<center>Вы не были зарегистрированы на участие.</center>" : "<center>You have not been registered to participate.</center>");
}
else if(pageName.equalsIgnoreCase("openpage"))
{
player.sendPacket(makeOpenPage(player, Integer.parseInt(st.nextToken())));
}
else if(pageName.equalsIgnoreCase("tryaccept"))
{
player.sendPacket(makeAcceptHtml(player, Long.parseLong(st.nextToken())));
}
else if(pageName.equalsIgnoreCase("accept"))
{
accept(player, Long.parseLong(st.nextToken()));
}
}
}
@Override
public void showChatWindow(Player player, int val, Object... arg)
{
player.sendPacket(new NpcHtmlMessage(player, this, HtmCache.getInstance().getNotNull(HTML_INDEX, player), val));
}
private NpcHtmlMessage makeOpenPage(Player player, int pageId)
{
NpcHtmlMessage html = new NpcHtmlMessage(player, this);
html.setFile(HTML_LIST);
StringBuilder sb = new StringBuilder();
final int count = (Integer) callScripts("getRatesCount", new Object[0]);
int num = pageId * Config.PLAYERS_PER_PAGE;
if(num > count)
num = count;
if(count > 0)
{
sb.append("<table width=300>");
for(int i = pageId * Config.PLAYERS_PER_PAGE - Config.PLAYERS_PER_PAGE; i < num; i++)
{
Object[] index = { i };
Rate rate = (Rate) callScripts("getRateByIndex", index);
sb.append("<tr>");
sb.append("<td align=center width=95>");
sb.append("<a action=\"bypass -h npc_%objectId%_tryaccept ").append(rate.getStoredId()).append("\">");
sb.append("<font color=\"ffff00\">").append(rate.getPlayerName()).append("</font></a></td>");
sb.append("<td align=center width=70>").append(rate.getPlayerLevel()).append("</td>");
sb.append("<td align=center width=100><font color=\"ff0000\">");
sb.append(rate.getPlayerClass()).append("</font></td>");
sb.append("<td align=center width=135><font color=\"00ff00\">");
sb.append(rate.getItemCount()).append(" ").append(rate.getItemName());
sb.append("</font></td></tr>");
}
sb.append("</table><br><br><br>");
int pg = getPagesCount(count);
sb.append("Страницы: ");
for(int i = 1; i <= pg; i++)
{
if(i == pageId)
sb.append(i).append(" ");
else
sb.append("<a action=\"bypass -h npc_%objectId%_openpage ").append(i).append("\">").append(i).append("</a> ");
}
}
else
sb.append(player.isLangRus() ? "<br><center>Ставок пока не сделано</center>" : "<br><center>Rates have not yet done</center>");
html.replace("%data%", sb.toString());
return html;
}
private NpcHtmlMessage makeBattleHtml(Player player)
{
NpcHtmlMessage html = new NpcHtmlMessage(player, this);
html.setFile(HTML_MAKEBATTLE);
html.replace("%items%", (String) callScripts("getItemsList", new Object[0]));
return html;
}
private NpcHtmlMessage makeAcceptHtml(Player player, long storedId)
{
Object[] id = { storedId };
Rate rate = (Rate) callScripts("getRateByStoredId", id);
NpcHtmlMessage html = new NpcHtmlMessage(player, this);
html.setFile(HTML_ACCEPT);
html.replace("%name%", rate.getPlayerName());
html.replace("%class%", rate.getPlayerClass());
html.replace("%level%", String.valueOf(rate.getPlayerLevel()));
html.replace("%rate%", rate.getItemCount() + " " + rate.getItemName());
html.replace("%storedId%", String.valueOf(rate.getStoredId()));
return html;
}
private void accept(Player player, long storedId)
{
final Object[] data = { GameObjectsStorage.getAsPlayer(storedId), player };
if(player.getStoredId() == storedId)
{
sendResult(player, player.isLangRus() ? "Ошибка!" : "Error!", player.isLangRus() ? "Вы не можете вызвать на бой самого себя." : "You can not call the fight itself.");
return;
}
//TODO: Проверка на айтемы... Берем пример с doStart
//if(Functions.getItemCount(player, _))
if((Boolean) callScripts("requestConfirmation", data))
{
sendResult(player, player.isLangRus() ? "Внимание!" : "Attention!", player.isLangRus() ? "Вы отправили запрос сопернику. Если все условия соответствуют, Вас переместят на арену<br><center><font color=\"LEVEL\">Удачи!</font></center><br>" : "You have sent a request to the opponent. If all conditions match, you will move into the arena<br><center><font color=\"LEVEL\">Good luck!</font></center><br>");
}
}
private void sendResult(Player player, String title, String text)
{
NpcHtmlMessage html = new NpcHtmlMessage(player, this);
html.setFile(HtmCache.getInstance().getNotNull(HTML_RESULT, player));
html.replace("%title%", title);
html.replace("%text%", text);
player.sendPacket(html);
}
private int getPagesCount(int count)
{
if(count % Config.PLAYERS_PER_PAGE > 0)
return count / Config.PLAYERS_PER_PAGE + 1;
return count / Config.PLAYERS_PER_PAGE;
}
private Object callScripts(String methodName, Object[] args)
{
return Functions.callScripts("events.FightClub.FightClub", methodName, args);
}
public static class Rate
{
private String playerName;
private int playerLevel;
private String playerClass;
private int _itemId;
private String itemName;
private int _itemCount;
private long playerStoredId;
public Rate(Player player, int itemId, int itemCount)
{
playerName = player.getName();
playerLevel = player.getLevel();
playerClass = player.getClassId().name();
_itemId = itemId;
_itemCount = itemCount;
itemName = ItemFunctions.createItem(itemId).getTemplate().getName();
playerStoredId = player.getStoredId();
}
public String getPlayerName()
{
return playerName;
}
public int getPlayerLevel()
{
return playerLevel;
}
public String getPlayerClass()
{
return playerClass;
}
public int getItemId()
{
return _itemId;
}
public int getItemCount()
{
return _itemCount;
}
public String getItemName()
{
return itemName;
}
public long getStoredId()
{
return playerStoredId;
}
}
}