Skip to content

Instantly share code, notes, and snippets.

@dimkk
Last active August 13, 2016 11:35
Show Gist options
  • Save dimkk/d14c5f80980df0a19fc22ef1a8c889b7 to your computer and use it in GitHub Desktop.
Save dimkk/d14c5f80980df0a19fc22ef1a8c889b7 to your computer and use it in GitHub Desktop.
package quests;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import l2f.commons.util.Rnd;
import l2f.gameserver.model.instances.NpcInstance;
import l2f.gameserver.model.quest.Quest;
import l2f.gameserver.model.quest.QuestState;
import l2f.gameserver.scripts.ScriptFile;
public class _662_AGameOfCards extends Quest implements ScriptFile
{
// Нпц с которым говорить
private final static int KLUMP = 30845;
// Мобы с которых падает
private final static int[] mobs = {
20677,
21109,
21112,
21116,
21114,
21004,
21002,
21006,
21008,
21010,
18001,
20672,
20673,
20674,
20955,
20962,
20961,
20959,
20958,
20966,
20965,
20968,
20973,
20972,
21278,
21279,
21280,
21286,
21287,
21288,
21520,
21526,
21530,
21535,
21508,
21510,
21513,
21515
};
// Какой итем падает
private final static int RED_GEM = 8765;
// Награды
private final static int Enchant_Weapon_S = 959;
private final static int Enchant_Weapon_A = 729;
private final static int Enchant_Weapon_B = 947;
private final static int Enchant_Weapon_C = 951;
private final static int Enchant_Weapon_D = 955;
private final static int Enchant_Armor_D = 956;
private final static int ZIGGOS_GEMSTONE = 8868;
// Шанс дропа шарика видимо
private final static int drop_chance = 35;
// Набор карт
private final static Map<Integer, CardGame> Games = new ConcurrentHashMap<Integer, CardGame>();
// Объявление квеста и его правил
public _662_AGameOfCards()
{
super(true);
addStartNpc(KLUMP);
addKillId(mobs);
addQuestItem(RED_GEM);
}
// Обработчик событий
@Override
public String onEvent(String event, QuestState st, NpcInstance npc)
{
int _state = st.getState();
// Первый разговор
if (event.equalsIgnoreCase("30845_02.htm") && _state == CREATED)
{
// Установлен этап 1 и так далее
st.setCond(1);
st.setState(STARTED);
st.playSound(SOUND_ACCEPT);
}
else if (event.equalsIgnoreCase("30845_07.htm") && _state == STARTED)
{
st.playSound(SOUND_FINISH);
st.exitCurrentQuest(true);
}
else if (event.equalsIgnoreCase("30845_03.htm") && _state == STARTED && st.getQuestItemsCount(RED_GEM) >= 50)
return "30845_04.htm";
else if (event.equalsIgnoreCase("30845_10.htm") && _state == STARTED)
{
if (st.getQuestItemsCount(RED_GEM) < 50)
return "30845_10a.htm";
st.takeItems(RED_GEM, 50);
int player_id = st.getPlayer().getObjectId();
if (Games.containsKey(player_id))
Games.remove(player_id);
Games.put(player_id, new CardGame(player_id));
}
// Если выбирается ИГРА
else if (event.equalsIgnoreCase("play") && _state == STARTED)
{
// Получаем ID игрока
int player_id = st.getPlayer().getObjectId();
// Если не находится активных игр - начинаем новую
if (!Games.containsKey(player_id))
return null;
// Или возвращаем найденную игру
return Games.get(player_id).playField();
}
// Обработка забора карт
else if (event.startsWith("card") && _state == STARTED)
{
// Проверка - есть ли активная игра для этого игрока
int player_id = st.getPlayer().getObjectId();
if (!Games.containsKey(player_id))
return null;
try
{
// Получаем номер карты (приходит в названии ивента в виде cardX где X номер активной карты видимо)
int cardn = Integer.valueOf(event.replaceAll("card", ""));
// Возвращаем следующую карту методом Games.next() - описание будет ниже
return Games.get(player_id).next(cardn, st);
}
catch (Exception E)
{
return null;
}
}
return event;
}
// Обработчик разгвоора с НПЦ
@Override
public String onTalk(NpcInstance npc, QuestState st)
{
if (npc.getNpcId() != KLUMP)
return "noquest";
int _state = st.getState();
if (_state == CREATED)
{
// Проверка на текущий уровень > 61
if (st.getPlayer().getLevel() < 61)
{
st.exitCurrentQuest(true);
return "30845_00.htm";
}
st.setCond(0);
return "30845_01.htm";
}
else if (_state == STARTED)
return st.getQuestItemsCount(RED_GEM) < 50 ? "30845_03.htm" : "30845_04.htm";
return "noquest";
}
// Обработка убийства моба - считает шанс дропа шарика
@Override
public String onKill(NpcInstance npc, QuestState qs)
{
if (qs.getState() == STARTED)
qs.rollAndGive(RED_GEM, 1, drop_chance);
return null;
}
@Override
public void onLoad()
{
}
@Override
public void onReload()
{
}
@Override
public void onShutdown()
{
}
// Тут все расчеты делаются по игре
private static class CardGame
{
private final String[] cards = new String[5];
private final int player_id;
// Карты
private final static String[] card_chars = new String[]{
"A",
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10",
"J",
"Q",
"K"
};
private final static String html_header = "<html><body>";
private final static String html_footer = "</body></html>";
private final static String table_header = "<table border=\"1\" cellpadding=\"3\"><tr>";
private final static String table_footer = "</tr></table><br><br>";
private final static String td_begin = "<center><td width=\"50\" align=\"center\"><br><br><br> ";
private final static String td_end = " <br><br><br><br></td></center>";
// Тут создается сама игра для игрока, запоминается ID игрока и для него генерируются ссылки на выбор карт
public CardGame(int _player_id)
{
player_id = _player_id;
for (int i = 0; i < cards.length; i++)
cards[i] = "<a action=\"bypass -h Quest _662_AGameOfCards card" + i + "\">?</a>";
}
// Логика выдачи следующей карты
public String next(int cardn, QuestState st)
{
// проверка на адекватность - номер карты попадает в макс. число карт или номер карты не число
if (cardn >= cards.length || !cards[cardn].startsWith("<a"))
return null;
// Рандомим карту
cards[cardn] = card_chars[Rnd.get(card_chars.length)];
// Проверяем - если последняя карта - показываем приглашение играть?? (надо проверить)
for (String card : cards)
if (card.startsWith("<a"))
// Вот тут что-то показывается
return playField();
// Вот тут расчёт выйгрыша или победы
return finish(st);
}
// Считаем выйгрыш
private String finish(QuestState st)
{
String result = html_header + table_header;
Map<String, Integer> matches = new HashMap<String, Integer>();
// Собираем карты в коллоды по типу в стэк
for (String card : cards)
{
// Считаем, есть ли такая карта уже и добавляем + 1
int count = matches.containsKey(card) ? matches.remove(card) : 0;
count++;
// Модифицируем кол-карт в стэеке
matches.put(card, count);
}
// Убираем карты без повторений
for (String card : cards)
if (matches.get(card) < 2)
matches.remove(card);
// smatches - карты с повторами, cmatches - набор повторений (Типа сколько карт повторилось)
String[] smatches = matches.keySet().toArray(new String[matches.size()]);
Integer[] cmatches = matches.values().toArray(new Integer[matches.size()]);
String txt = "Hmmm...? This is... No pair? Tough luck, my friend! Want to try again? Perhaps your luck will take a turn for the better...";
// Если повторений 1
if (cmatches.length == 1)
{
// Если повторов = 5, т.е. jjjjj
if (cmatches[0] == 5)
{
// Даем итемы и так далее
txt = "Hmmm...? This is... Five of a kind!!!! What luck! The goddess of victory must be with you! Here is your prize! Well earned, well played!";
st.giveItems(ZIGGOS_GEMSTONE, 43);
st.giveItems(Enchant_Weapon_S, 3);
st.giveItems(Enchant_Weapon_A, 1);
}
else if (cmatches[0] == 4)
{
txt = "Hmmm...? This is... Four of a kind! Well done, my young friend! That sort of hand doesn't come up very often, that's for sure. Here's your prize.";
st.giveItems(Enchant_Weapon_S, 2);
st.giveItems(Enchant_Weapon_C, 2);
}
else if (cmatches[0] == 3)
{
txt = "Hmmm...? This is... Three of a kind? Very good, you are very lucky. Here's your prize.";
st.giveItems(Enchant_Weapon_C, 2);
}
else if (cmatches[0] == 2)
{
txt = "Hmmm...? This is... One pair? You got lucky this time, but I wonder if it'll last. Here's your prize.";
st.giveItems(Enchant_Armor_D, 2);
}
}
else if (cmatches.length == 2)
if (cmatches[0] == 3 || cmatches[1] == 3)
{
txt = "Hmmm...? This is... A full house? Excellent! you're better than I thought. Here's your prize.";
st.giveItems(Enchant_Weapon_A, 1);
st.giveItems(Enchant_Weapon_B, 2);
st.giveItems(Enchant_Weapon_D, 1);
}
else
{
// Если 2 пары
txt = "Hmmm...? This is... Two pairs? You got lucky this time, but I wonder if it'll last. Here's your prize.";
st.giveItems(Enchant_Weapon_C, 1);
}
// Генерим текст
for (String card : cards)
if (smatches.length > 0 && smatches[0].equalsIgnoreCase(card))
result += td_begin + "<font color=\"55FD44\">" + card + "</font>" + td_end;
else if (smatches.length == 2 && smatches[1].equalsIgnoreCase(card))
result += td_begin + "<font color=\"FE6666\">" + card + "</font>" + td_end;
else
result += td_begin + card + td_end;
result += table_footer + txt;
if (st.getQuestItemsCount(RED_GEM) >= 50)
result += "<br><br><a action=\"bypass -h Quest _662_AGameOfCards 30845_10.htm\">Play Again!</a>";
result += html_footer;
Games.remove(player_id);
return result;
}
public String playField()
{
String result = html_header + table_header;
for (String card : cards)
result += td_begin + card + td_end;
result += table_footer + "Check your next card." + html_footer;
return result;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment