-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
720 lines (563 loc) · 28.4 KB
/
main.py
File metadata and controls
720 lines (563 loc) · 28.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
import logging
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove
from telegram.ext import Application, CommandHandler, CallbackQueryHandler, ContextTypes, MessageHandler, filters, ConversationHandler
import random
from enum import Enum
from dataclasses import dataclass, field
from typing import Dict, List, Optional
# Настройка логирования
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
logger = logging.getLogger(__name__)
# Константы
TOKEN = '8182669714:AAEWze0bZ2QAfNOjLc8ulB0xt7HC2sU-Q70' # Замените на токен вашего бота
# Состояния для ConversationHandler
CHOOSE_PLAYERS, ENTER_NAMES, SETUP_ROLES, NIGHT_ACTION, DAY_DISCUSSION, VOTING = range(6)
class GamePhase(Enum):
SETUP = "setup"
NIGHT = "night"
MORNING = "morning"
DAY = "day"
VOTING = "voting"
ENDED = "ended"
class Role(Enum):
CIVILIAN = "Мирный житель"
MAFIA = "Мафия"
DON = "Дон мафии"
DETECTIVE = "Комиссар"
DOCTOR = "Доктор"
LOVER = "Любовница"
BODYGUARD = "Телохранитель"
JOURNALIST = "Журналист"
MANIAC = "Маньяк"
CHEMIST = "Химик"
GHOST = "Призрак"
@dataclass
class Player:
name: str
role: Optional[Role] = None
is_alive: bool = True
protected_by_doctor: bool = False
blocked_by_lover: bool = False
last_healed_by: Optional[str] = None
voted_for: Optional[str] = None
@dataclass
class MafiaGame:
host_id: int
players: List[Player] = field(default_factory=list)
phase: GamePhase = GamePhase.SETUP
night_actions: Dict[str, str] = field(default_factory=dict)
deaths_tonight: List[str] = field(default_factory=list)
day_number: int = 0
night_number: int = 0
# Настройки ролей
role_counts: Dict[Role, int] = field(default_factory=lambda: {
Role.MAFIA: 1,
Role.DON: 0,
Role.DETECTIVE: 1,
Role.DOCTOR: 1,
Role.LOVER: 0,
Role.BODYGUARD: 0,
Role.JOURNALIST: 0,
Role.MANIAC: 0,
Role.CHEMIST: 0,
Role.GHOST: 0,
})
# Хранилище игр
games: Dict[int, MafiaGame] = {}
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Приветственное сообщение"""
user_id = update.effective_user.id
welcome_text = """
🎭 Добро пожаловать в игру "МАФИЯ"!
🎯 **Правила и порядок действий**
🧩 **Основные принципы:**
• Игра делится на дни и ночи
• Каждый день и ночь — это один игровой цикл
• Цель каждой стороны — уничтожить других
**Стороны:**
🟩 Добрые (город) - мирные жители
🟥 Злые (мафия) - преступники
⚫ Нейтральные - играют за себя
🕰 **Этапы игры:**
1️⃣ Ночь 🌙 - Игроки с ночными способностями действуют
2️⃣ Утро ☀️ - Объявление результатов ночи
3️⃣ День 💬 - Обсуждение подозреваемых
4️⃣ Голосование 🗳 - Изгнание игрока
⚔️ **Приоритет ночных действий:**
1. Любовница (блокирует цель)
2. Доктор (лечит от убийства)
3. Химик (убивает игнорируя лечение)
4. Маньяк (убивает всех)
5. Мафия/Дон (убивают мирных)
6. Комиссар (проверяет игрока)
Готовы начать игру?
"""
keyboard = [[InlineKeyboardButton("🎮 СОЗДАТЬ ИГРУ", callback_data="create_game")]]
reply_markup = InlineKeyboardMarkup(keyboard)
await update.message.reply_text(welcome_text, reply_markup=reply_markup, parse_mode='Markdown')
return CHOOSE_PLAYERS
async def create_game_callback(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Переход к выбору количества игроков"""
query = update.callback_query
await query.answer()
text = "Выберите количество игроков:"
keyboard = [
[InlineKeyboardButton("4 игрока", callback_data="players_4")],
[InlineKeyboardButton("5 игроков", callback_data="players_5")],
[InlineKeyboardButton("6 игроков", callback_data="players_6")],
[InlineKeyboardButton("7 игроков", callback_data="players_7")],
[InlineKeyboardButton("8 игроков", callback_data="players_8")],
[InlineKeyboardButton("9 игроков", callback_data="players_9")],
[InlineKeyboardButton("10 игроков", callback_data="players_10")],
[InlineKeyboardButton("11 игроков", callback_data="players_11")],
[InlineKeyboardButton("12 игроков", callback_data="players_12")],
]
reply_markup = InlineKeyboardMarkup(keyboard)
await query.edit_message_text(text, reply_markup=reply_markup)
return CHOOSE_PLAYERS
async def create_game_callback(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Переход к выбору количества игроков"""
query = update.callback_query
await query.answer()
text = "Выберите количество игроков:"
keyboard = [
[InlineKeyboardButton("6 игроков", callback_data="players_6")],
[InlineKeyboardButton("7 игроков", callback_data="players_7")],
[InlineKeyboardButton("8 игроков", callback_data="players_8")],
[InlineKeyboardButton("9 игроков", callback_data="players_9")],
[InlineKeyboardButton("10 игроков", callback_data="players_10")],
[InlineKeyboardButton("11 игроков", callback_data="players_11")],
[InlineKeyboardButton("12 игроков", callback_data="players_12")],
]
reply_markup = InlineKeyboardMarkup(keyboard)
await query.edit_message_text(text, reply_markup=reply_markup)
return CHOOSE_PLAYERS
async def players_chosen(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Обработка выбора количества игроков"""
query = update.callback_query
await query.answer()
user_id = query.from_user.id
num_players = int(query.data.split("_")[1])
# Создаём новую игру
games[user_id] = MafiaGame(host_id=user_id)
context.user_data['num_players'] = num_players
context.user_data['current_player'] = 0
await query.edit_message_text(
f"✅ Выбрано игроков: {num_players}\n\n"
f"Теперь введите имя игрока №1:"
)
return ENTER_NAMES
async def receive_name(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Получение имён игроков"""
user_id = update.effective_user.id
game = games.get(user_id)
if not game:
await update.message.reply_text("❌ Ошибка! Начните заново с /start")
return ConversationHandler.END
player_name = update.message.text.strip()
if not player_name or len(player_name) > 20:
await update.message.reply_text("❌ Имя должно быть от 1 до 20 символов. Попробуйте снова:")
return ENTER_NAMES
# Добавляем игрока
game.players.append(Player(name=player_name))
context.user_data['current_player'] += 1
current = context.user_data['current_player']
total = context.user_data['num_players']
if current < total:
await update.message.reply_text(
f"✅ Добавлен: {player_name}\n\n"
f"Введите имя игрока №{current + 1}:"
)
return ENTER_NAMES
else:
# Все имена введены, переходим к настройке ролей
await update.message.reply_text(
f"✅ Добавлен: {player_name}\n\n"
f"Все {total} игроков добавлены!\n\n"
f"📋 Список игроков:\n" + "\n".join([f"{i+1}. {p.name}" for i, p in enumerate(game.players)])
)
await show_role_setup(update, context)
return SETUP_ROLES
async def show_role_setup(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Показать меню настройки ролей"""
user_id = update.effective_user.id
game = games.get(user_id)
num_players = len(game.players)
setup_text = f"""
⚙️ НАСТРОЙКА РОЛЕЙ
Всего игроков: {num_players}
Текущие роли:
"""
total_assigned = 0
for role, count in game.role_counts.items():
if count > 0:
setup_text += f"• {role.value}: {count}\n"
total_assigned += count
civilians = num_players - total_assigned
setup_text += f"• Мирные жители: {civilians}\n\n"
if civilians < 0:
setup_text += "⚠️ Слишком много ролей! Уменьшите количество.\n\n"
setup_text += "Выберите роль для настройки:"
keyboard = [
[InlineKeyboardButton("Мафия", callback_data="setup_MAFIA"),
InlineKeyboardButton("Дон", callback_data="setup_DON")],
[InlineKeyboardButton("Комиссар", callback_data="setup_DETECTIVE"),
InlineKeyboardButton("Доктор", callback_data="setup_DOCTOR")],
[InlineKeyboardButton("Любовница", callback_data="setup_LOVER"),
InlineKeyboardButton("Телохранитель", callback_data="setup_BODYGUARD")],
[InlineKeyboardButton("Маньяк", callback_data="setup_MANIAC"),
InlineKeyboardButton("Химик", callback_data="setup_CHEMIST")],
[InlineKeyboardButton("Журналист", callback_data="setup_JOURNALIST"),
InlineKeyboardButton("Призрак", callback_data="setup_GHOST")],
[InlineKeyboardButton("✅ НАЧАТЬ ИГРУ", callback_data="start_game")]
]
reply_markup = InlineKeyboardMarkup(keyboard)
await update.message.reply_text(setup_text, reply_markup=reply_markup)
async def role_setup_callback(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Обработка настройки ролей"""
query = update.callback_query
await query.answer()
user_id = query.from_user.id
game = games.get(user_id)
if query.data == "start_game":
return await start_game_process(update, context)
if query.data.startswith("setup_"):
role_name = query.data.replace("setup_", "")
role = Role[role_name]
keyboard = [
[InlineKeyboardButton("0", callback_data=f"set_{role_name}_0"),
InlineKeyboardButton("1", callback_data=f"set_{role_name}_1"),
InlineKeyboardButton("2", callback_data=f"set_{role_name}_2")],
[InlineKeyboardButton("3", callback_data=f"set_{role_name}_3"),
InlineKeyboardButton("4", callback_data=f"set_{role_name}_4")],
[InlineKeyboardButton("« Назад", callback_data="back_to_setup")]
]
reply_markup = InlineKeyboardMarkup(keyboard)
await query.edit_message_text(
f"Сколько {role.value}?\nТекущее: {game.role_counts[role]}",
reply_markup=reply_markup
)
return SETUP_ROLES
if query.data.startswith("set_"):
parts = query.data.split("_")
role_name = parts[1]
count = int(parts[2])
role = Role[role_name]
game.role_counts[role] = count
await query.answer(f"✅ {role.value}: {count}")
# Возвращаемся к общему меню
num_players = len(game.players)
setup_text = f"""
⚙️ НАСТРОЙКА РОЛЕЙ
Всего игроков: {num_players}
Текущие роли:
"""
total_assigned = 0
for r, c in game.role_counts.items():
if c > 0:
setup_text += f"• {r.value}: {c}\n"
total_assigned += c
civilians = num_players - total_assigned
setup_text += f"• Мирные жители: {civilians}\n\n"
if civilians < 0:
setup_text += "⚠️ Слишком много ролей! Уменьшите количество.\n\n"
setup_text += "Выберите роль для настройки:"
keyboard = [
[InlineKeyboardButton("Мафия", callback_data="setup_MAFIA"),
InlineKeyboardButton("Дон", callback_data="setup_DON")],
[InlineKeyboardButton("Комиссар", callback_data="setup_DETECTIVE"),
InlineKeyboardButton("Доктор", callback_data="setup_DOCTOR")],
[InlineKeyboardButton("Любовница", callback_data="setup_LOVER"),
InlineKeyboardButton("Телохранитель", callback_data="setup_BODYGUARD")],
[InlineKeyboardButton("Маньяк", callback_data="setup_MANIAC"),
InlineKeyboardButton("Химик", callback_data="setup_CHEMIST")],
[InlineKeyboardButton("Журналист", callback_data="setup_JOURNALIST"),
InlineKeyboardButton("Призрак", callback_data="setup_GHOST")],
[InlineKeyboardButton("✅ НАЧАТЬ ИГРУ", callback_data="start_game")]
]
reply_markup = InlineKeyboardMarkup(keyboard)
await query.edit_message_text(setup_text, reply_markup=reply_markup)
return SETUP_ROLES
if query.data == "back_to_setup":
num_players = len(game.players)
setup_text = f"""
⚙️ НАСТРОЙКА РОЛЕЙ
Всего игроков: {num_players}
Текущие роли:
"""
total_assigned = 0
for r, c in game.role_counts.items():
if c > 0:
setup_text += f"• {r.value}: {c}\n"
total_assigned += c
civilians = num_players - total_assigned
setup_text += f"• Мирные жители: {civilians}\n\n"
setup_text += "Выберите роль для настройки:"
keyboard = [
[InlineKeyboardButton("Мафия", callback_data="setup_MAFIA"),
InlineKeyboardButton("Дон", callback_data="setup_DON")],
[InlineKeyboardButton("Комиссар", callback_data="setup_DETECTIVE"),
InlineKeyboardButton("Доктор", callback_data="setup_DOCTOR")],
[InlineKeyboardButton("Любовница", callback_data="setup_LOVER"),
InlineKeyboardButton("Телохранитель", callback_data="setup_BODYGUARD")],
[InlineKeyboardButton("Маньяк", callback_data="setup_MANIAC"),
InlineKeyboardButton("Химик", callback_data="setup_CHEMIST")],
[InlineKeyboardButton("Журналист", callback_data="setup_JOURNALIST"),
InlineKeyboardButton("Призрак", callback_data="setup_GHOST")],
[InlineKeyboardButton("✅ НАЧАТЬ ИГРУ", callback_data="start_game")]
]
reply_markup = InlineKeyboardMarkup(keyboard)
await query.edit_message_text(setup_text, reply_markup=reply_markup)
return SETUP_ROLES
async def start_game_process(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Начало игры - раздача ролей"""
query = update.callback_query
user_id = query.from_user.id
game = games.get(user_id)
# Проверка корректности ролей
total_assigned = sum(game.role_counts.values())
num_players = len(game.players)
if total_assigned > num_players:
await query.answer("❌ Слишком много ролей!", show_alert=True)
return SETUP_ROLES
# Раздача ролей
roles_list = []
for role, count in game.role_counts.items():
roles_list.extend([role] * count)
# Добавляем мирных жителей
while len(roles_list) < num_players:
roles_list.append(Role.CIVILIAN)
random.shuffle(roles_list)
# Назначаем роли
for player, role in zip(game.players, roles_list):
player.role = role
# Показываем роли СО СПОЙЛЕРАМИ
roles_text = "🎭 ИГРА НАЧАЛАСЬ!\n\n📋 РОЛИ ИГРОКОВ:\n\n"
for i, player in enumerate(game.players, 1):
# Используем HTML теги для спойлера
roles_text += f"{i}. {player.name} - <span class=\"tg-spoiler\">{player.role.value}</span>\n"
roles_text += "\n🌙 Город засыпает, наступает НОЧЬ №1...\n\n"
roles_text += "Используйте команду /night для начала ночной фазы"
game.phase = GamePhase.NIGHT
game.night_number = 1
await query.edit_message_text(roles_text, parse_mode='HTML')
return ConversationHandler.END
async def night_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Команда для ночной фазы"""
user_id = update.effective_user.id
game = games.get(user_id)
if not game:
await update.message.reply_text("❌ Нет активной игры. Начните с /start")
return
night_text = f"🌙 НОЧЬ №{game.night_number}\n\n"
night_text += "Город спит. Просыпаются:\n\n"
# Показываем, кто действует ночью
for player in game.players:
if not player.is_alive:
continue
if player.role in [Role.LOVER, Role.DOCTOR, Role.MAFIA, Role.DON,
Role.DETECTIVE, Role.MANIAC, Role.CHEMIST, Role.BODYGUARD]:
night_text += f"• {player.name} ({player.role.value})\n"
night_text += "\n💬 Ведущий проводит ночные действия вручную.\n"
night_text += "После завершения ночи используйте /morning"
await update.message.reply_text(night_text)
async def morning_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Команда для утра"""
user_id = update.effective_user.id
game = games.get(user_id)
if not game:
await update.message.reply_text("❌ Нет активной игры.")
return
morning_text = f"☀️ УТРО после ночи №{game.night_number}\n\n"
morning_text += "Город просыпается...\n\n"
morning_text += "Ведущий объявляет, кто погиб этой ночью.\n\n"
morning_text += "Для отметки погибших используйте /kill <имя>\n"
morning_text += "Для начала дня используйте /day"
game.phase = GamePhase.MORNING
await update.message.reply_text(morning_text)
async def kill_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Отметить игрока как погибшего"""
user_id = update.effective_user.id
game = games.get(user_id)
if not game:
await update.message.reply_text("❌ Нет активной игры.")
return
if not context.args:
await update.message.reply_text("Использование: /kill <имя игрока>")
return
player_name = " ".join(context.args)
player_found = None
for player in game.players:
if player.name.lower() == player_name.lower() and player.is_alive:
player_found = player
break
if not player_found:
await update.message.reply_text(f"❌ Игрок '{player_name}' не найден среди живых.")
return
player_found.is_alive = False
await update.message.reply_text(f"💀 {player_found.name} ({player_found.role.value}) погиб!")
# Проверка победы
if check_victory(game):
await announce_victory(update, game)
async def day_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Начало дневного обсуждения"""
user_id = update.effective_user.id
game = games.get(user_id)
if not game:
await update.message.reply_text("❌ Нет активной игры.")
return
game.day_number += 1
game.phase = GamePhase.DAY
alive_players = [p for p in game.players if p.is_alive]
day_text = f"💬 ДЕНЬ №{game.day_number}\n\n"
day_text += f"Живых игроков: {len(alive_players)}\n\n"
day_text += "Список живых:\n"
for i, player in enumerate(alive_players, 1):
day_text += f"{i}. {player.name}\n"
day_text += "\n🗣 Начинается обсуждение!\n"
day_text += "После обсуждения используйте /vote для голосования"
await update.message.reply_text(day_text)
async def vote_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Начало голосования"""
user_id = update.effective_user.id
game = games.get(user_id)
if not game:
await update.message.reply_text("❌ Нет активной игры.")
return
game.phase = GamePhase.VOTING
alive_players = [p for p in game.players if p.is_alive]
vote_text = "🗳 ГОЛОСОВАНИЕ\n\n"
vote_text += "Кого изгнать из города?\n\n"
for i, player in enumerate(alive_players, 1):
vote_text += f"{i}. {player.name}\n"
vote_text += "\nВедущий собирает голоса.\n"
vote_text += "Для изгнания используйте: /exile <имя>"
await update.message.reply_text(vote_text)
async def exile_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Изгнать игрока по результатам голосования"""
user_id = update.effective_user.id
game = games.get(user_id)
if not game:
await update.message.reply_text("❌ Нет активной игры.")
return
if not context.args:
await update.message.reply_text("Использование: /exile <имя игрока>")
return
player_name = " ".join(context.args)
player_found = None
for player in game.players:
if player.name.lower() == player_name.lower() and player.is_alive:
player_found = player
break
if not player_found:
await update.message.reply_text(f"❌ Игрок '{player_name}' не найден среди живых.")
return
player_found.is_alive = False
await update.message.reply_text(
f"🏛 Город изгнал: {player_found.name}\n"
f"Роль: {player_found.role.value}"
)
# Проверка победы
if check_victory(game):
await announce_victory(update, game)
else:
await update.message.reply_text(
f"\n🌙 Наступает ночь №{game.night_number + 1}\n"
f"Используйте /night"
)
game.night_number += 1
def check_victory(game: MafiaGame) -> bool:
"""Проверка условий победы"""
alive_players = [p for p in game.players if p.is_alive]
mafia_count = sum(1 for p in alive_players if p.role in [Role.MAFIA, Role.DON, Role.CHEMIST])
town_count = sum(1 for p in alive_players if p.role not in [Role.MAFIA, Role.DON, Role.CHEMIST, Role.MANIAC])
maniac_alive = any(p for p in alive_players if p.role == Role.MANIAC)
# Мафия победила
if mafia_count >= town_count and not maniac_alive:
game.phase = GamePhase.ENDED
return True
# Город победил
if mafia_count == 0 and not maniac_alive:
game.phase = GamePhase.ENDED
return True
# Маньяк победил
if len(alive_players) == 1 and maniac_alive:
game.phase = GamePhase.ENDED
return True
return False
async def announce_victory(update: Update, game: MafiaGame):
"""Объявление победителя"""
alive_players = [p for p in game.players if p.is_alive]
mafia_count = sum(1 for p in alive_players if p.role in [Role.MAFIA, Role.DON, Role.CHEMIST])
maniac_alive = any(p for p in alive_players if p.role == Role.MANIAC)
if maniac_alive and len(alive_players) == 1:
winner_text = "🎊 ПОБЕДА МАНЬЯКА!"
elif mafia_count >= len(alive_players) - mafia_count:
winner_text = "🎊 ПОБЕДА МАФИИ!"
else:
winner_text = "🎊 ПОБЕДА МИРНЫХ ЖИТЕЛЕЙ!"
winner_text += "\n\n📋 Все роли:\n\n"
for player in game.players:
status = "💀" if not player.is_alive else "✅"
# Роли со спойлером
winner_text += f"{status} {player.name} - <span class=\"tg-spoiler\">{player.role.value}</span>\n"
winner_text += "\n\nДля новой игры используйте /start"
await update.message.reply_text(winner_text, parse_mode='HTML')
async def status_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Показать текущее состояние игры"""
user_id = update.effective_user.id
game = games.get(user_id)
if not game:
await update.message.reply_text("❌ Нет активной игры. Начните с /start")
return
status_text = f"📊 СОСТОЯНИЕ ИГРЫ\n\n"
status_text += f"Фаза: {game.phase.value}\n"
status_text += f"День: {game.day_number}\n"
status_text += f"Ночь: {game.night_number}\n\n"
alive_count = sum(1 for p in game.players if p.is_alive)
status_text += f"Живых игроков: {alive_count}/{len(game.players)}\n\n"
status_text += "Игроки:\n"
for player in game.players:
status = "✅" if player.is_alive else "💀"
# Роли со спойлером
status_text += f"{status} {player.name} - <span class=\"tg-spoiler\">{player.role.value}</span>\n"
await update.message.reply_text(status_text, parse_mode='HTML')
async def cancel(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Отмена создания игры"""
user_id = update.effective_user.id
if user_id in games:
del games[user_id]
await update.message.reply_text("❌ Создание игры отменено. Для новой игры используйте /start")
return ConversationHandler.END
def main():
"""Запуск бота"""
application = Application.builder().token(TOKEN).build()
# ConversationHandler для создания игры
conv_handler = ConversationHandler(
entry_points=[CommandHandler('start', start)],
states={
CHOOSE_PLAYERS: [
CallbackQueryHandler(create_game_callback, pattern="^create_game$"),
CallbackQueryHandler(players_chosen, pattern="^players_\\d+$")
],
ENTER_NAMES: [MessageHandler(filters.TEXT & ~filters.COMMAND, receive_name)],
SETUP_ROLES: [CallbackQueryHandler(role_setup_callback)],
},
fallbacks=[CommandHandler('cancel', cancel)],
)
application.add_handler(conv_handler)
# Обработчик для кнопки "Следующий игрок"
application.add_handler(CallbackQueryHandler(next_role_callback, pattern="^next_role$"))
# Команды для управления игрой
application.add_handler(CommandHandler("night", night_command))
application.add_handler(CommandHandler("morning", morning_command))
application.add_handler(CommandHandler("day", day_command))
application.add_handler(CommandHandler("vote", vote_command))
application.add_handler(CommandHandler("kill", kill_command))
application.add_handler(CommandHandler("exile", exile_command))
application.add_handler(CommandHandler("status", status_command))
# Запуск бота
logger.info("Бот запущен!")
application.run_polling(allowed_updates=Update.ALL_TYPES)
if __name__ == '__main__':
main()