from telegram import Update, WebAppInfo, KeyboardButton, ReplyKeyboardMarkup from telegram.ext import ContextTypes from database import Database import json db = Database() async def start_command(update: Update, context: ContextTypes.DEFAULT_TYPE): keyboard = [ [ KeyboardButton( "Открыть счётчик 🎲", web_app=WebAppInfo(url=context.bot_data['webapp_url']) ) ], [KeyboardButton("Новая игра 🎮"), KeyboardButton("Статистика 📊")], [KeyboardButton("Завершить игру 🏁")] ] reply_markup = ReplyKeyboardMarkup(keyboard, resize_keyboard=True) await update.message.reply_text( "🎲 Добро пожаловать в счётчик кубиков для нард!\n\n" "Выберите действие:", reply_markup=reply_markup ) async def new_game_command(update: Update, context: ContextTypes.DEFAULT_TYPE): user = update.effective_user # Проверяем, нет ли уже активной игры active_game = db.get_active_game(user.id) if active_game: await update.message.reply_text( "❗️ У вас уже есть активная игра. " "Сначала завершите её командой /end_game" ) return game_id = db.create_game(user.id, user.username) context.user_data['current_game'] = game_id await update.message.reply_text( "🎮 Новая игра начата!\n" "Используйте кнопку «Открыть счётчик» для записи бросков." ) async def handle_webapp_data(update, context): try: data = json.loads(update.effective_message.web_app_data.data) if data['type'] == 'game_session': # Получаем активную игру пользователя game = db.get_active_game(update.effective_user.id) if game: # Записываем все броски for throw in data['throws']: db.add_throw( game['id'], throw['dice'][0], throw['dice'][1] ) # Завершаем игру db.end_game(game['id']) # Отправляем сообщение об успешном завершении await update.message.reply_text( f"Игра завершена! Записано {len(data['throws'])} бросков.\n" f"Используйте /statistics для просмотра статистики." ) else: await update.message.reply_text( "Ошибка: активная игра не найдена.\n" "Используйте /new_game для начала новой игры." ) except Exception as e: print(f"Error handling webapp data: {e}") await update.message.reply_text("Произошла ошибка при обработке данных.") async def statistics_command(update: Update, context: ContextTypes.DEFAULT_TYPE): user_id = update.effective_user.id stats = db.get_statistics(user_id) # Получаем активную игру active_game = db.get_active_game(user_id) response = "📊 Ваша статистика:\n\n" if stats['total_throws']: response += ( f"Всего игр: {stats['total_games']}\n" f"Всего бросков: {stats['total_throws']}\n" f"Средняя сумма: {stats['avg_sum']:.2f}\n" ) if active_game: game_throws = db.get_game_throws(active_game['id']) response += f"\nТекущая игра:\n" response += f"Количество бросков: {len(game_throws)}\n" if game_throws: last_throw = game_throws[0] response += f"Последний бросок: {last_throw['dice1']}-{last_throw['dice2']}" else: response += "У вас пока нет записанных бросков." await update.message.reply_text(response) async def end_game_command(update: Update, context: ContextTypes.DEFAULT_TYPE): game_id = context.user_data.get('current_game') if not game_id: await update.message.reply_text("❌ У вас нет активной игры!") return game_throws = db.get_game_throws(game_id) db.end_game(game_id) del context.user_data['current_game'] response = "🏁 Игра завершена!\n\n" if game_throws: total_throws = len(game_throws) avg_sum = sum(t['dice1'] + t['dice2'] for t in game_throws) / total_throws response += ( f"Статистика игры:\n" f"Всего бросков: {total_throws}\n" f"Средняя сумма: {avg_sum:.2f}" ) else: response += "В игре не было записано ни одного броска." await update.message.reply_text(response)