File size: 28,868 Bytes
3a3b605
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""الألعاب الشاملة (35+ لعبة):
كت، صراحة، اسألني، تويت، لو خيروك، تحدي، حزورة/لغز/فزورة، تفكيك/فكك، تركيب/ترتيب، رياضيات، أسرع/كلمات،
ثقافة/أسئلة، علم، انكليزي، عربي (مفرد/جمع)، كورة، سيارات، حيوانات، مشهور، ممثلين، مغنين، لاعبين، أنمي،
دين، أكمل المثل، محيبس، حجرة ورقة مقص، اكس او، العكس، معاني، المختلف، سمايلات، بات، خمن (3 محاولات)،
حروف، الروليت بالانضمام، الحظ/حظي، نقاطي، توب النقاط، + لعبة المستذئب المصرية."""
import random
import re
import time
from telegram import InlineKeyboardMarkup
from telegram.ext import CallbackQueryHandler
from core.router import exact, norm
from core import content
from core.store import bump, get_counter, stats
from core.kb import btn
from modules.toggles import tg_on
from modules import settings_mod
from strings_ar import S


def _games_ok(update):
    return tg_on(update.effective_chat.id, "games")


def _make_reply(game):
    async def h(update, ctx, arg=""):
        if not _games_ok(update):
            await update.message.reply_text(S["games_off"])
            return
        line = content.pick(game)
        if not line:
            if game == "كت":
                await update.message.reply_text(S["empty_kit"])
            elif game == "صراحه":
                await update.message.reply_text(S["empty_saraha"])
            else:
                await update.message.reply_text(S["no_content"])
            return
        kb = settings_mod.kb_markup(update.effective_chat.id)
        await update.message.reply_text(line, reply_markup=kb)
    return h


for g in ("كت", "صراحه", "اسالني", "تويت", "لو خيروك", "عواصم", "امثال", "معلومات دينيه"):
    exact(norm(g))(_make_reply(g))

exact("كت تويت")(_make_reply("تويت"))
exact("خيروك")(_make_reply("لو خيروك"))
exact("امثله", "امثلة")(_make_reply("امثال"))
exact("دين")(_make_reply("معلومات دينيه"))


@exact("تحدي")
async def tahaddi(update, ctx, arg=""):
    if not _games_ok(update):
        await update.message.reply_text(S["games_off"])
        return
    kb = InlineKeyboardMarkup([
        [btn("مستوى ضعيف", "th:1", style="success")],
        [btn("مستوى متوسط", "th:2", style="primary")],
        [btn("مستوى صعب", "th:3", style="danger")]])
    await update.message.reply_text(S["tahaddi_pick"], reply_markup=kb)


async def tahaddi_cb(update, ctx):
    q = update.callback_query
    await q.answer()
    line = content.pick("تحدي") or S["no_content"]
    lvl = {"1": "ضعيف", "2": "متوسط", "3": "صعب"}.get(q.data.split(":")[1], "")
    await q.edit_message_text(f"◂ {line} ↫\n✧︙المستوى: {lvl}")


def _split_answer(line):
    m = re.match(r"^(?:حزوره:\s*)?(.*?)\s*\((.+?)\)\s*$", line)
    return (m.group(1), m.group(2)) if m else (line, None)


def _start_round(ctx, rtype, ans, raw, extra=None):
    d = {"type": rtype, "ans": norm(ans), "raw": raw, "t": time.time()}
    if extra:
        d.update(extra)
    ctx.chat_data["round"] = d


@exact("حزوره", "حزورة", "لغز", "فزوره", "فزورة")
async def hazura(update, ctx, arg=""):
    if not _games_ok(update):
        await update.message.reply_text(S["games_off"])
        return
    line = content.pick("حزوره")
    if not line:
        await update.message.reply_text(S["no_content"])
        return
    q, a = _split_answer(line)
    _start_round(ctx, "hazura", a or "", a)
    await update.message.reply_text(f"🧩 {q}")


@exact("ثقافه", "ثقافة", "اسئله", "اسئلة")
async def thaqafa(update, ctx, arg=""):
    if not _games_ok(update):
        await update.message.reply_text(S["games_off"])
        return
    items = content.lines("thaqafa.txt")
    if not items:
        await update.message.reply_text(S["no_content"])
        return
    line = random.choice(items)
    m = re.match(r"^ثقافه:\s*(.*?)\s*\((.+?)\)\s*$", line)
    if not m:
        await update.message.reply_text(S["no_content"])
        return
    q, a = m.group(1), m.group(2)
    _start_round(ctx, "hazura", a, a)
    await update.message.reply_text(f"🧠 {q}\n✧︙أسرع إجابة صح = نقطة")


QUIZ_FUNCS = {}


def _mk_quiz(cmd, filename, emoji, *aliases):
    async def h(update, ctx, arg=""):
        if not _games_ok(update):
            await update.message.reply_text(S["games_off"])
            return
        items = content.lines(filename)
        if not items:
            await update.message.reply_text(S["no_content"])
            return
        line = random.choice(items)
        q, a = _split_answer(line)
        if not a:
            await update.message.reply_text(S["no_content"])
            return
        q = re.sub(r"^\S+:\s*", "", q)
        _start_round(ctx, "hazura", a, a)
        await update.message.reply_text(f"{emoji} {q}\n✧︙أسرع إجابة صح = نقطة")
    for name in (cmd,) + aliases:
        exact(name)(h)
    QUIZ_FUNCS[cmd] = h
    return h


_mk_quiz("علم", "flags.txt", "🚩", "اعلام", "العلم")
_mk_quiz("انكليزي", "eng.txt", "🔤", "انجليزي", "الانكليزي")
_mk_quiz("كورة", "kora.txt", "⚽", "كوره")
_mk_quiz("سيارات", "cars.txt", "🚗")
_mk_quiz("حيوانات", "animals.txt", "🦁")
_mk_quiz("مشهور", "celebs.txt", "⭐", "مشاهير", "خمن المشهور")
_mk_quiz("انمي", "anime.txt", "🎌", "الأنمي")
_mk_quiz("عربي", "arabi.txt", "📖", "مفرد وجمع")
_mk_quiz("ممثلين", "actors.txt", "🎬")
_mk_quiz("مغنين", "singers.txt", "🎤")
_mk_quiz("لاعبين", "players.txt", "🏃‍♂️")


@exact("العكس", "عكس")
async def aks_game(update, ctx, arg=""):
    if not _games_ok(update):
        await update.message.reply_text(S["games_off"])
        return
    items = content.lines("aks.txt")
    if not items:
        await update.message.reply_text(S["no_content"])
        return
    q, a = _split_answer(random.choice(items))
    _start_round(ctx, "hazura", a, a)
    await update.message.reply_text(S["aks_q"].format(word=q))


@exact("معاني", "المعاني")
async def maani_game(update, ctx, arg=""):
    if not _games_ok(update):
        await update.message.reply_text(S["games_off"])
        return
    items = content.lines("maani.txt")
    if not items:
        await update.message.reply_text(S["no_content"])
        return
    q, a = _split_answer(random.choice(items))
    _start_round(ctx, "hazura", a, a)
    await update.message.reply_text(S["maani_q"].format(emoji=q))


@exact("المختلف", "مختلف")
async def mokhtalif_game(update, ctx, arg=""):
    if not _games_ok(update):
        await update.message.reply_text(S["games_off"])
        return
    items = content.lines("mokhtalif.txt")
    if not items:
        await update.message.reply_text(S["no_content"])
        return
    q, a = _split_answer(random.choice(items))
    _start_round(ctx, "speed", a, a)
    await update.message.reply_text(S["mokhtalif_q"].format(row=q))


@exact("سمايلات", "السمايلات")
async def smiles_game(update, ctx, arg=""):
    if not _games_ok(update):
        await update.message.reply_text(S["games_off"])
        return
    items = content.lines("smiles.txt")
    if not items:
        await update.message.reply_text(S["no_content"])
        return
    em = random.choice(items)
    _start_round(ctx, "speed", em, em)
    await update.message.reply_text(S["smile_q"].format(emoji=em))


@exact("بات", "البات")
async def bat_game(update, ctx, arg=""):
    if not _games_ok(update):
        await update.message.reply_text(S["games_off"])
        return
    items = content.lines("bat.txt")
    if not items:
        await update.message.reply_text(S["no_content"])
        return
    q, a = _split_answer(random.choice(items))
    _start_round(ctx, "hazura", a, a)
    await update.message.reply_text(S["bat_q"].format(q=q))


@exact("خمن", "تخمين")
async def khammen_game(update, ctx, arg=""):
    if not _games_ok(update):
        await update.message.reply_text(S["games_off"])
        return
    items = content.lines("khammen.txt")
    if not items:
        await update.message.reply_text(S["no_content"])
        return
    hint, a = _split_answer(random.choice(items))
    _start_round(ctx, "khammen", a, a, extra={"tries": 3})
    await update.message.reply_text(S["khammen_q"].format(hint=hint))


@exact("الحظ", "حظي")
async def luck_game(update, ctx, arg=""):
    if not _games_ok(update):
        await update.message.reply_text(S["games_off"])
        return
    win = random.random() < 0.55
    if win:
        pts = bump(update.effective_chat.id, update.effective_user.id, "pts", 2)
        await update.message.reply_text(f"🍀 حظك حلو يا {update.effective_user.first_name}! كسبت +2 نقاط 🎉 (نقاطك: {pts})")
    else:
        await update.message.reply_text(f"😅 حظ أوفر المرة الجاية يا {update.effective_user.first_name}!")


AR_LETTERS = list("ابتثجحخدذرزسشصضطظعغفقكلمنهوي")


@exact("حروف", "حر")
async def horoof_game(update, ctx, arg=""):
    if not _games_ok(update):
        await update.message.reply_text(S["games_off"])
        return
    await update.message.reply_text(S["horoof_q"].format(letter=random.choice(AR_LETTERS)))


# ---------- لعبة الروليت الجماعية بالانضمام ----------
@exact("الروليت", "روليت جماعي", "لعبه روليت", "لعبة روليت")
async def group_roulette(update, ctx, arg=""):
    if not _games_ok(update):
        await update.message.reply_text(S["games_off"])
        return
    chat_id = update.effective_chat.id
    rid = f"{chat_id}:{int(time.time())}"
    ctx.chat_data.setdefault("gr", {})[rid] = {
        "host": update.effective_user.id,
        "players": {update.effective_user.id: update.effective_user.first_name},
    }
    kb = InlineKeyboardMarkup([
        [btn("🎟️ انضمام للروليت", f"gr:join:{rid}", style="success")],
        [btn("🎡 ابدأ السحب", f"gr:spin:{rid}", style="primary"),
         btn("❌ إلغاء", f"gr:cancel:{rid}", style="danger")],
    ])
    await update.message.reply_text(
        f"🎡 لعبة الروليت الجماعية بدأت!\n"
        f"✧︙المنضمين (1): {update.effective_user.first_name}\n"
        f"✧︙دوس (انضمام) للمشاركة، والمضيف يدوس (ابدأ السحب)!",
        reply_markup=kb,
    )


async def group_roulette_cb(update, ctx):
    q = update.callback_query
    parts = q.data.split(":", 2)
    action, rid = parts[1], parts[2]
    grs = ctx.chat_data.get("gr") or {}
    g = grs.get(rid)
    if not g:
        await q.answer("✧︙الجولة انتهت.", show_alert=True)
        return
    if action == "join":
        uid = q.from_user.id
        if uid in g["players"]:
            await q.answer("انت منضم بالفعل! 🎟️", show_alert=True)
            return
        g["players"][uid] = q.from_user.first_name
        await q.answer("انضممت للروليت ✅")
        names = "، ".join(g["players"].values())
        kb = InlineKeyboardMarkup([
            [btn("🎟️ انضمام للروليت", f"gr:join:{rid}", style="success")],
            [btn("🎡 ابدأ السحب", f"gr:spin:{rid}", style="primary"),
             btn("❌ إلغاء", f"gr:cancel:{rid}", style="danger")],
        ])
        await q.edit_message_text(f"🎡 لعبة الروليت الجماعية!\n✧︙المنضمين ({len(g['players'])}): {names}", reply_markup=kb)
        return
    if action == "cancel":
        if q.from_user.id != g["host"]:
            await q.answer("المضيف بس يقدر يلغي.", show_alert=True)
            return
        grs.pop(rid, None)
        await q.answer()
        await q.edit_message_text("✧︙تم إلغاء الروليت.")
        return
    if action == "spin":
        if q.from_user.id != g["host"]:
            await q.answer("المضيف بس يقدر يبدأ السحب.", show_alert=True)
            return
        if len(g["players"]) < 2:
            await q.answer("لازم لاعبين على الأقل!", show_alert=True)
            return
        grs.pop(rid, None)
        wid = random.choice(list(g["players"].keys()))
        wname = g["players"][wid]
        pts = bump(q.message.chat.id, wid, "pts", 3)
        await q.answer()
        await q.edit_message_text(f"🎡 انتهى السحب من بين {len(g['players'])} لاعبين!\n🎉 الفائز: {wname} 🏆 (+3 نقاط)\n✧︙نقاطه الآن: {pts}")


@exact("اكمل المثل")
async def akmel(update, ctx, arg=""):
    if not _games_ok(update):
        await update.message.reply_text(S["games_off"])
        return
    items = content.lines("amthal.txt")
    if not items:
        await update.message.reply_text(S["no_content"])
        return
    words = random.choice(items).split()
    if len(words) < 4:
        return
    cut = max(2, len(words) // 2)
    first, ans = " ".join(words[:cut]), " ".join(words[cut:])
    _start_round(ctx, "hazura", ans, ans)
    await update.message.reply_text(S["akmel_q"].format(first=first))


@exact("تركيب", "ترتيب")
async def tarkib(update, ctx, arg=""):
    if not _games_ok(update):
        await update.message.reply_text(S["games_off"])
        return
    w = content.tafkik_word()
    if not w:
        await update.message.reply_text(S["no_content"])
        return
    w = w.replace(" ", "")
    letters = list(w)
    random.shuffle(letters)
    shuffled = " ".join(letters)
    _start_round(ctx, "hazura", w, w)
    await update.message.reply_text(S["tarkib_q"].format(letters=shuffled))


@exact("نقاطي")
async def my_pts(update, ctx, arg=""):
    pts = get_counter(update.effective_chat.id, update.effective_user.id, "pts")
    await update.message.reply_text(f"🏆 نقاطك في الألعاب: {pts}")


@exact("توب النقاط", "توب الالعاب", "الاعبين")
async def top_pts(update, ctx, arg=""):
    d = stats.get(update.effective_chat.id, "pts", {})
    if not d:
        await update.message.reply_text(S["top_empty"])
        return
    best = sorted(d.items(), key=lambda x: -x[1])[:10]
    lines = [S["top_pts"]]
    for i, (u, n) in enumerate(best, 1):
        try:
            m = await update.effective_chat.get_member(int(u))
            nm = m.user.first_name
        except Exception:
            nm = u
        lines.append(f"{i}. {nm} — {n}")
    await update.message.reply_text("\n".join(lines))


# ---------- محيبس + حجره ورقه مقص + تفكيك + رياضيات + اسرع ----------
@exact("محيبس", "المحيبس")
async def mahbas(update, ctx, arg=""):
    if not _games_ok(update):
        await update.message.reply_text(S["games_off"])
        return
    n = random.randint(1, 5)
    kb = InlineKeyboardMarkup([
        [btn(f"✊ {i}", f"mh:{n}:{i}", style="primary") for i in range(1, 4)],
        [btn(f"✊ {i}", f"mh:{n}:{i}", style="primary") for i in range(4, 6)],
    ])
    await update.message.reply_text(S["mahbas_q"], reply_markup=kb)


async def mahbas_cb(update, ctx):
    q = update.callback_query
    await q.answer()
    _, n, pick = q.data.split(":")
    n, pick = int(n), int(pick)
    if pick == n:
        pts = bump(q.message.chat.id, q.from_user.id, "pts")
        await q.edit_message_text(S["mahbas_win"].format(name=q.from_user.first_name, n=n, pts=pts))
    else:
        await q.edit_message_text(S["mahbas_lose"].format(name=q.from_user.first_name, pick=pick, n=n))


RPS = {"حجره": "✊", "ورقه": "✋", "مقص": "✌️"}
BEATS = {"حجره": "مقص", "ورقه": "حجره", "مقص": "ورقه"}


@exact("حجره", "حجره ورقه مقص", "حجرة")
async def rps_game(update, ctx, arg=""):
    if not _games_ok(update):
        await update.message.reply_text(S["games_off"])
        return
    kb = InlineKeyboardMarkup([[
        btn("✊ حجره", "rps:حجره", style="primary"),
        btn("✋ ورقه", "rps:ورقه", style="primary"),
        btn("✌️ مقص", "rps:مقص", style="primary")]])
    await update.message.reply_text(S["rps_q"], reply_markup=kb)


async def rps_cb(update, ctx):
    q = update.callback_query
    await q.answer()
    me = q.data.split(":", 1)[1]
    bot = random.choice(list(RPS))
    mine, bots = f"{RPS[me]} {me}", f"{RPS[bot]} {bot}"
    if me == bot:
        await q.edit_message_text(S["rps_draw"].format(a=mine))
    elif BEATS[me] == bot:
        pts = bump(q.message.chat.id, q.from_user.id, "pts")
        await q.edit_message_text(S["rps_win"].format(name=q.from_user.first_name, a=mine, b=bots, pts=pts))
    else:
        await q.edit_message_text(S["rps_lose"].format(name=q.from_user.first_name, a=mine, b=bots))


@exact("تفكيك", "فكك")
async def tafkik(update, ctx, arg=""):
    if not _games_ok(update):
        await update.message.reply_text(S["games_off"])
        return
    w = content.tafkik_word()
    if not w:
        await update.message.reply_text(S["no_content"])
        return
    ans = " ".join(w.replace(" ", ""))
    _start_round(ctx, "tafkik", ans, ans)
    await update.message.reply_text(S["tafkik_q"].format(word=w))


@exact("رياضيات", "حساب")
async def math_game(update, ctx, arg=""):
    if not _games_ok(update):
        await update.message.reply_text(S["games_off"])
        return
    a, b = random.randint(3, 50), random.randint(3, 30)
    op = random.choice(["+", "-", "×"])
    res = {"+": a + b, "-": a - b, "×": a * b}[op]
    _start_round(ctx, "math", str(res), str(res))
    await update.message.reply_text(S["math_q"].format(expr=f"{a} {op} {b}"))


@exact("اسرع", "الاسرع", "كلمات")
async def speed_game(update, ctx, arg=""):
    if not _games_ok(update):
        await update.message.reply_text(S["games_off"])
        return
    w = content.tafkik_word()
    if not w:
        await update.message.reply_text(S["no_content"])
        return
    w = w.replace(" ", "")
    _start_round(ctx, "speed", w, w)
    await update.message.reply_text(S["speed_q"].format(word=w))


async def check_answer(update, ctx, is_cmd):
    r = ctx.chat_data.get("round")
    if not r or not update.message or not update.message.text or is_cmd:
        return False
    if time.time() - r["t"] > 120:
        ctx.chat_data.pop("round", None)
        return False
    txt = re.sub(r"\s+", " ", norm(update.message.text)).strip()
    if not txt:
        return False
    target = norm(r["raw"]) if r["type"] == "speed" else r["ans"]
    if target and (txt == target or (r["type"] in ("hazura", "khammen") and target in txt)):
        ctx.chat_data.pop("round", None)
        sec = int(time.time() - r["t"])
        bonus = 2 if r["type"] == "khammen" else 1
        pts = bump(update.effective_chat.id, update.effective_user.id, "pts", bonus)
        await update.message.reply_text(S["game_answer_fast"].format(
            name=update.effective_user.first_name, sec=sec, ans=r["raw"], pts=pts))
        return True
    if r["type"] == "khammen" and target and len(txt) <= 40:
        r["tries"] = r.get("tries", 1) - 1
        if r["tries"] <= 0:
            ctx.chat_data.pop("round", None)
            await update.message.reply_text(S["game_wrong"].format(ans=r["raw"]))
        else:
            await update.message.reply_text(S["khammen_try"].format(left=r["tries"]))
        return True
    if r["type"] in ("hazura", "tafkik") and target and len(txt) <= 40 and txt not in ("حزوره", "تفكيك", "فكك", "لغز"):
        ctx.chat_data.pop("round", None)
        await update.message.reply_text(S["game_wrong"].format(ans=r["raw"]))
        return True
    return False


# ---------- اكس او ----------
XO_E = "⬜"


def _xo_board_kb(gid, board):
    return InlineKeyboardMarkup([
        [btn(board[r * 3 + i] or XO_E, f"xo:m:{gid}:{r * 3 + i}", style="primary") for i in range(3)]
        for r in range(3)
    ])


def _xo_winner(b):
    for x, y, z in ((0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7), (2, 5, 8), (0, 4, 8), (2, 4, 6)):
        if b[x] and b[x] == b[y] == b[z]:
            return b[x]
    return None


@exact("اكس او", "اكس-او")
async def xo_start(update, ctx, arg=""):
    if not _games_ok(update):
        await update.message.reply_text(S["games_off"])
        return
    t = update.message.reply_to_message.from_user if update.message.reply_to_message else None
    if not t or t.id == update.effective_user.id or t.is_bot:
        await update.message.reply_text(S["xo_need_reply"])
        return
    gid = f"{update.effective_chat.id}:{update.effective_user.id}"
    ctx.chat_data.setdefault("xo_ch", {})[gid] = {
        "a": update.effective_user.id, "an": update.effective_user.first_name,
        "b": t.id, "bn": t.first_name, "t": time.time()}
    kb = InlineKeyboardMarkup([[btn("✅ اقبل التحدي", f"xo:yes:{gid}", style="success"), btn("❌ ارفض", f"xo:no:{gid}", style="danger")]])
    await update.message.reply_text(S["xo_challenge"].format(a=update.effective_user.first_name, b=t.first_name), reply_markup=kb)


async def xo_cb(update, ctx):
    q = update.callback_query
    parts = q.data.split(":")
    action = parts[1]
    chat = update.effective_chat
    if action == "no":
        gid = ":".join(parts[2:])
        ch = (ctx.chat_data.get("xo_ch") or {}).get(gid)
        if ch and q.from_user.id in (ch["a"], ch["b"]):
            ctx.chat_data["xo_ch"].pop(gid, None)
            await q.answer()
            await q.edit_message_text("✧︙اتلغى التحدي.")
        else:
            await q.answer(S["xo_notyou"], show_alert=True)
        return
    if action == "yes":
        gid = ":".join(parts[2:])
        ch = (ctx.chat_data.get("xo_ch") or {}).get(gid)
        if not ch or q.from_user.id != ch["b"]:
            await q.answer(S["xo_notyou"], show_alert=True)
            return
        ctx.chat_data["xo_ch"].pop(gid, None)
        gid2 = f"{chat.id}:{q.message.message_id}"
        ctx.chat_data.setdefault("xo", {})[gid2] = {"board": [""] * 9, "x": ch["a"], "o": ch["b"], "an": ch["an"], "bn": ch["bn"], "turn": "❌"}
        await q.answer()
        await q.edit_message_text(S["xo_turn"].format(x=ch["an"], o=ch["bn"], turn=f"{ch['an']} ❌"), reply_markup=_xo_board_kb(gid2, [""] * 9))
        return
    if action == "m":
        gid2, cell = parts[2] + ":" + parts[3], int(parts[4])
        g = (ctx.chat_data.get("xo") or {}).get(gid2)
        if not g:
            await q.answer("اللعبة خلصت.", show_alert=True)
            return
        cur_id = g["x"] if g["turn"] == "❌" else g["o"]
        if q.from_user.id != cur_id:
            await q.answer("استنى دورك 😅", show_alert=True)
            return
        if g["board"][cell]:
            await q.answer(S["xo_busy"], show_alert=True)
            return
        g["board"][cell] = g["turn"]
        winner = _xo_winner(g["board"])
        if winner or all(g["board"]):
            ctx.chat_data["xo"].pop(gid2, None)
            await q.answer()
            if winner:
                wname = g["an"] if winner == "❌" else g["bn"]
                pts = bump(chat.id, cur_id, "pts", 5)
                await q.edit_message_text(S["xo_win"].format(w=wname, pts=pts))
            else:
                await q.edit_message_text(S["xo_draw"])
            return
        g["turn"] = "⭕" if g["turn"] == "❌" else "❌"
        tname = g["an"] if g["turn"] == "❌" else g["bn"]
        await q.answer()
        await q.edit_message_text(S["xo_turn"].format(x=g["an"], o=g["bn"], turn=f"{tname} {g['turn']}"), reply_markup=_xo_board_kb(gid2, g["board"]))


HANDLERS = [
    CallbackQueryHandler(tahaddi_cb, pattern=r"^th:"),
    CallbackQueryHandler(xo_cb, pattern=r"^xo:"),
    CallbackQueryHandler(mahbas_cb, pattern=r"^mh:"),
    CallbackQueryHandler(rps_cb, pattern=r"^rps:"),
    CallbackQueryHandler(group_roulette_cb, pattern=r"^gr:"),
]


def games_kb(page=0):
    if page == 0:
        return InlineKeyboardMarkup([
            [btn("كت 🎲", "g:s:كت", style="primary"), btn("صراحه 💭", "g:s:صراحه", style="primary")],
            [btn("اسالني ❓", "g:s:اسالني", style="primary"), btn("تويت 🐦", "g:s:تويت", style="primary")],
            [btn("لو خيروك ⚖️", "g:s:لو خيروك", style="primary"), btn("تحدي 🎯", "g:s:تحدي", style="primary")],
            [btn("حزوره 🧩", "g:s:حزوره", style="success"), btn("تفكيك 🔤", "g:s:تفكيك", style="success")],
            [btn("رياضيات ➕", "g:s:رياضيات", style="success"), btn("اسرع ⚡", "g:s:اسرع", style="success")],
            [btn("العكس ♻️", "g:s:العكس", style="success"), btn("معاني 💡", "g:s:معاني", style="success")],
            [btn("المختلف 🔍", "g:s:المختلف", style="success"), btn("سمايلات 😀", "g:s:سمايلات", style="success")],
            [btn("بات 🎯", "g:s:بات", style="primary"), btn("خمن 🔮", "g:s:خمن", style="primary")],
            [btn("الروليت 🎡", "g:s:الروليت", style="success"), btn("المستذئب 🐺", "g:s:مستذئب", style="danger")],
            [btn("المزيد من الألعاب ▶️", "g:p:1", style="primary")],
        ])
    return InlineKeyboardMarkup([
        [btn("انمي 🎌", "g:s:انمي", style="primary"), btn("عربي 📖", "g:s:عربي", style="primary")],
        [btn("ممثلين 🎬", "g:s:ممثلين", style="primary"), btn("مغنين 🎤", "g:s:مغنين", style="primary")],
        [btn("لاعبين 🏃‍♂️", "g:s:لاعبين", style="primary"), btn("الحظ 🍀", "g:s:الحظ", style="success")],
        [btn("عواصم 🌍", "g:s:عواصم", style="primary"), btn("امثال 📜", "g:s:امثال", style="primary")],
        [btn("ثقافه 🧠", "g:s:ثقافه", style="success"), btn("تركيب 🔠", "g:s:تركيب", style="success")],
        [btn("علم 🚩", "g:s:علم", style="success"), btn("انكليزي 🔤", "g:s:انكليزي", style="primary")],
        [btn("كورة ⚽", "g:s:كورة", style="primary"), btn("سيارات 🚗", "g:s:سيارات", style="primary")],
        [btn("حيوانات 🦁", "g:s:حيوانات", style="primary"), btn("محيبس 💍", "g:s:محيبس", style="success")],
        [btn("مشهور ⭐", "g:s:مشهور", style="primary"), btn("اكمل المثل 📜", "g:s:اكمل المثل", style="success")],
        [btn("حجره ورقه مقص ✊", "g:s:حجره", style="success"), btn("توب النقاط 🏆", "g:s:توب النقاط", style="primary")],
        [btn("◀️ الصفحة السابقة", "g:p:0", style="primary")],
    ])


async def games_cb(update, ctx):
    q = update.callback_query
    parts = q.data.split(":", 2)
    if parts[1] == "p":
        await q.answer()
        try:
            await q.edit_message_reply_markup(reply_markup=games_kb(int(parts[2])))
        except Exception:
            pass
        return
    game = parts[2]
    await q.answer()

    class FakeMsg:
        def __init__(self, q):
            self._q = q
            self.reply_to_message = None

        async def reply_text(self, text, **kw):
            return await self._q.message.reply_text(text, **kw)

    fake = type("U", (), {"message": FakeMsg(q), "effective_chat": q.message.chat, "effective_user": q.from_user})()
    if game == "مستذئب":
        from modules import werewolf
        await werewolf.ww_new(fake, ctx)
        return
    fn = {
        "تحدي": tahaddi, "حزوره": hazura, "تفكيك": tafkik, "ثقافه": thaqafa,
        "رياضيات": math_game, "اسرع": speed_game, "تركيب": tarkib,
        "محيبس": mahbas, "حجره": rps_game, "توب النقاط": top_pts,
        "اكمل المثل": akmel, "العكس": aks_game, "معاني": maani_game,
        "المختلف": mokhtalif_game, "سمايلات": smiles_game, "بات": bat_game,
        "خمن": khammen_game, "حروف": horoof_game, "الروليت": group_roulette,
        "الحظ": luck_game,
    }.get(game) or QUIZ_FUNCS.get(game)
    if fn:
        await fn(fake, ctx)
    else:
        await _make_reply(game)(fake, ctx)


HANDLERS.append(CallbackQueryHandler(games_cb, pattern=r"^g:"))