Beispiel #1
0
 def update_skills(self):
     class_skills = skills.get(self.game_class)
     for i in list(class_skills):
         if i == 'Атака' or i == 'Пропуск хода':
             continue
         self.skill_cooldown.update({i: 0})
         self.skill_lvl.update({i: 1})
Beispiel #2
0
 def update_cooldown(self):
     from work_materials.globals import skills
     class_skills = skills.get(self.game_class)
     for i in list(class_skills.values()):
         if i.name == 'Атака' or i.name == 'Пропуск хода':
             continue
         self.skill_cooldown.update({i.name: 0})
Beispiel #3
0
 def lvl_up_skill(self, skill_number):
     if int(skill_number) not in range(6):
         return None
     skill_names = list(skills.get(self.game_class))
     self.skill_lvl.update({
         skill_names[int(skill_number)]:
         int(self.skill_lvl.get(skill_names[int(skill_number)])) + 1
     })
Beispiel #4
0
def bots_processing():
    try:
        battle = battle_with_bots_to_set.get()
        while battle:
            try:
                print("got ai battle")
                aggro_list = battle.aggro_list
                if not aggro_list:
                    #   Заполнение агро-листа в первый раз
                    for ai in battle.teams[1]:
                        current_ai_aggro_list = []
                        for player in battle.teams[0]:
                            current_ai_aggro_list.append(player)
                        aggro_list.update({ai.participant.nickname : current_ai_aggro_list})
                        ai.aggro_list = current_ai_aggro_list
                for ai in battle.teams[1]:
                    #print(ai.aggro_list)
                    for i in ai.aggro_list:
                        print(battle.taunt_list)
                        print("aggro list: ", i.participant.nickname in list(battle.taunt_list.get(0)), i.aggro)
                    ai.aggro_list.sort(key = lambda pib: (pib.participant.nickname not in battle.dead_list,
                                                          battle.taunt_list.get(0).get(pib.participant.nickname) > 1 if
                                                          i.participant.nickname in list(battle.taunt_list.get(0)) else False,
                                                          pib.aggro), reverse=True)
                    ai.skill = None
                    skills_list = skills.get(ai.participant.game_class)
                    for skill_name in list(skills_list)[1:-1]:
                        print(skill_name, ai.participant.skill_cooldown)
                        skill_cooldown = ai.participant.skill_cooldown.get(skill_name)
                        if skill_cooldown == 0:
                            skill = skills_list.get(skill_name)
                            ai.skill = skill
                            break
                    if ai.skill is None:
                        ai.skill = get_skill(ai.participant.game_class, "Атака")
                    targets = [ai.aggro_list[0].participant]
                    ai.targets = targets
                    battle.skills_queue.append(ai)
            except KeyboardInterrupt:
                return 0
            except Exception:
                for player_in_battle in battle.teams[0]:
                    try:
                        dispatcher.bot.send_message(chat_id = player_in_battle.participant.id, text = "<b>Ошибка при обработке ИИ</b>", parse_mode="HTML")
                    except Exception:
                        logging.error(traceback.format_exc())
                logging.error(traceback.format_exc())
            print("put from ai")
            battles_need_treating.put(battle)
            battle = battle_with_bots_to_set.get()
    except KeyboardInterrupt:
        return 0
    except Exception:
        logging.error(traceback.format_exc())
Beispiel #5
0
 def skill_avaliable(
         self, skill_name
 ):  #-1 - нет такого скилла, -2 - не разблокирован, -3 - КД
     if skill_name == 'Атака' or skill_name == 'Пропуск хода':
         return 1
     avaliable_skills = skills.get(self.game_class)
     flag = 0
     for i in list(avaliable_skills.values()):
         if i.name == skill_name:
             flag = 1
             break
     if flag == 0:
         return -1
     for i in range(len(list(avaliable_skills.values()))):
         if list(avaliable_skills.values())[i].name == skill_name:
             if self.skill_lvl.get(skill_name) <= 0:
                 return -2
             else:
                 if self.skill_cooldown.get(skill_name) > 0:
                     return -3
                 else:
                     return 1
Beispiel #6
0
def get_general_battle_buttons(player):
    user_data = dispatcher.user_data.get(player.id)
    if user_data and user_data.get('status') == "Battle_dead":
        return ReplyKeyboardRemove()
    stun = dispatcher.user_data.get(player.id).get('stunned')
    if stun is not None and stun > 0:
        #return ReplyKeyboardRemove()
        return None
    __general_battle_buttons = []
    n_cols = 3
    class_skills = skills.get(player.game_class)
    for i in class_skills.values():
        if i.priority == 0:
            continue
        if i.priority == 10:
            __general_battle_buttons.append(KeyboardButton(i.name))
            n_cols += 1
            continue
        if player.skill_lvl.get(i.name) > 0:
            __general_battle_buttons.append(KeyboardButton(i.name))
            n_cols += 1
    __general_battle_buttons.append(
        KeyboardButton('Использовать предмет')
    )  #TODO Сделать использование предметов в сообщении по /use_
    __general_battle_buttons.append(KeyboardButton('Голосование ((флекс))'))
    __general_battle_buttons.append(KeyboardButton('Пропуск хода'))
    if n_cols % 2 == 0:
        n_cols = 2
    elif n_cols % 3 == 0:
        n_cols = 3
    elif n_cols == 5:
        n_cols = 2
    elif n_cols == 7:
        n_cols = 3
    else:
        n_cols = 2
    return ReplyKeyboardMarkup(build_menu(__general_battle_buttons, n_cols),
                               resize_keyboard=True)
Beispiel #7
0
 def update_cooldown(self):
     class_skills = skills.get(self.game_class)
     for i in list(class_skills.values()):
         if i.name == 'Атака' or i.name == 'Пропуск хода':
             continue
         self.skill_cooldown.update({i.name: 0})
Beispiel #8
0
    def update_from_database(self):
        request = "SELECT id, username, nickname, sex, fraction, race, game_class," \
                  " exp, lvl, free_points, free_skill_points, fatigue, first_skill_lvl, second_skill_lvl, " \
                  "third_skill_lvl, fourth_skill_lvl, fifth_skill_lvl, endurance, power, armor, charge, speed, mana, hp," \
                  " location, gold, metal, wood, " \
                  "head, body, shoulders, legs, feet, left_arm, right_arm, mount FROM players WHERE id = %s"
        cursor.execute(request, (self.id, ))
        row = cursor.fetchone()
        if row is None:
            return None
        self.id = row[0]
        self.username = row[1]
        self.nickname = row[2]
        self.sex = row[3]
        self.fraction = row[4]
        self.race = row[5]
        self.game_class = row[6]
        self.aggro_prob = aggro_probe_game_classes.get(self.game_class)
        self.exp = row[7]
        self.lvl = row[8]
        self.free_points = row[9]
        self.free_skill_points = row[10]
        self.fatigue = row[11]
        skill_names = list(skills.get(self.game_class))
        for i in range(len(skill_names)):
            if i in [0, len(skill_names) - 1]:
                continue
            self.skill_lvl.update({skill_names[i]: row[12 + i - 1]})
        self.stats.update(endurance=row[17],
                          power=row[18],
                          armor=row[19],
                          charge=row[20],
                          speed=row[21])
        self.charge = row[22]
        self.hp = row[23]
        self.location = row[24]
        self.resources.update(gold=row[25], metal=row[26], wood=row[27])

        self.on_character.update(
            head=row[28] if row[28] != 'None' else None,
            body=row[29] if row[29] != 'None' else None,
            shoulders=row[30] if row[30] != 'None' else None,
            legs=row[31] if row[31] != 'None' else None,
            feet=row[32] if row[32] != 'None' else None,
            left_arm=row[33] if row[33] != 'None' else None,
            right_arm=row[34] if row[34] != 'None' else None,
            mount=row[35] if row[35] != 'None' else None)
        request = "SELECT type, id, quanty FROM inventory WHERE user_id = %s"
        cursor.execute(request, (self.id, ))
        row = cursor.fetchone()
        while row:
            type = row[0]
            id = row[1]
            quanty = row[2]
            if type == "a":
                self.al_backpack.update({id: quanty})
            elif type == "r":
                self.res_backpack.update({id: quanty})
            else:
                self.eq_backpack.update({id: quanty})
            row = cursor.fetchone()
        return self
Beispiel #9
0
def battle_count(
):  #Тут считается битва в которой все выбрали действие, отдельный процесс, Не забыть сделать так, чтобы выполнялось в таком порядке, в котором было выбрано
    #Возможно стоит едитить сообщение и проставлять галки для тех, кто уже готов
    try:
        while True:
            battle = battles_need_treating.get()
            try:
                team_strings = ["Team 1:\n", "Team 2:\n"]
                result_strings = ["Team 1:\n", "Team 2:\n"]
                damage_dict = {}
                for i in battle.skills_queue:
                    try:
                        if i.participant.nickname in battle.dead_list:
                            #   Проверка на смэрт
                            if not i.is_ai:
                                message_group = get_message_group(
                                    i.participant.id)
                                dispatcher.bot.group_send_message(
                                    message_group,
                                    chat_id=i.participant.id,
                                    text="<b>Вы мертвы</b>",
                                    parse_mode="HTML",
                                    reply_markup=ReplyKeyboardRemove())
                            continue
                        if i.participant.nickname in battle.stun_list:
                            #   Проверка на стан
                            team_strings[
                                i.
                                team] += "•<b>{0}</b> Оглушен на {1} ходов".format(
                                    i.participant.nickname +
                                    game_classes_to_emoji.get(
                                        i.participant.game_class),
                                    battle.stun_list.get(
                                        i.participant.nickname) - 1)
                            continue
                        skill_str = i.skill.use_skill(i.targets, battle,
                                                      i.participant)
                        damage = 0
                        if skill_str is not None:
                            try:
                                damage = int(skill_str)
                            except ValueError:
                                damage = None
                            if damage is not None and damage >= 0:
                                skill_str = "(+" + skill_str + ")"
                            else:
                                skill_str = "(" + skill_str + ")"
                        if damage is not None and damage != 0:
                            for t in i.targets:
                                record = damage_dict.get(t.nickname)
                                if record is None:
                                    damage_dict.update({t.nickname: damage})
                                else:
                                    damage_dict.update(
                                        {t.nickname: record + damage})
                        if i.skill.priority == 0:
                            team_strings[
                                i.team] += i.skill.format_string.format(
                                    i.participant.nickname +
                                    game_classes_to_emoji.get(
                                        i.participant.game_class), "", "")
                        else:
                            if len(i.targets) > 1:
                                team_strings[
                                    i.team] += i.skill.format_string.format(
                                        i.participant.nickname +
                                        game_classes_to_emoji.get(
                                            i.participant.game_class),
                                        "Команда противника",
                                        "<b>" + skill_str + "</b>")
                            else:
                                team_strings[
                                    i.team] += i.skill.format_string.format(
                                        i.participant.nickname +
                                        game_classes_to_emoji.get(
                                            i.participant.game_class),
                                        i.targets[0].nickname +
                                        game_classes_to_emoji.get(
                                            i.targets[0].game_class),
                                        "<b>" + skill_str + "</b>")
                        print(battle.mode, damage)
                        if battle.mode == "pve" and not i.participant.is_ai:
                            if damage < 0:  #   damage < 0, если наносится урон
                                #   Обработка агро
                                for target in i.targets:
                                    if target.is_ai:
                                        print(battle.aggro_list)
                                        player_agro_dict = battle.aggro_list.get(
                                            target.nickname)
                                        #current_aggro = player_agro_dict.get(i.participant.nickname)]
                                        current_aggro = None
                                        for pib in player_agro_dict:
                                            if pib.nickname == i.participant.nickname:
                                                current_aggro = pib.aggro
                                                if not current_aggro:
                                                    print(
                                                        "current aggro is None!"
                                                    )
                                                    current_aggro = 0
                                                print(current_aggro, damage,
                                                      i.participant.aggro_prob)
                                                pib.aggro += damage * i.participant.aggro_prob
                                                print(
                                                    "aggro for {0} updated, new value = {1}"
                                                    .format(
                                                        i.participant.nickname,
                                                        current_aggro))

                    except Exception:
                        if not i.is_ai:
                            dispatcher.bot.group_send_message(
                                get_message_group(i.participant.id),
                                chat_id=
                                get_player_choosing_from_battle_via_nick(
                                    battle,
                                    i.participant.nickname).participant.id,
                                text="<b>Ошибка при обработке скиллов</b>",
                                parse_mode="HTML")
                        logging.error(traceback.format_exc())
                team_strings[0] += '\n'
                battle.skills_queue.clear()
                for i in range(2):
                    for j in range(battle.team_players_count[i]):
                        player_choosing = battle.teams[i][j]
                        player = player_choosing.participant
                        try:
                            if player.nickname in battle.dead_list or player.hp <= 0:
                                result_strings[i] += "✖️"
                            else:
                                if player.nickname in list(
                                        battle.stun_list
                                ) and battle.stun_list.get(
                                        player.nickname) > 1:
                                    result_strings[i] += "💫({0})".format(
                                        battle.stun_list.get(player.nickname) -
                                        1)
                                if battle.taunt_list.get(i).get(
                                        player.nickname
                                ) is not None and battle.taunt_list.get(i).get(
                                        player.nickname) > 1:
                                    result_strings[i] += "🔰({0})".format(
                                        battle.taunt_list.get(i).get(
                                            player.nickname) - 1)
                            curr_damage = damage_dict.get(player.nickname)
                            str_damage = ""
                            if curr_damage is not None and curr_damage != 0:
                                str_damage += "("
                                str_damage += "+" if curr_damage > 0 else ""
                                str_damage += str(curr_damage)
                                str_damage += ")"

                            result_strings[
                                i] += "<b>{0}</b>{1}  {2}{4}🌡 {3}⚡️   /info_{5}\n".format(
                                    player.nickname,
                                    game_classes_to_emoji.get(
                                        player.game_class), player.hp,
                                    player.charge, str_damage, player_choosing.
                                    number)  #TODO написать красиво
                            player_buff_list = battle.buff_list.get(
                                player.nickname)
                            flag = 0
                            if player_buff_list is not None:
                                for t in list(player_buff_list):
                                    if not player_buff_list.get(t):
                                        continue
                                    else:
                                        if flag == 0:
                                            result_strings[i] += "    Баффы:\n"
                                            flag = 1

                                    for k in player_buff_list.get(t):
                                        result_strings[
                                            i] += "        <b>{2}{0}</b> {3} на {1} ходов\n".format(
                                                k.buff, k.turns,
                                                "+" if k.buff > 0 else "", t)
                            else:
                                logging.error(
                                    "player_buff_list is None in battle_processing for "
                                    + player.nickname)
                                logging.error("battle.buff_list: " +
                                              str(battle.buff_list))

                            class_skills = skills.get(player.game_class)
                            flag = 0
                            if class_skills is not None:
                                for t in list(class_skills.values()):
                                    if t.name not in [
                                            'Атака', 'Пропуск хода'
                                    ] and player.skill_cooldown.get(
                                            t.name) > 0:
                                        player.skill_cooldown.update({
                                            t.name:
                                            player.skill_cooldown.get(t.name) -
                                            1
                                        })
                                        cooldown = player.skill_cooldown.get(
                                            t.name)
                                        if cooldown == 0:
                                            continue
                                        else:
                                            if flag == 0:
                                                result_strings[
                                                    i] += "    Cooldown:\n"
                                                flag = 1
                                        result_strings[
                                            i] += "        {0} - {1} ходов\n".format(
                                                t.name, cooldown
                                            )  #TODO разобраться с окончаниями
                            else:
                                logging.error(
                                    "class_skills is None in battle_processing for "
                                    + player.nickname)

                            result_strings[i] += '\n'
                            player_choosing.targets = None
                            player_choosing.skill = None
                            if not player_choosing.is_ai:
                                reply_markup = get_general_battle_buttons(
                                    player)
                                if player.nickname in battle.dead_list:
                                    reply_markup = None
                                message_group = get_message_group(player.id)
                                dispatcher.bot.group_send_message(
                                    message_group,
                                    chat_id=player.id,
                                    text=team_strings[0] + '\n' +
                                    team_strings[1],
                                    parse_mode="HTML",
                                    reply_markup=reply_markup)
                        except Exception:
                            logging.error(traceback.format_exc())
                            if not player_choosing.is_ai:
                                message_group = get_message_group(player.id)
                                dispatcher.bot.group_send_message(
                                    message_group,
                                    chat_id=player.id,
                                    text=
                                    "<b>Ошибка при отправлении списка использованных скиллов</b>",
                                    parse_mode="HTML")
                #Проставление статусов и зануление
                for i in range(2):
                    for j in range(battle.team_players_count[i]):
                        player_choosing = battle.teams[i][j]
                        if not player_choosing.is_ai:
                            player = player_choosing.participant
                            try:
                                dict = {'status': 'Battle'}
                                if player.dead == 1:
                                    dict.update({'status': 'Battle_dead'})
                                interprocess_dictionary = InterprocessDictionary(
                                    player.id, "user_data", dict)
                                interprocess_queue.put(interprocess_dictionary)

                                reply_markup = get_general_battle_buttons(
                                    player)
                                message_group = get_message_group(player.id)
                                dispatcher.bot.group_send_message(
                                    message_group,
                                    chat_id=player.id,
                                    text=result_strings[0] + "\n" +
                                    result_strings[1],
                                    parse_mode="HTML",
                                    reply_markup=reply_markup)
                            except Exception:
                                logging.error(traceback.format_exc())
                                if not player_choosing.is_ai:
                                    message_group = get_message_group(
                                        player.id)
                                    dispatcher.bot.group_send_message(
                                        message_group,
                                        chat_id=player.id,
                                        text=
                                        "<b>Ошибка при отправлении результата</b",
                                        parse_mode="HTML")

                #Смэрт и зануление
                for i in range(2):
                    for j in range(battle.team_players_count[i]):
                        player_choosing = battle.teams[i][j]
                        player = player_choosing.participant
                        #Проверка на смэрт
                        if player.hp <= 0:
                            try:
                                battle.dead_list.append(player.nickname)
                                player.dead = 1
                                player_choosing.skill = 6
                                player_choosing.targets = [player]
                                try:
                                    battle.taunt_list.get(i).pop(
                                        player.nickname)
                                except KeyError:
                                    pass
                                try:
                                    battle.buff_list.pop(player.nickname)
                                except KeyError:
                                    pass
                                if not player_choosing.is_ai:
                                    message_group = get_message_group(
                                        player.id)
                                    dispatcher.bot.group_send_message(
                                        message_group,
                                        chat_id=player.id,
                                        text="<b>Вы мертвы!</b>",
                                        parse_mode="HTML"
                                    )  #, reply_markup=ReplyKeyboardRemove())
                                    interprocess_dictionary = InterprocessDictionary(
                                        player.id, "user_data",
                                        {'status': 'Battle_dead'})
                                    interprocess_queue.put(
                                        interprocess_dictionary
                                    )  #TODO сделать смерть ии
                            except Exception:
                                logging.error(traceback.format_exc())
                                if not player_choosing.is_ai:
                                    message_group = get_message_group(
                                        player.id)
                                    dispatcher.bot.group_send_message(
                                        message_group,
                                        chat_id=player.id,
                                        text=
                                        "<b>Ошибка при обработке смерти</b",
                                        parse_mode="HTML")
                        #Проверка на стан
                        elif player.nickname in list(battle.stun_list):
                            try:
                                stun = battle.stun_list.get(player.nickname)
                                if stun <= 1:
                                    battle.stun_list.pop(player.nickname)
                                    interprocess_dictionary = InterprocessDictionary(
                                        player.id, "remove stun", {})
                                    interprocess_queue.put(
                                        interprocess_dictionary)
                                else:
                                    player_choosing.skill = get_skill(
                                        player.game_class, "Пропуск хода")
                                    player_choosing.targets = [player]
                                    battle.stun_list.update(
                                        {player.nickname: stun - 1})
                                    if not player_choosing.is_ai:
                                        message_group = get_message_group(
                                            player.id)
                                        dispatcher.bot.group_send_message(
                                            message_group,
                                            chat_id=player.id,
                                            text="Вы оглушены!",
                                            reply_markup=ReplyKeyboardRemove())
                                        interprocess_dictionary = InterprocessDictionary(
                                            player.id, "user_data", {
                                                'stunned':
                                                battle.stun_list.get(
                                                    player.nickname)
                                            })
                                        interprocess_queue.put(
                                            interprocess_dictionary)
                                    battle.skills_queue.append(player_choosing)
                            except Exception:
                                logging.error(traceback.format_exc())
                                if not player_choosing.is_ai:
                                    message_group = get_message_group(
                                        player.id)
                                    dispatcher.bot.group_send_message(
                                        message_group,
                                        chat_id=player.id,
                                        text="<b>Ошибка при обработке стана</b",
                                        parse_mode="HTML")

                        #Зануление баффов:
                        try:
                            player_buff_list = battle.buff_list.get(
                                player.nickname)
                            if player_buff_list is not None:
                                for t in list(player_buff_list.values()):
                                    for k in t:
                                        if k.turns <= 1:
                                            t.remove(k)
                                        else:
                                            k.turns -= 1
                        except Exception:
                            logging.error(traceback.format_exc())
                            if not player_choosing.is_ai:
                                message_group = get_message_group(player.id)
                                dispatcher.bot.group_send_message(
                                    message_group,
                                    chat_id=player.id,
                                    text="<b>Ошибка при занулении баффов</b",
                                    parse_mode="HTML")

                    #Зануление таунтов:
                    team_taunt_list = battle.taunt_list.get(i)
                    if team_taunt_list is not None:
                        for t in list(team_taunt_list):
                            if team_taunt_list.get(t) <= 1:
                                team_taunt_list.pop(t)
                            else:
                                team_taunt_list.update(
                                    {t: team_taunt_list.get(t) - 1})

                #Проверка победы
                res = check_win(battle)
                for i in range(2):
                    for j in range(battle.team_players_count[i]):
                        if res != -1:
                            player_choosing = battle.teams[i][j]
                            if not player_choosing.is_ai:
                                player = player_choosing.participant
                                text = ""
                                if res == 2:
                                    text = "<b>Ничья</b>"
                                elif player_choosing.team == res:
                                    text = "<b>Ваша команда победила! + 100exp</b>"

                                    interprocess_dictionary = InterprocessDictionary(
                                        player.id, "change_player_state", {
                                            player.id: None,
                                            "exp": 100
                                        })
                                    interprocess_queue.put(
                                        interprocess_dictionary)
                                else:
                                    text = "<b>Ваша команда проиграла</b>"
                                if not player_choosing.is_ai:
                                    message_group = get_message_group(
                                        player.id)
                                    dispatcher.bot.group_send_message(
                                        message_group,
                                        chat_id=player.id,
                                        text=text,
                                        parse_mode="HTML")
                                    interprocess_dictionary = InterprocessDictionary(
                                        player.id, "battle status return", {})
                                    interprocess_queue.put(
                                        interprocess_dictionary)
                                    #user_data = {'status' : player.saved_battle_status, 'location': player.location}   #TODO Глеб, разберись, тут ошибки: AttributeError: 'Player' object has no attribute 'saved_battle_status'
                                    #show_general_buttons(dispatcher.bot, player.id, user_data, message_group)
                                    message_group.shedule_removal()
                        else:
                            player_choosing = battle.teams[i][j]
                            if not player_choosing.is_ai:
                                player = player_choosing.participant
                                message_group = get_message_group(player.id)
                                message_group.shedule_removal()
                battle.last_count_time = time.time()
                if res == -1:
                    treated_battles.put(battle)
            except Exception:
                logging.error("Одна из битв упала id - " + str(battle.id) +
                              "С ошибкой:\n")
                logging.error(traceback.format_exc())
    except KeyboardInterrupt:
        return 0