def parse_travel_jobs(): try: f = open('backup/travel_jobs', 'rb') to_parse = pickle.load(f) f.close() for i in to_parse: player = get_player(i) user_data = dispatcher.user_data.get(i) update_status(user_data.get('status'), player, user_data) dispatcher.user_data[i].update({'saved_status': 'Traveling'}) t = to_parse.get(i) update = Chat_Id_Update(player.id) contexts = { 'chat_id': player.id, 'location_id': user_data.get('new_location'), 'player': player, 'update': update, 'user_data': user_data } j = MyJob( job.run_once(move_player, t[1], context=contexts), t[1], player.id ) # TODO неверно работает, необходимо сохранять не сколько осталось, а когда заканчивается j.start_time = time.time() - t[0] travel_jobs.update({i: j}) except FileNotFoundError: logging.error("Data file not found") except: logging.error(traceback.format_exc())
def lvl_up_points(bot, update, user_data): id = update.message.from_user.id player = get_player(id) if player is None: return if update.message.text == "Готово": player.update_stats() update_status(user_data.get('saved_lvl_up_status'), player, user_data) user_data.pop('saved_lvl_up_status') show_general_buttons(bot, update, user_data) player.lvl_check() return else: player.lvl_up_point(update.message.text) player.free_points -= 1 players.update({id: player}) players_need_update.put(player) if(update.message.text == "заряд"): bot.send_message(chat_id=update.message.chat_id, text="Улучшен <b>{0}</b>".format(update.message.text), parse_mode='HTML') else: bot.send_message(chat_id=update.message.chat_id, text="Улучшена <b>{0}</b>".format(update.message.text), parse_mode='HTML') choose_points(bot, update, user_data)
def farm(bot, update, user_data): player = get_player(update.message.from_user.id) update_status("Farming", player, user_data) print(player.status) user_data.update({'Farming_started': time.time(), 'Farming': True}) player.grind_started_time = time.time() grinding_players.append(player) show_general_buttons(bot, update, user_data)
def move_player(bot, job): player = job.context.get('player') user_data = job.context.get('user_data') update_status('In Location', player, user_data) update_location(job.context.get('location_id'), player, user_data) print(player.nickname, "Переместился в новую локацию -", player.location) players_need_update.put(player) travel_jobs.pop(player.id) update = job.context.get('update') show_general_buttons(bot, update, user_data)
def return_from_farm(bot, update, user_data): player = get_player(update.message.from_user.id) update_status("In Location", player, user_data) try: user_data.pop('Farming') user_data.pop('Farming_started') except KeyError: pass while player in grinding_players: grinding_players.remove(player) show_general_buttons(bot, update, user_data)
def choose_points(bot, update, user_data): id = update.message.from_user.id player = get_player(id) if(player is None): return free_points = player.free_points if(free_points < 0): player.free_points = 0 free_points = 0 if(free_points == 0): bot.send_message(chat_id = update.message.chat_id, text = "У вас нет свободных очков\n\n" "Выносливость - <b>{0}</b>\nБроня - <b>{1}</b>\n" "Сила - <b>{2}</b>\nСкорость - <b>{3}</b>\n" "Заряд - <b>{4}</b>".format( player.stats.get("endurance"), player.stats.get("armor"), player.stats.get("power"), player.stats.get("speed"), player.stats.get("charge")), parse_mode = "HTML", reply_markup = ReplyKeyboardRemove()) player.update_stats() players.update({id: player}) players_need_update.put(player) update_status(user_data.get('saved_lvl_up_status'), player, user_data) user_data.pop('saved_lvl_up_status') player.update_stats() show_general_buttons(bot, update, user_data) return update_status("Lvl_up_points", player, user_data) button_list = [ KeyboardButton("Выносливость"), KeyboardButton("Броня"), KeyboardButton("Сила"), KeyboardButton("Скорость"), KeyboardButton("Заряд"), KeyboardButton("Готово") ] buttons = ReplyKeyboardMarkup(build_menu(button_list, n_cols=2), resize_keyboard=True, one_time_keyboard=False) s = '' if free_points == 1: s = "характеристику" elif free_points >= 2 or free_points <= 4: s = "характеристики" elif free_points >= 5: s = "характеристик" bot.send_message(chat_id=update.message.chat_id, text="Вы можете улучшить <b>{5}</b> {6}\n\nВыберите характеристику, которую хотите улучшить\n" "Выносливость - <b>{0}</b>\nБроня - <b>{1}</b>\n" "Сила - <b>{2}</b>\nСкорость - <b>{3}</b>\n" "Заряд- <b>{4}</b>".format(player.stats.get("endurance"), player.stats.get("armor"), player.stats.get("power"), player.stats.get("speed"), player.stats.get("charge"), free_points, s), parse_mode='HTML', reply_markup=buttons) players.update({id: player}) players_need_update.put(player)
def lvl_up_skill(bot, update, user_data): id = update.message.from_user.id player = get_player(id) if player is None: return if update.message.text == "Готово": update_status("Lvl_up_points", player, user_data) bot.send_message(chat_id = update.message.from_user.id, text="Теперь выберите очки характеристик") choose_points(bot, update, user_data) else: player.lvl_up_skill(update.message.text) player.free_skill_points -= 1 players.update({id : player}) players_need_update.put(player) bot.send_message(chat_id = update.message.chat_id, text="Улучшен <b>{0}</b> скилл".format(update.message.text), parse_mode='HTML') choose_skill(bot, update, user_data)
def travel(bot, update, user_data): player = get_player(update.message.from_user.id) user_data.update({'location': player.location}) user_data.update({'location_name': locations.get(player.location).name}) current_location = locations.get(player.location) paths = current_location.roads path_buttons = [] for i in paths: path_buttons.append(KeyboardButton(locations.get(i).name)) path_buttons.append(KeyboardButton("Назад")) road_buttons = ReplyKeyboardMarkup(build_menu(path_buttons, n_cols=2), resize_keyboard=True, one_time_keyboard=True) bot.send_message(chat_id=update.message.chat_id, text="Вы в локации: {0}".format(current_location.name), reply_markup=road_buttons) update_status('Choosing way', player, user_data)
def choose_way(bot, update, user_data): if update.message.text == 'Назад': update_status('In Location', get_player(update.message.from_user.id), user_data) show_general_buttons(bot, update, user_data) return player = get_player(update.message.from_user.id) current_location = locations.get(player.location) paths = current_location.roads loc_name = update.message.text new_loc_id = 0 for i in paths.keys(): tmp_location = i if locations.get(tmp_location).name == loc_name: new_loc_id = tmp_location break if new_loc_id == 0: logging.error('ERROR: NO SUCH ID bot.py in choose_way, id = 0') else: update_status('Traveling', player, user_data) bot.send_message( chat_id=update.message.chat_id, text="Вы отправились в локацию: {0}, до нее идти {1} минут".format( locations.get(new_loc_id).name, paths.get(new_loc_id)), reply_markup=traveling_buttons) contexts = { 'chat_id': update.message.chat_id, 'location_id': new_loc_id, 'player': player, 'update': update, 'user_data': user_data } if filter_is_admin(update.message): bot.send_message(chat_id=update.message.chat_id, text="Вы можете использовать /fasttravel") user_data.update({'new_location': new_loc_id}) tmp_job = job.run_once(move_player, paths.get(new_loc_id) * 60, context=contexts) j = MyJob(tmp_job, paths.get(new_loc_id) * 60, update.message.chat_id) travel_jobs.update({player.id: j}) return
def return_to_location_admin(bot, update, user_data): player_id = update.message.chat_id player = get_player(player_id) update_status('In Location', player, user_data) update_location(player.location, player, user_data) j = travel_jobs.get(player.id) if pending_battles.get(user_data.get("Battle id")) is not None: pending_battles.pop(user_data.get("Battle id")) """list_user_data = list(user_data) if 'saved_battle_status' in list_user_data: user_data.pop('saved_battle_status') if 'chosen skill' in list_user_data: user_data.pop('chosen skill') if 'Battle waiting update' in list_user_data: user_data.pop('Battle waiting update') if 'Battle id' in list_user_data: user_data.pop('Battle id') if 'matchmaking' in list_user_data: user_data.pop('matchmaking') if 'Team' in list_user_data: user_data.pop('Team')""" if 'saved_info_status' in user_data: user_data.pop('saved_info_status') interprocess_dict = InterprocessDictionary(player.id, "battle status return", {}) interprocess_queue.put(interprocess_dict) try: grinding_players.remove(player) user_data.pop('grind_started') user_data.pop('farming_started') except Exception: pass #bot.send_message(chat_id=player_id,text="Вы вернулись в локацию: {0}".format(locations.get(player.location).name)) if j is None: return j.job.schedule_removal()
def merchant(bot, update, user_data): player = get_player(update.message.from_user.id) update_status('Merchant', player, user_data) user_data.update({'saved_merchant_status': 'In Location'}) show_general_buttons(bot, update, user_data)
def choose_skill(bot, update, user_data): id = update.message.from_user.id player = get_player(id) if player is None: return free_skill = player.free_skill_points if free_skill < 0: player.free_skill_points = 0 free_skill = 0 if free_skill == 0: button_list = [ KeyboardButton("Выносливость"), KeyboardButton("Броня"), KeyboardButton("Сила"), KeyboardButton("Скорость"), KeyboardButton("Заряд"), KeyboardButton("Готово") ] buttons = ReplyKeyboardMarkup(build_menu(button_list, n_cols=2), resize_keyboard=True, one_time_keyboard=False) bot.send_message(chat_id = update.message.chat_id, text = "У вас нет очков навыков\n\n" "{5} - {0}-го уровня\n{6} - {1}-го уровня\n" "{7} - {2}-го уровня\n{8} - {3}-го уровня\n" "{9} - {4}-го уровня".format(list(player.skill_lvl.values())[0], list(player.skill_lvl.values())[1], list(player.skill_lvl.values())[2], list(player.skill_lvl.values())[3], list(player.skill_lvl.values())[4], list(player.skill_lvl)[0], list(player.skill_lvl)[1], list(player.skill_lvl)[2], list(player.skill_lvl)[3], list(player.skill_lvl)[4]), reply_markup = buttons) update_status("Lvl_up_points", player, user_data) player.update_skills() players.update({id: player}) players_need_update.put(player) choose_points(bot, update, user_data) show_general_buttons(bot, update, user_data) player.lvl_check() return update_status("Lvl_up_skill", player, user_data) button_list = [ KeyboardButton("1"), KeyboardButton("2"), KeyboardButton("3"), KeyboardButton("4"), KeyboardButton("5"), KeyboardButton("Готово") ] buttons = ReplyKeyboardMarkup(build_menu(button_list, n_cols=2), resize_keyboard=True, one_time_keyboard = False) s = '' if free_skill == 1: s = "навык" elif free_skill >= 2 and free_skill <= 4: s = "навыка" elif free_skill >= 5: s = "навыков" bot.send_message(chat_id=update.message.chat_id, text="Вы можете улучшить <b>{5}</b> {6}\n\nВыберите навык, который хотите улучшить\n\n" "{7} - {0}-го уровня\n{8} - {1}-го уровня\n" "{9} - {2}-го уровня\n{10} - {3}-го уровня\n" "{11} - {4}-го уровня".format(list(player.skill_lvl.values())[0], list(player.skill_lvl.values())[1], list(player.skill_lvl.values())[2], list(player.skill_lvl.values())[3], list(player.skill_lvl.values())[4], free_skill, s, list(player.skill_lvl)[0], list(player.skill_lvl)[1], list(player.skill_lvl)[2], list(player.skill_lvl)[3], list(player.skill_lvl)[4]), parse_mode='HTML', reply_markup=buttons) players.update({id: player}) players_need_update.put(player)
def matchmaking_callback(bot, update, user_data): mes = update.callback_query.message matchmaking = user_data.get("matchmaking") if update.callback_query.data == "mm start" or update.callback_query.data == "mm cancel": group = user_data.get("battle_group") player = get_player(update.callback_query.from_user.id) if update.callback_query.data == "mm cancel": if user_data.get("status") != "Matchmaking" and user_data.get( "status" ) != "Battle": # TODO Как битвы будут готовы, удалить проверку на статус "Battle", сейчас используется для отладки bot.send_message(chat_id=update.callback_query.from_user.id, text="Вы не находитесь в поиске битвы") return player_matchmaking = Player_matchmaking(player, 0, matchmaking, group=group) matchmaking_players.put(player_matchmaking) bot.answerCallbackQuery(callback_query_id=update.callback_query.id, text="Подбор игроков успешно отменён", show_alert=False) try: bot.deleteMessage(chat_id=update.callback_query.from_user.id, message_id=mes.message_id) except Unauthorized: pass except BadRequest: pass new_status = user_data.get('saved_battle_status') update_status(new_status, player, user_data) matchmaking_start(bot, update.callback_query, user_data) return # Начало подбора игроков flag = 0 for i in matchmaking: if i == 1: flag = 1 break if flag == 0: bot.send_message(chat_id=update.callback_query.from_user.id, text="Необходимо выбрать хотя бы один режим") bot.answerCallbackQuery(callback_query_id=update.callback_query.id) return if group is not None and ( matchmaking[0] or (group.num_players() > 3 and matchmaking[1]) or (group.num_players() > 5 and matchmaking[2])): bot.answerCallbackQuery(callback_query_id=update.callback_query.id) bot.send_message( chat_id=update.callback_query.from_user.id, text= "Игроков в группе больше, чем разрешено в выбранных режимах! (Хотя бы одном)" ) return status = user_data.get("status") player.saved_battle_status = status player_matchmaking = Player_matchmaking(player, 1, matchmaking, group=group) # bot.answerCallbackQuery(callback_query_id=update.callback_query.id, text = "Подбор игроков успешно запущен!", show_alert = False) button_list = [ InlineKeyboardButton("Отменить подбор игроков", callback_data="mm cancel") ] reply_markup = InlineKeyboardMarkup(build_menu(button_list, n_cols=1)) try: bot.deleteMessage(chat_id=update.callback_query.from_user.id, message_id=mes.message_id) except TelegramError: pass bot.send_message(chat_id=update.callback_query.from_user.id, text="Подбор игроков запущен!", reply_markup=reply_markup) user_data.update( saved_battle_status=status) if status != 'Matchmaking' else 0 update_status('Matchmaking', player, user_data) matchmaking_players.put(player_matchmaking) return # Настройки матчмейкинга битв callback_data = update.callback_query.data if callback_data == "mm 1x1": matchmaking[0] = (matchmaking[0] + 1) % 2 elif callback_data == "mm 3x3": matchmaking[1] = (matchmaking[1] + 1) % 2 elif callback_data == "mm 5x5": matchmaking[2] = (matchmaking[2] + 1) % 2 first_button_text = "{0}1 x 1".format('✅' if matchmaking[0] else "") second_button_text = "{0}3 x 3".format('✅' if matchmaking[1] else "") third_button_text = "{0}5 x 5".format('✅' if matchmaking[2] else "") button_list = [ InlineKeyboardButton(first_button_text, callback_data="mm 1x1"), InlineKeyboardButton(second_button_text, callback_data="mm 3x3"), InlineKeyboardButton(third_button_text, callback_data="mm 5x5") ] footer_buttons = [ InlineKeyboardButton("Начать поиск", callback_data="mm start") ] reply_markup = InlineKeyboardMarkup( build_menu(button_list, n_cols=3, footer_buttons=footer_buttons)) try: bot.editMessageReplyMarkup(chat_id=mes.chat_id, message_id=mes.message_id, reply_markup=reply_markup) bot.answerCallbackQuery(callback_query_id=update.callback_query.id) except TelegramError: logging.error(traceback.format_exc) pass
def interprocess_monitor(): data = interprocess_queue.get() while data is not None: try: keys = list(data.data.keys()) if data.type == "user_data": user_data = dispatcher.user_data.get(data.id) player = get_player(data.id) if 'status' in keys: update_status(data.data.get('status'), player, user_data) data.data.pop('status') keys.remove('status') for user_data_record in keys: user_data.update( {user_data_record: data.data.get(user_data_record)}) #print(user_data) elif data.type == "battles_pending": for record in keys: pending_battles.update({record: data.data.get(record)}) print("put battle") elif data.type == "battle status return": dispatcher.user_data.get(data.id).update({ 'status': dispatcher.user_data.get( data.id).get('saved_battle_status') }) user_data = dispatcher.user_data.get(data.id) if user_data.get('status') == None: dispatcher.user_data.get(data.id).update( {'status': 'In Location'}) list_user_data = list(user_data) if 'saved_battle_status' in list_user_data: user_data.pop('saved_battle_status') if 'chosen skill' in list_user_data: user_data.pop('chosen skill') if 'Battle_waiting_to_count' in list_user_data: user_data.pop('Battle_waiting_to_count') if 'Battle id' in list_user_data: try: pending_battles.pop(user_data.get('Battle id')) except KeyError: pass user_data.pop('Battle id') if 'matchmaking' in list_user_data: user_data.pop('matchmaking') if 'Team' in list_user_data: user_data.pop('Team') if 'stunned' in list_user_data: user_data.pop('stunned') if 'Test' in list_user_data: user_data.pop('Test') player = get_player(data.id) player.saved_battle_status = None show_general_buttons(dispatcher.bot, player.id, user_data) elif data.type == "remove stun": user_data = dispatcher.user_data.get(data.id) list_user_data = list(user_data) if "stunned" in list_user_data: user_data.pop('stunned') elif data.type == "change_player_state": player = get_player(list(data.data)[0]) list_keys = list(data.data)[1:] for key in list_keys: change_value = data.data.get(key) if key == "exp": player.exp += change_value player.lvl_check() elif key == "dead": player.dead = change_value elif key == "resources": for new_key in change_value: delta = change_value.get(new_key) old_value = player.resourses.get(new_key) if old_value is None: continue old_value += delta player.resources.update({new_key: old_value}) elif key == "eq_backpack": for new_key in change_value: delta = change_value.get(new_key) old_value = player.eq_backpack.get(new_key) if old_value is None: continue old_value += delta player.resources.update({new_key: old_value}) elif key == "al_backpack": for new_key in change_value: delta = change_value.get(new_key) old_value = player.al_backpack.get(new_key) if old_value is None: continue old_value += delta player.resources.update({new_key: old_value}) elif key == "res_backpack": for new_key in change_value: delta = change_value.get(new_key) old_value = player.res_backpack.get(new_key) if old_value is None: continue old_value += delta player.resources.update({new_key: old_value}) players_need_update.put(player) except Exception: logging.error(traceback.format_exc()) data = interprocess_queue.get() return 0
def return_from_merchant(bot, update, user_data): player = get_player(update.message.from_user.id) update_status(user_data.get('saved_merchant_status'), player, user_data) user_data.pop('saved_merchant_status') show_general_buttons(bot, update, user_data)