File size: 134,715 Bytes
be581d8 aa597c1 be581d8 aa597c1 e85e286 aa597c1 be581d8 aa597c1 be581d8 aa597c1 3da3f86 aa597c1 be581d8 aa597c1 be581d8 aa597c1 be581d8 2b61614 aa597c1 be581d8 aa597c1 be581d8 aa597c1 2b61614 be581d8 2b61614 be581d8 aa597c1 be581d8 aa597c1 be581d8 aa597c1 be581d8 2b61614 be581d8 aa597c1 be581d8 aa597c1 be581d8 aa597c1 be581d8 aa597c1 be581d8 aa597c1 be581d8 aa597c1 be581d8 aa597c1 be581d8 aa597c1 be581d8 aa597c1 be581d8 aa597c1 be581d8 aa597c1 be581d8 aa597c1 be581d8 2b61614 be581d8 2b61614 be581d8 aa597c1 be581d8 aa597c1 be581d8 aa597c1 be581d8 aa597c1 be581d8 aa597c1 be581d8 aa597c1 be581d8 aa597c1 be581d8 aa597c1 be581d8 aa597c1 be581d8 aa597c1 e85e286 be581d8 aa597c1 e76647f aa597c1 2b61614 aa597c1 be581d8 2b61614 be581d8 2b61614 be581d8 2b61614 be581d8 2b61614 be581d8 2b61614 be581d8 2b61614 be581d8 2b61614 be581d8 2b61614 be581d8 2b61614 be581d8 2b61614 be581d8 2b61614 be581d8 2b61614 be581d8 2b61614 be581d8 2b61614 be581d8 2b61614 be581d8 2b61614 be581d8 2b61614 be581d8 aa597c1 be581d8 2b61614 be581d8 2b61614 be581d8 2b61614 be581d8 2b61614 be581d8 2b61614 be581d8 2b61614 be581d8 2b61614 be581d8 2b61614 be581d8 2b61614 aa597c1 2b61614 aa597c1 be581d8 aa597c1 be581d8 2b61614 be581d8 aa597c1 be581d8 2b61614 be581d8 2b61614 be581d8 2b61614 be581d8 2b61614 be581d8 2b61614 be581d8 2b61614 be581d8 2b61614 be581d8 2b61614 be581d8 2b61614 be581d8 2b61614 be581d8 2b61614 be581d8 2b61614 be581d8 2b61614 be581d8 2b61614 be581d8 aa597c1 be581d8 aa597c1 be581d8 aa597c1 be581d8 aa597c1 be581d8 2b61614 be581d8 aa597c1 be581d8 2b61614 be581d8 2b61614 be581d8 2b61614 be581d8 2b61614 be581d8 2b61614 be581d8 2b61614 be581d8 2b61614 be581d8 2b61614 be581d8 2b61614 be581d8 2b61614 be581d8 2b61614 be581d8 2b61614 be581d8 2b61614 be581d8 2b61614 be581d8 aa597c1 2b61614 be581d8 2b61614 be581d8 aa597c1 2b61614 be581d8 aa597c1 be581d8 2b61614 aa597c1 ccd4e1a aa597c1 | 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 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 | """CALL OF DUSY: Telegram Mini App game (knife / sniper / M4 / PKC arena). Bot via MTProto (Telethon), no aiogram.
Env (HF Space secrets): API_ID, API_HASH, BOT_TOKEN. Optional: PUBLIC_URL, ALLOW_GUEST=1 (browser testing)."""
import asyncio, os, json, hmac, hashlib, random, time, math
from collections import deque
from urllib.parse import parse_qsl
from aiohttp import web, WSMsgType
from telethon import TelegramClient, events
from telethon.sessions import StringSession
from telethon.tl import types as _T
from telethon.tl.types import KeyboardButtonRow, ReplyInlineMarkup
from telethon.tl.tlobject import TLObject
import struct
WebBtn = getattr(_T, "KeyboardButtonWebView", None)
if WebBtn is None: # old/odd Telethon builds: raw keyboardButtonWebView#13767230
class WebBtn(TLObject):
CONSTRUCTOR_ID = 0x13767230; SUBCLASS_OF_ID = 0xbad74a3
def __init__(self, text, url): self.text, self.url = text, url
def _bytes(self): return struct.pack("<I", self.CONSTRUCTOR_ID) + TLObject.serialize_bytes(self.text) + TLObject.serialize_bytes(self.url)
API_ID = int(os.getenv("API_ID", "0")); API_HASH = os.getenv("API_HASH", ""); BOT_TOKEN = os.getenv("BOT_TOKEN", "")
PUBLIC_URL = (os.getenv("PUBLIC_URL") or "https://" + os.getenv("SPACE_HOST", "localhost:7860")).rstrip("/")
ALLOW_GUEST = os.getenv("ALLOW_GUEST") == "1"
WIN_KILLS, MATCH_SEC, COUNTDOWN = 25, 300, 4
TICK = 1 / 30 # server tick / snapshot rate
HP_MAX, REGEN_DELAY, REGEN_RATE = 100, 8, 20 # auto-heal: after 8s without damage, +20 hp/s
START_COINS, KILL_COINS, HEAD_COINS = 12, 5, 8
EYE = (1.6, 1.0, .55) # eye height per stance (0 stand, 1 slide, 2 prone)
HEAD_Y = (1.62, 1.05, .42)
BODY = (((1.1, .5), (.5, .45)), ((.8, .5),), ((.3, .55),)) # (centre height, radius) hit spheres per stance
# damage table: body / head. sniper: body = half hp, head = dead. spray weapons: balanced for ~5 body shots / ~3 head shots
WEAPONS = {
"k": dict(cd=.45),
"s": dict(cd=1.6, body=50, head=100, spread=.02),
"m4": dict(cd=.09, mag=30, rl=1.9, body=20, head=40, spread=.010, bloom=.0035, maxb=.035),
"pkc": dict(cd=.085, mag=100, rl=4.2, body=24, head=48, spread=.020, bloom=.0045, maxb=.06),
}
SHOP = {"m4": ("w", 20), "pkc": ("w", 35), "frag": ("g", 6), "smoke": ("g", 4), "molo": ("g", 8)}
GR_MAX = 2
BOT_USER = ""
rooms = {}
j = lambda o: json.dumps(o, separators=(",", ":"), ensure_ascii=False)
def num(v, lo=-1e4, hi=1e4):
v = float(v)
if not math.isfinite(v): raise ValueError
return max(lo, min(hi, v))
# ---------- maps (boxes: [cx, y0, cz, w, h, d]) ----------
def make_map(i):
r = random.Random(i * 91 + 7); B = []
def bx(x, y, z, w, h, d): B.append([round(x, 1), y, round(z, 1), w, h, d])
def stairs(x, z, sx, n):
for k in range(n): bx(x + sx * (.6 + 1.2 * k), 0, z, 1.2, .5 * (n - k), 3)
for s in (-1, 1): bx(0, 0, s * 37, 76, 7, 2); bx(s * 37, 0, 0, 2, 7, 76)
if i == 0: # desert ruins
for _ in range(30):
x, z = r.uniform(-30, 30), r.uniform(-17, 17)
if abs(x) < 5 and abs(z) < 5: continue
bx(x, 0, z, *r.choice([(1.6, 4, 1.6), (7, 3.5, 1.4), (1.4, 3.5, 7), (4, 2, 4)]))
bx(0, 0, 0, 6, 1.5, 6)
elif i == 1: # snow base: centre platform + sniper towers
bx(0, 0, 0, 12, 3, 12); stairs(6, 0, 1, 6); stairs(-6, 0, -1, 6)
for s in (-1, 1): bx(s * 27, 0, s * 6, 6, 4, 6); stairs(s * 24, s * 6, -s, 8)
for _ in range(9):
x, z = r.uniform(-30, 30), r.uniform(-15, 15)
if abs(x) < 9 or abs(x) > 22: continue
bx(x, 0, z, *r.choice([(8, 2.5, 1), (1, 2.5, 8), (2, 1.5, 2)]))
else: # city rooftops
for sx in (-1, 1):
for sz in (-1, 1): bx(sx * 14, 0, sz * 8, 10, 5, 10); stairs(sx * 19, sz * 8, sx, 10)
bx(0, 4.6, -8, 18, .4, 3); bx(0, 4.6, 8, 18, .4, 3)
for _ in range(10):
x, z = r.uniform(-8, 8), r.uniform(-16, 16)
if abs(z) < 11: continue
bx(x, 0, z, 2, 1.5, 2)
return B
# ---------- Telegram auth ----------
def check(init):
try:
d = dict(parse_qsl(init, keep_blank_values=True)); h = d.pop("hash", None)
s = "\n".join(f"{k}={v}" for k, v in sorted(d.items()))
key = hmac.new(b"WebAppData", BOT_TOKEN.encode(), hashlib.sha256).digest()
if h and hmac.compare_digest(hmac.new(key, s.encode(), hashlib.sha256).hexdigest(), h):
return json.loads(d["user"])
except Exception: pass
return None
# ---------- connection: one writer task per socket, so a slow phone never stalls the game loop ----------
class Conn:
def __init__(s, ws): s.ws = ws; s.q = asyncio.Queue(); s.task = asyncio.create_task(s.run())
def send(s, o, drop=False): s.raw(j(o), drop)
def raw(s, m, drop=False):
if drop and s.q.qsize() > 2: return # snapshots are droppable: always send the freshest one
s.q.put_nowait(m)
async def run(s):
try:
while True: await s.ws.send_str(await s.q.get())
except Exception: pass
def close(s): s.task.cancel()
def tx(p, o, drop=False): p["ws"].send(o, drop)
def bc(R, o, drop=False):
m = j(o)
for p in list(R["players"].values()): p["ws"].raw(m, drop)
def rs(R):
bc(R, {"t": "room", "code": R["code"], "host": R["host"], "mode": R["mode"], "map": R["map"], "state": R["state"],
"link": f"https://t.me/{BOT_USER}?start={R['code']}",
"players": [{"id": p["id"], "name": p["name"], "photo": p["photo"], "team": p["team"]} for p in R["players"].values()]})
# ---------- geometry ----------
def dirv(P):
c = math.cos(P["pitch"]); return (-math.sin(P["yaw"]) * c, math.sin(P["pitch"]), -math.cos(P["yaw"]) * c)
def ray_box(o, d, b):
x, y0, z, w, h, dd = b; lo = (x - w / 2, y0, z - dd / 2); hi = (x + w / 2, y0 + h, z + dd / 2); t0, t1 = 0, 1e9
for i in range(3):
if abs(d[i]) < 1e-9:
if o[i] < lo[i] or o[i] > hi[i]: return None
else:
a, c = (lo[i] - o[i]) / d[i], (hi[i] - o[i]) / d[i]
if a > c: a, c = c, a
t0, t1 = max(t0, a), min(t1, c)
if t0 > t1: return None
return t0
def ray_sph(o, d, c, r):
oc = [o[i] - c[i] for i in range(3)]; b = sum(oc[i] * d[i] for i in range(3)); cc = sum(v * v for v in oc) - r * r
disc = b * b - cc
if disc < 0: return None
t = -b - math.sqrt(disc)
return t if t >= 0 else (0 if cc < 0 else None)
def blocked(R, o, dv, dist):
for b in R["boxes"]:
t = ray_box(o, dv, b)
if t is not None and t < dist - .05: return True
return False
def seg_dist(a, b, c):
ab = [b[i] - a[i] for i in range(3)]; ac = [c[i] - a[i] for i in range(3)]; l2 = sum(v * v for v in ab) or 1e-9
t = max(0, min(1, sum(ab[i] * ac[i] for i in range(3)) / l2))
return math.sqrt(sum((a[i] + ab[i] * t - c[i]) ** 2 for i in range(3)))
# ---------- lag compensation: rewind enemies to what the shooter actually saw ----------
def pos_at(p, t):
h = list(p["hist"])
if not h: return p["x"], p["y"], p["z"], p["st"]
if t >= h[-1][0]: e = h[-1]; return e[1], e[2], e[3], e[4]
if t <= h[0][0]: e = h[0]; return e[1], e[2], e[3], e[4]
for i in range(len(h) - 1, 0, -1):
a, b = h[i - 1], h[i]
if a[0] <= t <= b[0]:
k = (t - a[0]) / max(1e-6, b[0] - a[0])
return a[1] + (b[1] - a[1]) * k, a[2] + (b[2] - a[2]) * k, a[3] + (b[3] - a[3]) * k, b[4]
e = h[-1]; return e[1], e[2], e[3], e[4]
def trace(R, P, o, dv, rng, tr):
best = (None, False, rng)
for p in R["players"].values():
if not p["alive"] or p["team"] == P["team"]: continue
x, y, z, st = pos_at(p, tr)
hh = ray_sph(o, dv, (x, y + HEAD_Y[st], z), .3)
bb = [b for b in (ray_sph(o, dv, (x, y + hy, z), r) for hy, r in BODY[st]) if b is not None]
tb = min(bb) if bb else None
if hh is not None and (tb is None or hh <= tb + .35): d_, head = hh, True
elif tb is not None: d_, head = tb, False
else: continue
if d_ < best[2] and not blocked(R, o, dv, d_): best = (p, head, d_)
return best
# ---------- players ----------
def new_player(pid, name, photo, team, C, R):
p = dict(id=pid, name=name, photo=photo, team=team, ws=C, room=R, x=0, y=0, z=0, yaw=0, pitch=0, alive=False, rt=0, cd=0, wp="k", st=0,
rtt=80, hp=HP_MAX, lh=0, hs=0, bloom=0, hist=deque(maxlen=90), lg=0)
reset_loadout(p); return p
def reset_loadout(P):
P.update(coins=START_COINS, own={"k", "s"}, gr={"frag": 0, "smoke": 0, "molo": 0}, knife=True, ammo={"m4": 30, "pkc": 100}, rl={}, hp=HP_MAX)
def inv_msg(P): return {"t": "inv", "coins": P["coins"], "own": sorted(P["own"]), "gr": P["gr"], "kn": P["knife"], "ammo": P["ammo"]}
def spawn(P):
R = P["room"]; z = random.uniform(24, 33) * (-1 if P["team"] == "H" else 1)
P.update(x=random.uniform(-26, 26), y=0, z=z, alive=True, hp=HP_MAX, st=0, knife=True, rl={}, bloom=0, lh=0, wp="k")
P["ammo"] = {"m4": 30, "pkc": 100}; P["hist"].clear(); P["hist"].append((time.time(), P["x"], 0, z, 0))
drop_knives(R, P)
tx(P, {"t": "spawn", "x": P["x"], "y": 0, "z": z, "yaw": math.pi if P["team"] == "H" else 0})
tx(P, {"t": "hp", "hp": HP_MAX}); tx(P, inv_msg(P))
def start_msg(R, P, cd): return {"t": "start", "map": R["map"], "boxes": R["boxes"], "team": P["team"], "cd": cd, "win": WIN_KILLS}
def drop_knives(R, P):
for pr in [q for q in R["pr"] if q["k"] == "kn" and q["own"] == P["id"]]:
R["pr"].remove(pr); bc(R, {"t": "knp", "id": pr["id"]})
def finish(R, win):
if R["state"] != "play": return
R["state"] = "end"; bc(R, {"t": "end", "win": win})
async def back():
await asyncio.sleep(8)
if R["code"] in rooms:
R["state"] = "lobby"; R["pr"] = []; R["fires"] = []
for p in R["players"].values(): p["alive"] = False
rs(R)
asyncio.create_task(back())
def kill(R, K, V, w, head=False):
V["alive"] = False; V["rt"] = time.time() + 3; V["knife"] = True; drop_knives(R, V)
enemy = bool(K and K is not V and K["team"] != V["team"])
if enemy:
R["sc"][K["team"]] += 1; K["coins"] += HEAD_COINS if head else KILL_COINS; tx(K, inv_msg(K))
bc(R, {"t": "kill", "k": K["name"] if K else "", "kt": K["team"] if K else "", "kid": K["id"] if K else "", "v": V["name"], "vt": V["team"], "vid": V["id"], "w": w, "hs": int(head)})
tx(V, {"t": "dead", "by": K["name"] if K and K is not V else "", "sec": 3})
if enemy and R["sc"][K["team"]] >= WIN_KILLS: finish(R, K["team"])
def hurt(R, K, V, dmg, w, head=False, src=None):
if not V["alive"] or R["state"] != "play": return
V["hp"] -= dmg; V["lh"] = time.time()
tx(V, {"t": "hp", "hp": max(0, round(V["hp"])), "a": src})
if K and K is not V: tx(K, {"t": "hit", "h": int(head), "d": round(dmg)})
if V["hp"] <= 0: kill(R, K, V, w, head)
def leave(P):
R = P["room"]
if R["players"].get(P["id"]) is not P: return
del R["players"][P["id"]]; drop_knives(R, P)
if not R["players"]: rooms.pop(R["code"], None); return
if R["host"] == P["id"]: R["host"] = next(iter(R["players"]))
if R["state"] == "play" and len({p["team"] for p in R["players"].values()}) < 2: finish(R, "T")
else: rs(R)
def start_reload(P, w, now):
sp = WEAPONS[w]
if w in P["rl"] or P["ammo"][w] >= sp["mag"]: return
P["rl"][w] = now + sp["rl"]; tx(P, {"t": "ammo", "w": w, "n": P["ammo"][w], "rl": sp["rl"]})
# ---------- projectiles (grenades / smoke / molotov / thrown knife) ----------
def step_pr(R, pr, dt):
r = .12; p, v = pr["p"], pr["v"]; v[1] -= pr["g"] * dt
n = [p[0] + v[0] * dt, p[1] + v[1] * dt, p[2] + v[2] * dt]; hit = False
if n[1] < r:
n[1] = r; hit = True
if v[1] < 0: v[1] = -v[1] * .35; v[0] *= .65; v[2] *= .65
for x, y0, z, w, h, d in R["boxes"]:
if abs(n[0] - x) < w / 2 + r and abs(n[2] - z) < d / 2 + r and y0 - r < n[1] < y0 + h + r:
dep, ax, sg = min((x + w / 2 + r - n[0], 0, 1), (n[0] - (x - w / 2 - r), 0, -1), (z + d / 2 + r - n[2], 2, 1), (n[2] - (z - d / 2 - r), 2, -1),
(y0 + h + r - n[1], 1, 1), (n[1] - (y0 - r), 1, -1))
n[ax] += sg * dep; hit = True
if v[ax] * sg < 0: v[ax] = -v[ax] * .35
for k in (0, 1, 2):
if k != ax: v[k] *= .75
old = list(p); p[:] = n
return hit, old
def explode(R, pr):
p = pr["p"]; own = R["players"].get(pr["own"]); bc(R, {"t": "boom", "id": pr["id"], "k": "frag", "p": [round(c, 2) for c in p]})
for V in list(R["players"].values()):
if not V["alive"]: continue
if V is not own and own and V["team"] == own["team"]: continue
c = (V["x"], V["y"] + (1.0, .7, .3)[V["st"]], V["z"]); dist = math.dist(c, p)
if dist >= 6.5: continue
o = (p[0], p[1] + .3, p[2]); dv = [(c[i] - o[i]) / (dist or 1) for i in range(3)]
if dist > .8 and blocked(R, o, dv, dist): continue
dmg = max(22, 120 * (1 - dist / 6.5)) * (.5 if V is own else 1)
hurt(R, own, V, dmg, "g", False, (p[0], p[2]))
def tick_projectiles(R, now, dt):
for pr in list(R["pr"]):
if pr not in R["pr"]: continue
k = pr["k"]
if pr["st"] == "stuck":
own = R["players"].get(pr["own"])
if own and own["alive"] and math.dist((own["x"], own["y"] + .5, own["z"]), pr["p"]) < 1.7:
own["knife"] = True; R["pr"].remove(pr); bc(R, {"t": "knp", "id": pr["id"]}); tx(own, inv_msg(own))
continue
for _ in range(2):
hit, old = step_pr(R, pr, dt / 2)
if k == "kn":
own = R["players"].get(pr["own"]); done = False
for V in R["players"].values():
if not V["alive"] or (own and V["team"] == own["team"]): continue
for hy, rad, hd in ((HEAD_Y[V["st"]], .3, True), (1.1 if V["st"] == 0 else .6 if V["st"] == 1 else .3, .55, False)):
if seg_dist(old, pr["p"], (V["x"], V["y"] + hy, V["z"])) < rad:
pr["p"][:] = [V["x"], .1, V["z"]]; pr["v"][:] = [0, 0, 0]; pr["st"] = "stuck"
bc(R, {"t": "knh", "id": pr["id"], "p": [round(c, 2) for c in pr["p"]]})
hurt(R, own, V, 100, "t", hd, (old[0], old[2])); done = True; break
if done: break
if done: break
if hit:
pr["v"][:] = [0, 0, 0]; pr["st"] = "stuck"; pr["p"][1] = max(.08, pr["p"][1]); bc(R, {"t": "knh", "id": pr["id"], "p": [round(c, 2) for c in pr["p"]]}); break
elif k == "molo" and hit:
R["pr"].remove(pr); R["fires"].append(dict(id=pr["id"], p=list(pr["p"]), end=now + 5.5, nt=now, own=pr["own"], tm=pr["tm"]))
bc(R, {"t": "boom", "id": pr["id"], "k": "molo", "p": [round(c, 2) for c in pr["p"]], "dur": 5.5}); break
if pr not in R["pr"] or pr["st"] == "stuck": continue
age = now - pr["t0"]
if k == "frag" and age >= 2.4: R["pr"].remove(pr); explode(R, pr)
elif k == "smoke" and age >= 1.5:
R["pr"].remove(pr); bc(R, {"t": "boom", "id": pr["id"], "k": "smoke", "p": [round(c, 2) for c in pr["p"]], "dur": 12})
elif k == "molo" and age >= 3.5:
R["pr"].remove(pr); R["fires"].append(dict(id=pr["id"], p=list(pr["p"]), end=now + 5.5, nt=now, own=pr["own"], tm=pr["tm"]))
bc(R, {"t": "boom", "id": pr["id"], "k": "molo", "p": [round(c, 2) for c in pr["p"]], "dur": 5.5})
elif k == "kn" and age > 6: R["pr"].remove(pr); bc(R, {"t": "knp", "id": pr["id"]})
for f in list(R["fires"]):
if now >= f["end"]: R["fires"].remove(f); continue
if now >= f["nt"]:
f["nt"] = now + .5; own = R["players"].get(f["own"])
for V in list(R["players"].values()):
if V["alive"] and (V is own or V["team"] != f["tm"]) and math.hypot(V["x"] - f["p"][0], V["z"] - f["p"][2]) < 3.2 and abs(V["y"] - f["p"][1]) < 2.2:
hurt(R, own, V, 12, "m", False, (f["p"][0], f["p"][2]))
# ---------- messages ----------
async def on_msg(C, P, d):
t = d.get("t"); now = time.time()
if t == "ping": C.send({"t": "pong", "c": d.get("c")}); return P
if t == "join":
if P: return P
u = check(d.get("init", ""))
if not u and ALLOW_GUEST and d.get("guest"): u = {"id": abs(hash(d["guest"])) % 10 ** 9, "first_name": str(d["guest"])[:16]}
if not u: C.send({"t": "err", "m": "افتح اللعبة من داخل تيلجرام"}); return None
code = (d.get("room") or "").upper().strip()[:8]; pid = str(u["id"])
if code:
R = rooms.get(code)
if not R: C.send({"t": "err", "m": "الغرفة غير موجودة، تأكد من الكود"}); return None
elif d.get("create"):
code = "".join(random.choice("ABCDEFGHJKMNPQRSTUVWXYZ23456789") for _ in range(5))
R = rooms[code] = dict(code=code, host=None, mode="manual", map=0, state="lobby", players={}, sc={"H": 0, "V": 0}, boxes=[], go=0, end=0, pr=[], fires=[], pid=0)
else: C.send({"t": "err", "m": "اكتب كود الغرفة أو أنشئ غرفة جديدة"}); return None
old = R["players"].get(pid)
if not old and (R["state"] != "lobby" or len(R["players"]) >= 8):
C.send({"t": "err", "m": "الغرفة ممتلئة أو المباراة بدأت"}); return None
if old:
try: await old["ws"].ws.close()
except Exception: pass
name = (u.get("first_name", "") + " " + u.get("last_name", "")).strip()[:20] or "لاعب"
ph = u.get("photo_url", ""); ph = ph if str(ph).startswith("https://") else ""
P = new_player(pid, name, ph, old["team"] if old else None, C, R)
if old:
for k in ("coins", "own", "gr", "knife", "ammo", "alive", "hp", "x", "y", "z", "st"): P[k] = old[k]
R["players"][pid] = P
if R["host"] not in R["players"]: R["host"] = pid
tx(P, {"t": "me", "id": pid}); rs(R)
if R["state"] == "play": tx(P, start_msg(R, P, 0)); spawn(P)
return P
if t == "leave":
if P: leave(P)
return None
if not P: return P
R = P["room"]; host = R["host"] == P["id"]; play = R["state"] == "play"
if t == "rtt":
try: P["rtt"] = num(d["v"], 0, 1000) * .5 + P["rtt"] * .5
except Exception: pass
elif t == "team" and R["state"] == "lobby" and R["mode"] == "manual" and d.get("team") in ("H", "V"):
P["team"] = d["team"]; rs(R)
elif t == "mode" and host and R["state"] == "lobby" and d.get("m") in ("manual", "random"):
R["mode"] = d["m"]; rs(R)
elif t == "map" and host and R["state"] == "lobby" and d.get("m") in (0, 1, 2):
R["map"] = d["m"]; rs(R)
elif t == "start" and host and R["state"] == "lobby":
ps = list(R["players"].values())
if R["mode"] == "random":
random.shuffle(ps)
for i, p in enumerate(ps): p["team"] = "HV"[i % 2]
if len({p["team"] for p in ps}) < 2 or any(p["team"] is None for p in ps):
C.send({"t": "err", "m": "لازم كل لاعب يختار فريق، ويكون بكل فريق لاعب واحد على الأقل"}); return P
R.update(state="play", sc={"H": 0, "V": 0}, boxes=make_map(R["map"]), go=now + COUNTDOWN, end=now + COUNTDOWN + MATCH_SEC, pr=[], fires=[], pid=0)
for p in ps: reset_loadout(p); tx(p, start_msg(R, p, COUNTDOWN)); spawn(p)
elif t == "st" and play and P["alive"]:
try:
x, y, z = num(d["x"], -60, 60), num(d["y"], -50, 40), num(d["z"], -60, 60)
P.update(x=x, y=y, z=z, yaw=num(d["yaw"]), pitch=num(d["pitch"], -1.5, 1.5))
st = int(d.get("sa", 0)); P["st"] = st if st in (0, 1, 2) else 0
if d.get("wp") in WEAPONS: P["wp"] = d["wp"]
P["hist"].append((now, x, y, z, P["st"]))
except Exception: pass
elif t == "fall" and play and P["alive"] and now >= R["go"]: kill(R, None, P, "f")
elif t == "buy" and play:
it = SHOP.get(d.get("i"))
if not it: return P
kind, price = it; i = d["i"]
if P["coins"] < price: tx(P, {"t": "toast", "m": "عملاتك ما تكفي"}); return P
if kind == "w":
if i in P["own"]: tx(P, {"t": "toast", "m": "تملك هذا السلاح"}); return P
P["own"].add(i); P["ammo"][i] = WEAPONS[i]["mag"]
else:
if P["gr"][i] >= GR_MAX: tx(P, {"t": "toast", "m": "وصلت للحد الأقصى (2)"}); return P
P["gr"][i] += 1
P["coins"] -= price; tx(P, inv_msg(P)); tx(P, {"t": "bought", "i": i})
elif t == "reload" and play and P["alive"] and d.get("w") in ("m4", "pkc") and d["w"] in P["own"]: start_reload(P, d["w"], now)
elif t in ("fire", "throw") and play and P["alive"] and now >= R["go"]:
try:
nx, ny, nz = num(d["x"], -60, 60), num(d["y"], -50, 40), num(d["z"], -60, 60)
if math.hypot(nx - P["x"], nz - P["z"]) < 6: P.update(x=nx, y=ny, z=nz)
P["yaw"] = num(d["yaw"]); P["pitch"] = num(d["pitch"], -1.5, 1.5); st = int(d.get("sa", 0)); P["st"] = st if st in (0, 1, 2) else 0
except Exception: return P
eye = EYE[P["st"]]; o = (P["x"], P["y"] + eye, P["z"]); dv = dirv(P)
if t == "throw":
k = d.get("k")
if k == "kn":
if not P["knife"]: return P
P["knife"] = False; spd, g = 30, 7
elif k in P["gr"] and P["gr"][k] > 0:
P["gr"][k] -= 1; spd, g = 15, 22
dv = dirv(dict(yaw=P["yaw"], pitch=min(1.4, P["pitch"] + .2)))
else: return P
R["pid"] += 1; org = [o[0] + dv[0] * .6, o[1] - .15 + dv[1] * .6, o[2] + dv[2] * .6]
pr = dict(id=R["pid"], k=k, own=P["id"], tm=P["team"], p=org, v=[dv[0] * spd, dv[1] * spd, dv[2] * spd], g=g, t0=now, st="fly")
R["pr"].append(pr); bc(R, {"t": "thr", "id": pr["id"], "k": k, "o": [round(c, 2) for c in org], "v": [round(c, 2) for c in pr["v"]], "g": g, "by": P["id"]}); tx(P, inv_msg(P))
return P
w = d.get("w")
if w not in P["own"] or now < P["cd"] or P["rl"].get(w): return P
if w == "k" and not P["knife"]: return P
sp = WEAPONS[w]; P["cd"] = now + sp["cd"]; tr = now - min(.4, P["rtt"] / 1000 + .1)
if w == "k":
best, victim = 2.4, None; fx, fz = dv[0], dv[2]; fl = math.hypot(fx, fz) or 1
for p in R["players"].values():
if not p["alive"] or p["team"] == P["team"]: continue
x, y, z, st = pos_at(p, tr); dx, dz = x - P["x"], z - P["z"]; dist = math.hypot(dx, dz)
if dist < best and abs(y - P["y"]) < 1.5 and (dx * fx + dz * fz) / (dist * fl + 1e-9) > .35: best, victim = dist, p
if victim:
vf = (-math.sin(victim["yaw"]), -math.cos(victim["yaw"]))
back = (vf[0] * fx + vf[1] * fz) / fl > .5 # attacker behind the victim = backstab = instant kill
hurt(R, P, victim, 100 if back else 60, "k", False, (P["x"], P["z"]))
return P
if w in ("m4", "pkc"):
if P["ammo"][w] <= 0: start_reload(P, w, now); return P
P["ammo"][w] -= 1; sprd = sp["spread"] + P["bloom"]; P["bloom"] = min(sp["maxb"], P["bloom"] + sp["bloom"])
if P["ammo"][w] <= 0: start_reload(P, w, now)
else: sprd = 0 if d.get("sc") else sp["spread"]
if sprd:
a = random.uniform(0, 6.2832); r_ = sprd * math.sqrt(random.random())
dv = dirv(dict(yaw=P["yaw"] + r_ * math.cos(a), pitch=P["pitch"] + r_ * math.sin(a)))
bc(R, {"t": "shot", "o": [round(c, 2) for c in o], "d": [round(c, 3) for c in dv], "id": P["id"], "w": w})
V, head, dist = trace(R, P, o, dv, 300, tr)
if V:
dmg = sp["head" if head else "body"]
if w in ("m4", "pkc") and dist > 35: dmg *= max(.5, 1 - (dist - 35) / 100) # damage falloff for spray weapons
hurt(R, P, V, dmg, w, head, (P["x"], P["z"]))
return P
async def ws_handler(req):
ws = web.WebSocketResponse(heartbeat=25); await ws.prepare(req); C = Conn(ws); P = None
async for m in ws:
if m.type != WSMsgType.TEXT: continue
try: P = await on_msg(C, P, json.loads(m.data))
except Exception as e: print("msg error", repr(e))
if P: leave(P)
C.close()
return ws
def tick_room(R, now, dt):
ps = list(R["players"].values())
bc(R, {"t": "snap", "sc": [R["sc"]["H"], R["sc"]["V"]], "left": max(0, int(R["end"] - now)),
"p": [[p["id"], round(p["x"], 2), round(p["y"], 2), round(p["z"], 2), round(p["yaw"], 2), int(p["alive"]), round(p["pitch"], 2), p["wp"], p["st"]] for p in ps]}, True)
for p in ps:
p["bloom"] = max(0, p["bloom"] - .12 * dt)
for w, e in list(p["rl"].items()):
if now >= e: del p["rl"][w]; p["ammo"][w] = WEAPONS[w]["mag"]; tx(p, {"t": "ammo", "w": w, "n": p["ammo"][w], "rl": 0})
if p["alive"] and p["hp"] < HP_MAX and now - p["lh"] >= REGEN_DELAY: # auto-heal after 8s without being hit
p["hp"] = min(HP_MAX, p["hp"] + REGEN_RATE * dt)
if now - p["lg"] > .2 or p["hp"] >= HP_MAX: p["lg"] = now; tx(p, {"t": "hp", "hp": round(p["hp"])})
if not p["alive"] and now >= p["rt"] and now >= R["go"]: spawn(p)
tick_projectiles(R, now, dt)
if now >= R["end"]:
a, b = R["sc"]["H"], R["sc"]["V"]; finish(R, "H" if a > b else "V" if b > a else "T")
async def game_loop():
last = time.time()
while True:
await asyncio.sleep(TICK); now = time.time(); dt = min(now - last, .1); last = now
for R in list(rooms.values()):
if R["state"] != "play": continue
try: tick_room(R, now, dt)
except Exception as e: print("tick error", repr(e))
# ---------- bot (MTProto) ----------
bot = TelegramClient(StringSession(), API_ID, API_HASH)
@bot.on(events.NewMessage(incoming=True, pattern=r"(?i)^/start(?:\s+([A-Za-z0-9]+))?"))
async def on_start(ev):
code = (ev.pattern_match.group(1) or "").upper()
url = PUBLIC_URL + ("/?room=" + code if code else "/")
kb = ReplyInlineMarkup([KeyboardButtonRow([WebBtn("🎮 العب الآن", url)])])
await ev.respond(f"🎯 CALL OF DUSY\nتمت دعوتك للغرفة {code} — اضغط الزر وانضم للمعركة!" if code else "🔪🎯 CALL OF DUSY\nمعركة سكاكين وسنايبرات وأسلحة.\nاضغط الزر لإنشاء غرفة أو الانضمام لغرفة صديقك.", buttons=kb)
async def run_bot():
global BOT_USER
while True:
try:
await bot.start(bot_token=BOT_TOKEN); BOT_USER = (await bot.get_me()).username
print("bot online @" + BOT_USER); await bot.run_until_disconnected()
except Exception as e: print("bot error", repr(e)); await asyncio.sleep(10)
async def index(_): return web.Response(text=HTML, content_type="text/html", headers={"Cache-Control": "no-store"})
async def main():
app = web.Application(); app.add_routes([web.get("/", index), web.get("/ws", ws_handler), web.get("/health", lambda r: web.Response(text="ok"))])
runner = web.AppRunner(app); await runner.setup(); await web.TCPSite(runner, "0.0.0.0", int(os.getenv("PORT", "7860"))).start()
asyncio.create_task(game_loop()); await run_bot()
# ---------- client ----------
HTML = r'''<!doctype html><html lang="ar" dir="rtl"><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no,viewport-fit=cover"><title>CALL OF DUSY</title>
<meta name="theme-color" content="#0b0718">
<script src="https://telegram.org/js/telegram-web-app.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
<style>
:root{color-scheme:dark;--bg:#0b0718;--or:#ff8a3d;--or2:#ffc15e;--cy:#3ee6d0;--rd:#ff5a6e;--tx:#fbefe0;--mut:#b9a9c9;--st:rgba(255,255,255,.14);--hf:Impact,"Arial Black",Haettenschweiler,sans-serif;--bs:1}
*{box-sizing:border-box;-webkit-tap-highlight-color:transparent}
html,body{margin:0;height:100%;background:var(--bg);color:var(--tx);font-family:"Segoe UI",Tahoma,"Noto Sans Arabic",system-ui,sans-serif;overflow:hidden;touch-action:none;-webkit-user-select:none;user-select:none}
canvas#cv{position:fixed;inset:0;width:100%;height:100%}
svg{display:block}button{font:inherit;cursor:pointer}input{font:inherit}
#bg{position:fixed;inset:0;background:radial-gradient(130% 70% at 50% -5%,#6b2f78 0,#321a5c 35%,#120a2a 70%,#0b0718 100%)}
#bg:before{content:"";position:absolute;inset:0;pointer-events:none;background:repeating-linear-gradient(0deg,rgba(255,255,255,.03) 0 1px,transparent 1px 44px),repeating-linear-gradient(90deg,rgba(255,255,255,.03) 0 1px,transparent 1px 44px);-webkit-mask-image:linear-gradient(#000,transparent 75%);mask-image:linear-gradient(#000,transparent 75%)}
.sunb{position:absolute;left:50%;top:-130px;width:430px;height:430px;margin-left:-215px;border-radius:50%;background:radial-gradient(circle,#ffc873 0,#ff7a45 30%,rgba(255,80,90,0) 68%);opacity:.5;animation:glow 7s ease-in-out infinite}
@keyframes glow{50%{opacity:.75;transform:scale(1.08)}}
.sky{position:absolute;left:0;right:0;bottom:0;width:100%;height:150px;opacity:.95}
.scr{position:fixed;inset:0;overflow-y:auto;overflow-x:hidden;touch-action:pan-y;z-index:1}
.wrap{position:relative;max-width:520px;margin:0 auto;padding:calc(env(safe-area-inset-top,0px) + 12px) 14px calc(env(safe-area-inset-bottom,0px) + 150px);display:flex;flex-direction:column;gap:12px}
.logo{text-align:center;padding:2px 0 0}
.logo .em{width:46px;height:46px;margin:0 auto 4px;color:var(--or2);filter:drop-shadow(0 0 10px rgba(255,138,61,.9));animation:spin 14s linear infinite}
@keyframes spin{to{transform:rotate(360deg)}}
.logo .l1{font:900 16px/1 var(--hf);letter-spacing:12px;color:var(--or2);text-shadow:0 0 14px #ff8a3d;padding-inline-start:12px}
.logo .l2{font:900 64px/1 var(--hf);letter-spacing:4px;background:linear-gradient(180deg,#fff3c4 0,#ffb454 45%,#ff5a3d 100%);-webkit-background-clip:text;background-clip:text;color:transparent;filter:drop-shadow(0 4px 0 #5a1530) drop-shadow(0 0 20px rgba(255,120,60,.55));padding-inline-start:4px}
.logo .tag{font-size:12.5px;color:var(--mut);margin-top:8px;letter-spacing:.5px}
.card{background:linear-gradient(180deg,rgba(255,255,255,.1),rgba(255,255,255,.04));border:1px solid var(--st);border-radius:18px;padding:12px 14px;backdrop-filter:blur(8px);-webkit-backdrop-filter:blur(8px);box-shadow:0 8px 24px rgba(0,0,0,.28)}
.lab{font-size:12px;color:var(--or2);font-weight:800;letter-spacing:.5px;margin-bottom:8px;display:flex;justify-content:space-between;align-items:center}
.rw{display:flex;gap:8px;align-items:center}.sp{flex:1}
#code{font:900 34px/1 var(--hf);letter-spacing:7px;direction:ltr;color:var(--cy);text-shadow:0 0 16px rgba(62,230,208,.55)}
.btn{display:inline-flex;align-items:center;justify-content:center;gap:8px;border:0;border-radius:14px;padding:12px 16px;font-weight:800;color:var(--tx);background:rgba(255,255,255,.12);border:1px solid var(--st);transition:transform .12s}
.btn:active{transform:scale(.95)}.btn svg{width:20px;height:20px}.btn:disabled{opacity:.4}
.btn.pri{color:#2a0f00;border:0;background:linear-gradient(180deg,#ffd27a,#ff8a3d 60%,#ff5a3d);box-shadow:0 6px 18px rgba(255,100,50,.45),inset 0 1px 0 rgba(255,255,255,.6)}
.btn.blue{color:#032a26;border:0;background:linear-gradient(180deg,#9ff5e8,#3ee6d0 60%,#1fb5a3);box-shadow:0 6px 18px rgba(62,230,208,.35),inset 0 1px 0 rgba(255,255,255,.6)}
.btn.red{background:rgba(255,90,110,.2);border-color:rgba(255,90,110,.5);color:#ffd5db}
.btn.sm{padding:9px 13px;font-size:13px}.btn.ic{padding:9px;width:40px;height:40px}.btn.big{width:100%;font-size:19px;padding:15px}
.row{display:flex;align-items:center;gap:10px;padding:7px 8px;background:rgba(0,0,0,.25);border-radius:12px;margin-top:6px}.row b{flex:1;font-size:14px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.av{width:38px;height:38px;border-radius:50%;background:#3b2d68;display:flex;align-items:center;justify-content:center;overflow:hidden;font-weight:800;border:2px solid #6a5a95;flex:none}.av.H{border-color:var(--cy)}.av.V{border-color:var(--rd)}.av img{width:100%;height:100%;object-fit:cover}
.chip{font-style:normal;font-size:11.5px;font-weight:800;padding:3px 10px;border-radius:20px;background:#3b2d68}.chip.H{background:var(--cy);color:#06241f}.chip.V{background:var(--rd);color:#2a0710}
.tg2{display:grid;grid-template-columns:1fr 1fr;gap:10px}
.tcard{--c:#fff;border-radius:16px;padding:10px 8px;text-align:center;border:2px solid transparent;background:rgba(0,0,0,.3);color:var(--c);display:flex;flex-direction:column;align-items:center;gap:2px;transition:transform .12s}
.tcard.H{--c:#3ee6d0}.tcard.V{--c:#ff5a6e}.tcard svg{width:46px;height:46px}.tcard b{color:#fff;font-size:16px}.tcard small{color:var(--mut);font-size:11.5px}
.tcard.on{border-color:var(--c);background:linear-gradient(180deg,rgba(255,255,255,.12),rgba(0,0,0,.3));box-shadow:0 0 18px -3px var(--c);transform:translateY(-2px)}
.seg{display:flex;background:rgba(0,0,0,.35);border-radius:13px;padding:3px;gap:3px}.seg button{flex:1;border:0;background:transparent;color:var(--mut);padding:9px 4px;border-radius:10px;font-weight:800;font-size:13px}
.seg button.on{background:linear-gradient(180deg,#ffd27a,#ff8a3d);color:#2a0f00}
.maps{display:grid;grid-template-columns:repeat(3,1fr);gap:8px}
.mp{height:92px;border-radius:14px;border:2px solid transparent;position:relative;overflow:hidden;color:#fff;padding:0;background:var(--g);display:flex;flex-direction:column;justify-content:flex-end;align-items:center;text-shadow:0 1px 6px #000;transition:transform .12s}
.mp .ic2{position:absolute;top:8px;left:0;right:0;font-size:26px;text-align:center}.mp span{font-size:11.5px;font-weight:800;padding:14px 4px 6px;width:100%;text-align:center;background:linear-gradient(transparent,rgba(0,0,0,.65))}
.mp.on{border-color:var(--or2);box-shadow:0 0 18px rgba(255,170,80,.6);transform:translateY(-2px)}
#start{margin-top:12px;animation:pls 2s infinite}
@keyframes pls{50%{box-shadow:0 6px 30px rgba(255,100,50,.85),inset 0 1px 0 rgba(255,255,255,.6)}}
#wait{text-align:center;color:var(--mut);padding:10px}#wait i{font-style:normal;animation:bl 1.2s infinite}@keyframes bl{50%{opacity:.2}}
.ctl{font-size:11.5px;color:var(--mut);text-align:center;line-height:1.7}
.or{text-align:center;color:var(--mut);font-size:12px;display:flex;align-items:center;gap:10px}.or:before,.or:after{content:"";flex:1;height:1px;background:var(--st)}
#jin{flex:1;min-width:0;background:rgba(0,0,0,.35);border:1.5px solid var(--st);border-radius:14px;padding:12px;color:var(--cy);font:900 22px var(--hf);letter-spacing:6px;text-align:center;direction:ltr;text-transform:uppercase;outline:0;-webkit-user-select:text;user-select:text}
#jin:focus{border-color:var(--cy)}
.cn{display:flex;align-items:center;justify-content:center;gap:6px;font-size:11.5px;color:var(--mut)}.cn i{width:8px;height:8px;border-radius:50%;background:#e55;display:block}.cn.ok i{background:#4e8;box-shadow:0 0 8px #4e8}
#msg{display:none;position:fixed;top:calc(env(safe-area-inset-top,0px) + 10px);left:50%;transform:translateX(-50%);z-index:60;max-width:90%;padding:10px 16px;border-radius:14px;background:rgba(120,25,60,.95);border:1px solid #ff7a9a;font-weight:700;text-align:center;box-shadow:0 8px 24px rgba(0,0,0,.5)}
.modal{position:fixed;inset:0;z-index:40;display:none;align-items:center;justify-content:center;background:rgba(6,3,16,.78);backdrop-filter:blur(5px);touch-action:pan-y;padding:12px}
.mbox{width:100%;max-width:480px;max-height:92vh;overflow-y:auto;background:linear-gradient(180deg,#2b1a55,#160d33);border:1px solid var(--st);border-radius:20px;padding:14px;box-shadow:0 20px 60px #000}
.mh{display:flex;align-items:center;gap:10px;margin-bottom:10px}.mh b{flex:1;font:900 22px var(--hf);letter-spacing:1px;color:var(--or2)}
.coin{display:inline-flex;align-items:center;gap:6px;font:900 18px var(--hf);color:#ffe9a0;background:rgba(0,0,0,.45);border:1px solid rgba(255,200,80,.4);padding:4px 12px;border-radius:20px}.coin svg{width:20px;height:20px}
.sh{display:flex;align-items:center;gap:10px;padding:9px;background:rgba(0,0,0,.28);border-radius:14px;margin-top:8px;border:1px solid transparent}
.sh .si{width:62px;height:40px;color:#ffd9a0;flex:none}.sh .si svg{width:100%;height:100%}.sh .sd{flex:1;min-width:0}.sh .sd b{display:block;font-size:14.5px}.sh .sd small{color:var(--mut);font-size:11.5px;line-height:1.5;display:block}
.sh .btn{padding:8px 12px;font-size:13px;white-space:nowrap}.sh .btn svg{width:16px;height:16px}.sh.own{border-color:rgba(80,230,140,.5)}
.st{margin:12px 0 5px;font-size:12px;color:var(--or2);font-weight:800}
.sl{display:flex;align-items:center;gap:10px;font-size:13px}.sl span{min-width:40px}.sl input{flex:1;accent-color:#ff8a3d}
#hud{position:fixed;inset:0;display:none;pointer-events:none;z-index:5}
#hud *{pointer-events:none}#hud .b,#hud .tg,#hud .ed,.touch #hud .slot{pointer-events:auto}
#sc{position:absolute;direction:ltr;top:calc(env(safe-area-inset-top,0px) + 8px);left:50%;transform:translateX(-50%);display:flex;align-items:stretch;border-radius:14px;overflow:hidden;box-shadow:0 6px 20px rgba(0,0,0,.5);border:1px solid rgba(255,255,255,.18);background:rgba(10,6,24,.6);backdrop-filter:blur(6px)}
#sc .tm{min-width:74px;padding:5px 10px 9px;text-align:center;position:relative}
#sc .tm b{display:block;font:900 26px/1 var(--hf)}#sc .tm small{font-size:10.5px;opacity:.9}
#sc .H{background:linear-gradient(180deg,rgba(62,230,208,.38),rgba(62,230,208,.06));color:#c6fff6}#sc .V{background:linear-gradient(180deg,rgba(255,90,110,.38),rgba(255,90,110,.06));color:#ffd5db}
#sc .clk{padding:5px 10px;font:900 21px/1 var(--hf);display:flex;align-items:center;letter-spacing:1px;min-width:64px;justify-content:center}#sc .clk.lo{color:#ff6a6a;animation:bl 1s infinite}
#sc .bar{position:absolute;left:0;right:0;bottom:0;height:4px;background:rgba(0,0,0,.45)}#sc .bar i{display:block;height:100%;width:0;background:currentColor;transition:width .3s}
#hpw{position:absolute;left:50%;transform:translateX(-50%);top:calc(env(safe-area-inset-top,0px) + 62px);width:170px;height:14px;border-radius:8px;background:rgba(10,6,24,.65);border:1px solid rgba(255,255,255,.25);overflow:hidden}
#hpw i{display:block;height:100%;width:100%;background:linear-gradient(90deg,#3ee68a,#9af05a);transition:width .15s}#hpw.lo i{background:linear-gradient(90deg,#ff3b4e,#ff7a45)}
#hpw b{position:absolute;inset:0;text-align:center;font:800 10px/14px sans-serif;text-shadow:0 1px 2px #000;direction:ltr}
#radar{position:absolute;left:10px;top:calc(env(safe-area-inset-top,0px) + 8px);width:98px;height:98px;border-radius:50%;border:2px solid rgba(255,190,120,.7);box-shadow:0 0 14px rgba(0,0,0,.5)}
#kd{position:absolute;left:10px;top:calc(env(safe-area-inset-top,0px) + 112px);font-size:11.5px;font-weight:800;background:rgba(10,6,24,.6);border:1px solid var(--st);padding:3px 10px;border-radius:10px;direction:rtl;line-height:1.5}
#coins{position:absolute;right:10px;top:calc(env(safe-area-inset-top,0px) + 54px)}
#feed{position:absolute;top:calc(env(safe-area-inset-top,0px) + 94px);right:10px;display:flex;flex-direction:column;gap:4px;align-items:flex-end}
.kf{direction:ltr;display:flex;align-items:center;gap:6px;font-size:12.5px;padding:3px 10px;border-radius:10px;background:rgba(10,6,24,.62);border:1px solid transparent;animation:fin .25s}.kf.me{border-color:var(--or2);background:rgba(90,40,10,.7)}
.kf i{width:22px;height:20px;color:#ffe9b0;display:block}.kf i svg{width:100%;height:100%}.kf em{font-style:normal;color:#ff7a8a;width:14px;height:14px;display:block}.kf em svg{width:100%;height:100%}@keyframes fin{from{opacity:0;transform:translateX(20px)}}
#xh{position:absolute;left:50%;top:50%;width:0;height:0}#xh i{position:absolute;background:#fff;box-shadow:0 0 2px #000,0 0 4px #000}
#xh i:nth-child(1){width:2px;height:9px;left:-1px;top:-18px}#xh i:nth-child(2){width:2px;height:9px;left:-1px;top:9px}#xh i:nth-child(3){width:9px;height:2px;left:-18px;top:-1px}#xh i:nth-child(4){width:9px;height:2px;left:9px;top:-1px}
#xh u{position:absolute;left:-1.5px;top:-1.5px;width:3px;height:3px;border-radius:50%;background:#ff5a3d}
#hm{position:absolute;left:50%;top:50%;width:0;height:0;opacity:0}#hm i{position:absolute;width:3px;height:11px;background:#fff;box-shadow:0 0 4px #000}
#hm i:nth-child(1){transform:translate(-18px,-18px) rotate(45deg)}#hm i:nth-child(2){transform:translate(16px,-18px) rotate(-45deg)}#hm i:nth-child(3){transform:translate(-18px,8px) rotate(-45deg)}#hm i:nth-child(4){transform:translate(16px,8px) rotate(45deg)}
#hm.f{animation:hmf .35s}@keyframes hmf{0%{opacity:1;transform:scale(1.5)}100%{opacity:0;transform:scale(1)}}#hm.h i{background:#ff3b3b}
.dn{position:absolute;left:50%;top:50%;font:900 18px var(--hf);color:#fff;text-shadow:0 2px 6px #000;animation:dnf .8s forwards}.dn.h{color:#ff5a4a;font-size:24px}@keyframes dnf{from{transform:translate(18px,-10px);opacity:1}to{transform:translate(18px,-60px);opacity:0}}
#ban{position:absolute;left:0;right:0;top:24%;text-align:center;opacity:0}#ban small{display:block;font-size:12px;color:var(--or2);letter-spacing:2px}#ban b{font:900 28px/1.1 var(--hf);text-shadow:0 2px 14px #000,0 0 18px #ff5a3d}#ban u{text-decoration:none;display:block;font:900 15px var(--hf);color:#ffe9a0}
#ban.f{animation:bnf 1.6s}@keyframes bnf{0%{opacity:0;transform:scale(1.6)}12%{opacity:1;transform:scale(1)}80%{opacity:1}100%{opacity:0;transform:translateY(-20px)}}
#cdn,#death,#over{position:absolute;inset:0;display:none;align-items:center;justify-content:center;text-align:center;flex-direction:column;font-weight:900;text-shadow:0 2px 12px #000}
#cdn{font:900 110px/1 var(--hf);color:var(--or2);text-shadow:0 0 30px #ff6a3d,0 4px 0 #5a1530}#cdn small{font:700 15px "Segoe UI",Tahoma,sans-serif;letter-spacing:3px;color:#fff}
#death{background:radial-gradient(circle,rgba(110,10,30,.15) 30%,rgba(120,10,30,.7) 100%);gap:6px}#death .dt{font:900 30px var(--hf);color:#ff7a8a;letter-spacing:2px}#death .dby{font-size:16px}#death .dsec{font:900 54px var(--hf);color:#fff}
#death .dh{font-size:12px;color:#ffe9a0;font-weight:700;margin-top:8px}
#over{background:rgba(10,6,24,.82);gap:6px;backdrop-filter:blur(4px)}#over .rs{font:900 64px/1 var(--hf);letter-spacing:3px;animation:pop .5s}#over .rs.w{background:linear-gradient(#fff3c4,#ffb454);-webkit-background-clip:text;background-clip:text;color:transparent;filter:drop-shadow(0 0 20px #ff8a3d)}#over .rs.l{color:#ff6a7a}#over .rs.t{color:#cbd}
#over .big{font:900 34px var(--hf);direction:ltr}#over .sm{font-size:14px;opacity:.85;font-weight:600}@keyframes pop{from{transform:scale(2);opacity:0}}
#scope{position:absolute;inset:0;display:none;background:radial-gradient(circle at 50% 50%,transparent 0,transparent 26vmin,rgba(0,0,0,.5) 29.6vmin,#000 30.5vmin)}
#scope svg{position:absolute;left:50%;top:50%;width:60vmin;height:60vmin;margin:-30vmin 0 0 -30vmin}
#scope b{position:absolute;left:50%;top:calc(50% + 31.5vmin);transform:translateX(-50%);font:700 11px monospace;color:#9fe;opacity:.8;letter-spacing:2px}
#dmg{position:absolute;inset:0;opacity:0;background:radial-gradient(circle,transparent 45%,rgba(255,20,40,.65) 100%);transition:opacity .35s}#dmg.on{opacity:1;transition:none}#dmg.lo{opacity:.5;animation:bl 1s infinite}
#dir{position:absolute;left:50%;top:50%;width:0;height:0}#dir i{position:absolute;left:-14px;top:-120px;width:28px;height:28px;color:#ff3b4e;filter:drop-shadow(0 0 4px #000);animation:dnf2 1.2s forwards}#dir i svg{width:100%;height:100%}@keyframes dnf2{0%{opacity:1}100%{opacity:0}}
#smk{position:absolute;inset:0;opacity:0;background:#9aa0a8;transition:opacity .25s}#fir{position:absolute;inset:0;opacity:0;background:radial-gradient(circle,rgba(255,150,40,.1) 30%,rgba(255,70,10,.6) 100%)}
#flash{position:absolute;inset:0;opacity:0;background:#fff;transition:opacity .5s}
#cdbar{position:absolute;left:50%;transform:translateX(-50%);bottom:calc(env(safe-area-inset-bottom,0px) + 40px);width:130px;height:5px;border-radius:3px;background:rgba(255,255,255,.18);overflow:hidden;opacity:0;transition:opacity .15s}#cdbar i{display:block;height:100%;background:linear-gradient(90deg,#ffb454,#ff6a4d);width:0}
#ammo{position:absolute;left:50%;transform:translateX(-50%);bottom:calc(env(safe-area-inset-bottom,0px) + 8px);font:900 20px var(--hf);letter-spacing:1px;text-shadow:0 2px 6px #000;direction:ltr;display:none}#ammo small{font-size:12px;opacity:.7}#ammo.z{color:#ff6a6a}
#slots{position:absolute;left:10px;bottom:calc(env(safe-area-inset-bottom,0px) + 12px);display:flex;gap:6px;direction:ltr;z-index:2}
.slot{position:relative;width:62px;height:44px;border-radius:12px;background:rgba(10,6,24,.62);border:1.5px solid rgba(255,255,255,.22);color:#b9a9c9;display:flex;align-items:center;justify-content:center;padding:6px 8px;transition:all .15s}
.slot.on{border-color:var(--or2);color:#fff;box-shadow:0 0 14px rgba(255,170,80,.55);background:linear-gradient(180deg,rgba(255,170,80,.38),rgba(10,6,24,.65))}
.slot.lk{opacity:.45;border-style:dashed}.slot.lk:after{content:"🔒";position:absolute;right:3px;bottom:1px;font-size:11px}
.slot span{position:absolute;top:1px;left:6px;font:800 10px sans-serif;opacity:.75}.slot svg{width:100%;height:100%}
#hint{position:absolute;left:0;right:0;bottom:calc(env(safe-area-inset-bottom,0px) + 120px);text-align:center;font-size:11.5px;color:#fff;text-shadow:0 1px 6px #000;opacity:.85;transition:opacity 1s}
.tg{position:absolute;top:calc(env(safe-area-inset-top,0px) + 8px);width:38px;height:38px;padding:8px;border-radius:50%;background:rgba(10,6,24,.65);border:1.5px solid rgba(255,255,255,.3);color:#fff;transform:scale(var(--bs))}
#bshop{right:10px;border-color:#ffc15e;color:#ffd27a}#bset{right:54px}#bsnd{right:98px}
.tg svg{width:100%;height:100%}
.b{display:none;position:absolute;flex-direction:column;align-items:center;justify-content:center;gap:1px;border-radius:50%;background:radial-gradient(circle at 35% 30%,rgba(255,255,255,.3),rgba(255,255,255,.07));border:2px solid rgba(255,255,255,.42);color:#fff;touch-action:none;box-shadow:0 4px 14px rgba(0,0,0,.45);padding:0;transform:scale(var(--bs));overflow:hidden}
.touch .b,body.editing .b{display:flex}.b svg{width:46%;height:46%;filter:drop-shadow(0 1px 2px #000)}.b small{font:800 10px/1 "Segoe UI",Tahoma,sans-serif;text-shadow:0 1px 3px #000;letter-spacing:.2px}.b:active{filter:brightness(1.5)}
.b .cdr{position:absolute;inset:0;border-radius:50%;background:conic-gradient(rgba(0,0,0,.6) calc(var(--p,0)*1%),transparent 0);pointer-events:none}.b .n{position:absolute;top:2px;right:5px;font:900 12px var(--hf);color:#ffe9a0;text-shadow:0 1px 3px #000}.b.off{opacity:.35}
#bf{right:18px;bottom:calc(env(safe-area-inset-bottom,0px) + 34px);width:96px;height:96px;background:radial-gradient(circle at 35% 30%,rgba(255,190,110,.85),rgba(255,70,60,.55));border-color:#ffb26e;box-shadow:0 0 22px rgba(255,100,50,.55)}#bf small{font-size:12px}
#bj{right:126px;bottom:calc(env(safe-area-inset-bottom,0px) + 30px);width:64px;height:64px;background:radial-gradient(circle at 35% 30%,rgba(150,255,170,.5),rgba(255,255,255,.07));border-color:#9af0a8}
#bl{right:124px;bottom:calc(env(safe-area-inset-bottom,0px) + 108px);width:62px;height:62px;background:radial-gradient(circle at 35% 30%,rgba(255,220,120,.55),rgba(255,255,255,.07));border-color:#ffd98a}
#bp{right:196px;bottom:calc(env(safe-area-inset-bottom,0px) + 36px);width:60px;height:60px;background:radial-gradient(circle at 35% 30%,rgba(200,150,255,.55),rgba(255,255,255,.07));border-color:#cfa8ff}
#bs{right:24px;bottom:calc(env(safe-area-inset-bottom,0px) + 144px);width:62px;height:62px;background:radial-gradient(circle at 35% 30%,rgba(120,230,255,.55),rgba(255,255,255,.07));border-color:#8fe6ff}
#br{right:196px;bottom:calc(env(safe-area-inset-bottom,0px) + 106px);width:56px;height:56px}
.q{width:50px;height:50px}.q small{font-size:9px}
#bk{left:10px;top:48%}#bg_{left:66px;top:48%}#bh{left:10px;top:calc(48% + 56px)}#bm{left:66px;top:calc(48% + 56px)}
#joy{position:absolute;display:none;width:110px;height:110px;margin:-55px;border-radius:50%;border:2px solid rgba(255,255,255,.4);background:radial-gradient(circle,rgba(255,255,255,.12),rgba(255,255,255,.04));box-shadow:0 0 16px rgba(0,0,0,.4)}
#joy i,#joyfix i{position:absolute;left:50%;top:50%;width:48px;height:48px;margin:-24px;border-radius:50%;background:radial-gradient(circle at 35% 30%,#fff,#ffcf8a);opacity:.85}
#joyfix{display:none;position:absolute;left:24px;bottom:calc(env(safe-area-inset-bottom,0px) + 110px);width:110px;height:110px;border-radius:50%;border:2px dashed rgba(255,255,255,.5);background:radial-gradient(circle,rgba(255,255,255,.1),rgba(255,255,255,.03))}
body.fixedjoy #joyfix{display:block}
body.editing #hud{display:block!important;background:rgba(6,3,16,.55);z-index:45}body.editing #hud>*:not(.ed){display:none!important}
body.editing .ed{outline:2px dashed #ffc15e;outline-offset:3px;cursor:grab;touch-action:none}body.editing #joyfix{display:block!important}body.editing .slot{pointer-events:none}
#editbar{display:none;position:fixed;left:50%;transform:translateX(-50%);bottom:calc(env(safe-area-inset-bottom,0px) + 12px);z-index:50;gap:8px;background:rgba(20,10,45,.92);border:1px solid var(--st);padding:8px;border-radius:16px}body.editing #editbar{display:flex}
#editnote{display:none;position:fixed;top:calc(env(safe-area-inset-top,0px) + 10px);left:0;right:0;text-align:center;z-index:50;font-weight:800;color:#ffc15e;text-shadow:0 2px 6px #000}body.editing #editnote{display:block}
</style></head><body>
<canvas id="cv"></canvas>
<div id="bg"><div class="sunb"></div><svg class="sky" viewBox="0 0 400 150" preserveAspectRatio="none"><polygon fill="#1a0f3a" points="0,150 0,92 24,92 24,72 44,72 44,96 60,96 60,64 82,64 82,98 100,98 100,84 128,84 128,100 142,100 142,68 166,68 166,98 182,98 182,108 206,108 206,80 226,80 226,104 244,104 244,90 266,90 266,60 284,60 284,96 300,96 300,74 322,74 322,100 340,100 340,86 362,86 362,106 380,106 380,70 400,70 400,150"/><polygon fill="#0d0820" points="0,150 0,112 18,112 18,98 40,98 40,116 70,116 70,92 92,92 92,118 120,118 120,104 150,104 150,120 176,120 176,100 200,100 200,122 232,122 232,96 256,96 256,118 290,118 290,102 312,102 312,120 346,120 346,98 372,98 372,114 400,114 400,150"/></svg></div>
<div id="msg"></div>
<div class="scr" id="menu"><div class="wrap">
<div class="logo"><svg class="em" viewBox="0 0 48 48" fill="none" stroke="currentColor" stroke-width="2.5"><circle cx="24" cy="24" r="16"/><circle cx="24" cy="24" r="3" fill="currentColor"/><path d="M24 2v10M24 36v10M2 24h10M36 24h10"/></svg><div class="l1">CALL OF</div><div class="l2">DUSY</div><div class="tag">سكاكين • سنايبرات • M4 • PKC • قنابل</div></div>
<div class="card"><button class="btn pri big" data-a="create" id="bcreate"></button></div>
<div class="or">أو</div>
<div class="card"><div class="lab"><span>انضم لغرفة صديقك</span></div><div class="rw"><input id="jin" maxlength="8" placeholder="الكود" autocomplete="off" autocapitalize="characters"><button class="btn blue" data-a="join" id="bjoin"></button></div></div>
<div class="card"><button class="btn big" style="font-size:16px;padding:12px" data-a="settings" id="bsetm"></button></div>
<div class="cn" id="cn"><i></i><span>جاري الاتصال...</span></div>
<div class="ctl">الجوال: عصا يسار للحركة • اسحب لليمين للتصويب<br>الكمبيوتر: WASD + ماوس • C تزحلق • Z انبطاح • B متجر • F/G/H/V رمي</div>
</div></div>
<div class="scr" id="lobby" style="display:none"><div class="wrap">
<div class="logo"><div class="l1">CALL OF</div><div class="l2" style="font-size:44px">DUSY</div></div>
<div class="card"><div class="lab"><span>كود الغرفة</span><button class="btn red sm" data-a="leave" id="bleave"></button></div><div class="rw"><div id="code">-----</div><div class="sp"></div><button class="btn pri sm" data-a="share" id="bshare"></button><button class="btn ic" data-a="copy" id="bcopy"></button></div></div>
<div class="card"><div class="lab"><span>اللاعبون</span><span id="pc">0/8</span></div><div id="plist"></div></div>
<div class="card" id="teams"><div class="lab"><span>اختر فريقك</span></div><div class="tg2">
<button class="tcard H" data-a="team:H" id="tH"><svg viewBox="0 0 48 48"><path d="M24 3 6 10v14c0 10 7 17 18 21 11-4 18-11 18-21V10Z" fill="currentColor" fill-opacity=".18" stroke="currentColor" stroke-width="2.5"/><path d="M9 22 24 13l15 9-15-3Zm7 7 8-4 8 4-8 9Z" fill="currentColor"/></svg><b>الصقور</b><small id="cH">0 لاعب</small></button>
<button class="tcard V" data-a="team:V" id="tV"><svg viewBox="0 0 48 48"><path d="M24 3 6 10v14c0 10 7 17 18 21 11-4 18-11 18-21V10Z" fill="currentColor" fill-opacity=".18" stroke="currentColor" stroke-width="2.5"/><path d="M12 13l6 7h12l6-7v13l-6 10H18l-6-10Z" fill="currentColor"/><circle cx="19" cy="26" r="2" fill="#140c2b"/><circle cx="29" cy="26" r="2" fill="#140c2b"/></svg><b>الذئاب</b><small id="cV">0 لاعب</small></button></div></div>
<div class="card" id="hostctl" style="display:none"><div class="lab"><span>إعدادات المباراة</span></div>
<div class="seg" style="margin-bottom:10px"><button data-a="mode:manual" id="mm">اختيار يدوي</button><button data-a="mode:random" id="mr">فرق عشوائية</button></div>
<div class="maps"><button class="mp" data-a="map:0" id="m0" style="--g:linear-gradient(180deg,#3a2a7a,#d9607a 45%,#ffb066)"><div class="ic2">🏜️</div><span>أطلال الصحراء</span></button><button class="mp" data-a="map:1" id="m1" style="--g:linear-gradient(180deg,#16254f,#6f86b8 50%,#e9dfe9)"><div class="ic2">❄️</div><span>القاعدة الثلجية</span></button><button class="mp" data-a="map:2" id="m2" style="--g:linear-gradient(180deg,#050512,#3a1a6a 50%,#c4506a)"><div class="ic2">🌃</div><span>أسطح المدينة</span></button></div>
<button class="btn pri big" id="start" data-a="start">ابدأ المعركة</button></div>
<div id="wait" style="display:none">بانتظار صاحب الغرفة ليبدأ المباراة <i>● ● ●</i></div>
<button class="btn" data-a="settings" id="bsetl" style="font-size:14px"></button>
</div></div>
<div class="modal" id="shop"><div class="mbox"><div class="mh"><b>المتجر</b><span class="coin" id="shopcoins"></span><button class="btn ic" data-a="closeshop">✕</button></div>
<div class="st">الأسلحة</div><div id="shopw"></div><div class="st">القنابل (حد أقصى 2 من كل نوع)</div><div id="shopg"></div>
<div class="ctl" style="margin-top:10px">كل قتلة = 5 عملات • هيدشوت = 8 عملات • السكين والسنايبر مجانيين</div></div></div>
<div class="modal" id="set"><div class="mbox"><div class="mh"><b>الإعدادات</b><button class="btn ic" data-a="closeset">✕</button></div>
<div class="st">الصوت</div><div class="seg"><button data-a="snd:1" id="sn1">مفعّل</button><button data-a="snd:0" id="sn0">مكتوم</button></div>
<div class="st">حساسية التصويب</div><div class="sl"><span id="vsens">1.0</span><input type="range" id="rsens" min="0.4" max="2.4" step="0.1"></div>
<div class="st">حجم الأزرار</div><div class="sl"><span id="vbs">1.0</span><input type="range" id="rbs" min="0.7" max="1.5" step="0.05"></div>
<div class="st">نوع الجويستك</div><div class="seg"><button data-a="joy:float" id="jf">عائم (يظهر حيث تلمس)</button><button data-a="joy:fixed" id="jx">ثابت (مكان محدد)</button></div>
<div class="st">جهة الحركة (الجويستك)</div><div class="seg"><button data-a="side:L" id="sdL">يسار</button><button data-a="side:R" id="sdR">يمين</button></div>
<div class="st">أماكن الأزرار</div><div class="rw"><button class="btn pri sm" style="flex:1" data-a="edit">✋ تعديل الأماكن (اسحب كل زر)</button></div><div class="rw" style="margin-top:8px"><button class="btn red sm" style="flex:1" data-a="resetlay">إعادة الأماكن الافتراضية</button></div>
</div></div>
<div id="editnote">اسحب أي زر أو الجويستك أو خانات الأسلحة إلى المكان اللي يريحك</div>
<div id="editbar"><button class="btn pri" data-a="editdone">✓ تم</button><button class="btn red" data-a="resetlay">إعادة ضبط</button></div>
<div id="hud">
<div id="smk"></div><div id="fir"></div><div id="dmg"></div><div id="dir"></div><div id="flash"></div>
<div id="sc"><div class="tm H"><b id="sH">0</b><small>الصقور</small><div class="bar" style="color:#3ee6d0"><i id="bH"></i></div></div><div class="clk" id="clk">5:00</div><div class="tm V"><b id="sV">0</b><small>الذئاب</small><div class="bar" style="color:#ff5a6e"><i id="bV"></i></div></div></div>
<div id="hpw"><i id="hpi"></i><b id="hpn">100</b></div>
<canvas id="radar" width="200" height="200"></canvas><div id="kd"></div>
<div class="coin" id="coins"></div>
<div id="feed"></div>
<button class="tg ed" id="bshop" data-ctl="bshop" data-a="shop"></button><button class="tg ed" id="bset" data-ctl="bset" data-a="settings"></button><button class="tg ed" id="bsnd" data-ctl="bsnd" data-a="snd"></button>
<div id="xh"><i></i><i></i><i></i><i></i><u></u></div><div id="hm"><i></i><i></i><i></i><i></i></div>
<div id="scope"><svg viewBox="-50 -50 100 100" stroke="#000" fill="#000"><g stroke-linecap="butt"><line x1="-50" y1="0" x2="-14" y2="0" stroke-width="1.2"/><line x1="14" y1="0" x2="50" y2="0" stroke-width="1.2"/><line x1="0" y1="-50" x2="0" y2="-14" stroke-width="1.2"/><line x1="0" y1="14" x2="0" y2="50" stroke-width="1.2"/><line x1="-14" y1="0" x2="14" y2="0" stroke-width=".22"/><line x1="0" y1="-14" x2="0" y2="14" stroke-width=".22"/></g><g stroke="none"><circle cx="-5" cy="0" r=".55"/><circle cx="5" cy="0" r=".55"/><circle cx="-9" cy="0" r=".55"/><circle cx="9" cy="0" r=".55"/><circle cx="0" cy="-5" r=".55"/><circle cx="0" cy="5" r=".55"/><circle cx="0" cy="-9" r=".55"/><circle cx="0" cy="9" r=".55"/><circle cx="0" cy="0" r=".4" fill="#f33"/></g></svg><b>x18</b></div>
<div id="ban"></div><div id="cdn"></div><div id="death"></div><div id="over"></div>
<div id="hint"></div><div id="cdbar"><i></i></div><div id="ammo"></div>
<div id="slots" class="ed" data-ctl="slots"><div class="slot" id="s1" data-w="k"><span>1</span></div><div class="slot" id="s2" data-w="s"><span>2</span></div><div class="slot" id="s3" data-w="m4"><span>3</span></div><div class="slot" id="s4" data-w="pkc"><span>4</span></div></div>
<div id="joy"><i></i></div><div id="joyfix" class="ed" data-ctl="joyfix"><i></i></div>
<button class="b ed" id="bf" data-ctl="bf"></button><button class="b ed" id="bj" data-ctl="bj"></button><button class="b ed" id="bs" data-ctl="bs"></button><button class="b ed" id="bl" data-ctl="bl"></button><button class="b ed" id="bp" data-ctl="bp"></button><button class="b ed" id="br" data-ctl="br"></button>
<button class="b q ed" id="bk" data-ctl="bk"></button><button class="b q ed" id="bg_" data-ctl="bg_"></button><button class="b q ed" id="bh" data-ctl="bh"></button><button class="b q ed" id="bm" data-ctl="bm"></button>
</div>
<script>
const $=s=>document.querySelector(s),$$=s=>[...document.querySelectorAll(s)],esc=s=>String(s).replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
const TG=window.Telegram&&Telegram.WebApp;if(TG){TG.ready();TG.expand();try{TG.disableVerticalSwipes()}catch(e){}}
const hap=t=>{try{TG&&TG.HapticFeedback&&TG.HapticFeedback.impactOccurred(t||'light')}catch(e){}};
const qs=new URLSearchParams(location.search),ROOM=(qs.get('room')||(TG&&TG.initDataUnsafe&&TG.initDataUnsafe.start_param)||'').toUpperCase();
const touch='ontouchstart' in window||navigator.maxTouchPoints>0;document.body.classList.toggle('touch',touch);
const TN={H:'الصقور',V:'الذئاب'},TCOL={H:'#3ee6d0',V:'#ff5a6e'};
let cfg={snd:1,sens:1,bs:1,joy:'float',side:'L',pos:{}};
try{Object.assign(cfg,JSON.parse(localStorage.getItem('dusy_cfg')||'{}'))}catch(e){}
const saveCfg=()=>{try{localStorage.setItem('dusy_cfg',JSON.stringify(cfg))}catch(e){}};
let ws,me,Rm=null,boxes=[],others={},alive=false,playing=false,goAt=0,wp='k',scoped=false,cd=0,cdStart=0,cdLen=0,myTeam='H',fireHeld=false,mapI=0,keys={},joy={x:0,y:0},WIN=25,kills=0,deaths=0,lastSc=[0,0],mv=0,deathEnd=0,lastCd=0,hintT=0,screen='menu',editing=false,shopOpen=false,hp=100,rtt=0,joined=false;
let inv={coins:0,own:['k','s'],gr:{frag:0,smoke:0,molo:0},kn:true,ammo:{m4:30,pkc:100}},reloadEnd=0,reloadLen=0;
const P={x:0,y:0,z:0,yaw:0,pitch:0,vy:0,ground:true};
const send=o=>ws&&ws.readyState===1&&ws.send(JSON.stringify(o)),show=(e,v)=>$(e).style.display=v?(v===1?'block':v):'none';
let noteT=0;function note(t,sticky){const m=$('#msg');m.textContent=t;m.style.display='block';clearTimeout(noteT);if(!sticky)noteT=setTimeout(()=>m.style.display='none',3800)}
/* ---------- icons ---------- */
const S1='fill="none" stroke="currentColor" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"';
const KNIFE='<polygon points="2.8,54.8 9.2,61.2 25.2,45.2 18.8,38.8"/><polygon points="17,35 29,47 31.5,44.5 19.5,32.5"/><path d="M24 34 54 4Q60 2 60 4Q56 26 31 41Z"/>';
const IC={
k:`<svg viewBox="0 0 64 64" fill="currentColor">${KNIFE}</svg>`,
knt:`<svg viewBox="0 0 64 64" fill="currentColor"><g transform="translate(8,0)">${KNIFE}</g><path d="M2 18h12M0 30h10M4 42h12" stroke="currentColor" stroke-width="3.5" stroke-linecap="round" opacity=".7"/></svg>`,
s:'<svg viewBox="0 0 96 32" fill="currentColor"><polygon points="2,10 24,12 24,19 12,24 2,20"/><rect x="24" y="11" width="26" height="8"/><rect x="50" y="13" width="44" height="3.5"/><rect x="90" y="11.5" width="5" height="6.5"/><rect x="30" y="3" width="26" height="5" rx="2.5"/><rect x="54" y="1.5" width="6" height="8" rx="1"/><rect x="26" y="2.5" width="5" height="6" rx="1"/><rect x="34" y="8" width="3" height="3"/><rect x="48" y="8" width="3" height="3"/><polygon points="26,19 32,19 30,28 24,28"/><rect x="38" y="19" width="7" height="6"/></svg>',
m4:'<svg viewBox="0 0 96 32" fill="currentColor"><rect x="2" y="12" width="16" height="7"/><rect x="16" y="9" width="30" height="9"/><rect x="44" y="11" width="40" height="5"/><rect x="82" y="9.5" width="10" height="8"/><polygon points="26,18 34,18 32,30 25,30"/><polygon points="14,18 20,18 18,28 13,28"/><rect x="24" y="5" width="14" height="4"/><rect x="50" y="8" width="3" height="3"/></svg>',
pkc:'<svg viewBox="0 0 96 32" fill="currentColor"><rect x="2" y="11" width="22" height="8"/><rect x="22" y="8" width="34" height="11"/><rect x="54" y="12" width="40" height="4"/><rect x="40" y="19" width="14" height="10" rx="1"/><rect x="62" y="9" width="22" height="9" rx="2" opacity=".85"/><polygon points="26,19 33,19 31,28 25,28"/><path d="M80 17 86 28M84 17 90 28" stroke="currentColor" stroke-width="2"/></svg>',
cross:`<svg viewBox="0 0 48 48" ${S1}><circle cx="24" cy="24" r="13"/><path d="M24 4v10M24 34v10M4 24h10M34 24h10"/></svg>`,
jump:`<svg viewBox="0 0 48 48" ${S1} stroke-width="5"><path d="M24 36V9M11 21 24 8l13 13"/><path d="M12 43h24" opacity=".6"/></svg>`,
scope:`<svg viewBox="0 0 48 48" ${S1} stroke-width="3.5"><circle cx="24" cy="24" r="17"/><path d="M24 2v14M24 32v14M2 24h14M32 24h14"/><circle cx="24" cy="24" r="2" fill="currentColor"/></svg>`,
slide:`<svg viewBox="0 0 48 48" ${S1}><circle cx="33" cy="9" r="3.5" fill="currentColor"/><path d="M30 15 22 26M30 15l8 6M22 26l17 5M22 26l-8 9"/><path d="M3 41h36M3 35h9" stroke-width="3" opacity=".65"/></svg>`,
prone:`<svg viewBox="0 0 48 48" ${S1}><circle cx="9" cy="25" r="3.5" fill="currentColor"/><path d="M15 28h21l8 4M20 28l-3 8M36 28l8-3"/><path d="M3 41h42" stroke-width="3" opacity=".65"/></svg>`,
reload:`<svg viewBox="0 0 48 48" ${S1}><path d="M39 24a15 15 0 1 1-5-11.2"/><path d="M35 5v9h-9"/></svg>`,
shop:`<svg viewBox="0 0 48 48" ${S1}><path d="M4 8h6l5 22h22l5-17H12"/><circle cx="18" cy="39" r="3" fill="currentColor"/><circle cx="34" cy="39" r="3" fill="currentColor"/></svg>`,
frag:'<svg viewBox="0 0 48 48" fill="currentColor"><ellipse cx="22" cy="30" rx="12" ry="14"/><rect x="17" y="8" width="9" height="7" rx="1.5"/><path d="M26 10h10l4 5" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round"/><circle cx="41" cy="20" r="3" fill="none" stroke="currentColor" stroke-width="2.5"/><path d="M12 27h20M11 33h22" stroke="#000" stroke-opacity=".35" stroke-width="2"/></svg>',
smoke:'<svg viewBox="0 0 48 48" fill="currentColor"><rect x="16" y="24" width="16" height="20" rx="3"/><rect x="20" y="19" width="8" height="6"/><path d="M10 15a6 6 0 0 1 4-9 7 7 0 0 1 13-1 6 6 0 0 1 8 8 5 5 0 0 1-2 6H12a5 5 0 0 1-2-4z" opacity=".7"/></svg>',
molo:'<svg viewBox="0 0 48 48" fill="currentColor"><path d="M20 21h8v5l5 6v10a3 3 0 0 1-3 3H18a3 3 0 0 1-3-3V32l5-6z"/><rect x="22" y="16" width="4" height="6"/><path d="M24 3c3 4 7 6 5 11-1 2-3 3-5 3s-5-1-5-4c0-3 2-4 2-6 0-2 2-3 3-4z" fill="#ffb454"/></svg>',
gear:`<svg viewBox="0 0 48 48" ${S1}><circle cx="24" cy="24" r="7"/><path d="M24 4v7M24 37v7M4 24h7M37 24h7M10 10l5 5M33 33l5 5M38 10l-5 5M15 33l-5 5"/></svg>`,
coin:'<svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="10" fill="#ffc83a" stroke="#b07a00" stroke-width="1.5"/><circle cx="12" cy="12" r="6.5" fill="none" stroke="#b07a00" stroke-width="1.3"/><path d="M12 8v8M9.5 10.5h5M9.5 13.5h5" stroke="#b07a00" stroke-width="1.4" stroke-linecap="round"/></svg>',
plus:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round"><path d="M12 4v16M4 12h16"/></svg>',
door:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"><path d="M14 4h6v16h-6M3 12h12M11 8l4 4-4 4"/></svg>',
skull:'<svg viewBox="0 0 48 48" fill="currentColor"><path d="M24 4C13 4 7 12 7 21c0 6 3 9 6 11v8h22v-8c3-2 6-5 6-11C41 12 35 4 24 4Zm-8 22a4 4 0 1 1 0-8 4 4 0 0 1 0 8Zm16 0a4 4 0 1 1 0-8 4 4 0 0 1 0 8Z"/></svg>',
arrow:'<svg viewBox="0 0 24 24" fill="currentColor"><path d="M12 2 22 20 12 15 2 20z"/></svg>',
share:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.3" stroke-linecap="round" stroke-linejoin="round"><circle cx="18" cy="5" r="3"/><circle cx="6" cy="12" r="3"/><circle cx="18" cy="19" r="3"/><path d="m8.6 10.5 6.8-4M8.6 13.5l6.8 4"/></svg>',
copy:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.3" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="12" height="12" rx="2"/><path d="M5 15V5a2 2 0 0 1 2-2h8"/></svg>',
on:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.3" stroke-linecap="round" stroke-linejoin="round"><path d="M11 5 6 9H2v6h4l5 4Z"/><path d="M15.5 8.5a5 5 0 0 1 0 7M18.5 5.5a9 9 0 0 1 0 13"/></svg>',
off:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.3" stroke-linecap="round" stroke-linejoin="round"><path d="M11 5 6 9H2v6h4l5 4Z"/><path d="m22 9-6 6M16 9l6 6"/></svg>'};
const WIC={k:IC.k,s:IC.s,m4:IC.m4,pkc:IC.pkc,g:IC.frag,m:IC.molo,t:IC.knt,f:IC.skull};
const bt=(id,ic,lb,extra)=>{$(id).innerHTML=ic+'<small>'+lb+'</small>'+(extra||'')};
bt('#bj',IC.jump,'قفز');bt('#bs',IC.scope,'منظار');bt('#bl',IC.slide,'تزحلق','<span class="cdr"></span>');bt('#bp',IC.prone,'انبطاح');bt('#br',IC.reload,'تعبئة');
bt('#bk',IC.knt,'رمي سكين');bt('#bg_',IC.frag,'قنبلة','<span class="n"></span>');bt('#bh',IC.smoke,'دخان','<span class="n"></span>');bt('#bm',IC.molo,'مولوتوف','<span class="n"></span>');
$('#bshop').innerHTML=IC.shop;$('#bset').innerHTML=IC.gear;
$('#s1').insertAdjacentHTML('beforeend',IC.k);$('#s2').insertAdjacentHTML('beforeend',IC.s);$('#s3').insertAdjacentHTML('beforeend',IC.m4);$('#s4').insertAdjacentHTML('beforeend',IC.pkc);
$('#bcreate').innerHTML=IC.plus+'<span>إنشاء غرفة</span>';$('#bjoin').innerHTML=IC.door+'<span>انضمام</span>';$('#bsetm').innerHTML=IC.gear+'<span>الإعدادات وأماكن الأزرار</span>';$('#bsetl').innerHTML=IC.gear+'<span>الإعدادات</span>';
$('#bleave').innerHTML=IC.door+'<span>مغادرة</span>';$('#bshare').innerHTML=IC.share+'<span>دعوة</span>';$('#bcopy').innerHTML=IC.copy;
const coinH=n=>IC.coin+'<span>'+n+'</span>';
/* ---------- audio (synth) ---------- */
let AC=null,NB=null;
function ac(){if(!AC){try{AC=new(window.AudioContext||window.webkitAudioContext)()}catch(e){}}if(AC&&AC.state==='suspended')AC.resume();return AC}
function nbuf(){if(NB)return NB;const a=ac(),n=a.sampleRate;NB=a.createBuffer(1,n,a.sampleRate);const d=NB.getChannelData(0);for(let i=0;i<n;i++)d[i]=Math.random()*2-1;return NB}
function snd(k,v){if(!cfg.snd)return;v=v==null?1:v;const a=ac();if(!a)return;const t=a.currentTime;
const env=(g,pk,dur,at)=>{g.gain.setValueAtTime(.0001,at);g.gain.exponentialRampToValueAtTime(Math.max(.0002,pk),at+.006);g.gain.exponentialRampToValueAtTime(.0001,at+dur)};
const nz=(dur,type,f0,f1,pk,at,q)=>{at=at||t;const s=a.createBufferSource();s.buffer=nbuf();const f=a.createBiquadFilter();f.type=type;f.Q.value=q||1;f.frequency.setValueAtTime(f0,at);f.frequency.exponentialRampToValueAtTime(f1,at+dur);const g=a.createGain();env(g,pk*v,dur,at);s.connect(f);f.connect(g);g.connect(a.destination);s.start(at,Math.random()*.4,dur+.05)};
const tn=(type,f0,f1,dur,pk,at)=>{at=at||t;const o=a.createOscillator();o.type=type;o.frequency.setValueAtTime(f0,at);o.frequency.exponentialRampToValueAtTime(f1,at+dur);const g=a.createGain();env(g,pk*v,dur,at);o.connect(g);g.connect(a.destination);o.start(at);o.stop(at+dur+.05)};
switch(k){
case'snipe':nz(.55,'lowpass',2800,140,1,t);nz(.07,'highpass',3000,7000,.7,t);tn('sine',150,32,.4,.9);nz(.8,'lowpass',600,90,.28,t+.14);break;
case'm4':nz(.1,'lowpass',4500,700,.8,t);nz(.03,'highpass',3500,7000,.5,t);tn('sine',130,50,.1,.5);break;
case'pkc':nz(.14,'lowpass',3500,450,1,t);nz(.04,'highpass',3000,6000,.5,t);tn('sine',95,38,.16,.75);break;
case'knife':nz(.22,'bandpass',500,3600,.7,t,2);break;
case'throw':nz(.18,'bandpass',300,1400,.45,t,1.5);break;
case'bolt':tn('square',320,180,.05,.12,t+.02);tn('square',180,340,.05,.12,t+.15);break;
case'reload':tn('square',500,300,.04,.12,t);tn('square',260,420,.05,.14,t+.5);tn('square',700,500,.03,.1,t+.9);break;
case'swap':nz(.06,'highpass',2000,4500,.25);break;
case'slide':nz(.55,'bandpass',250,900,.35,t,1.2);break;
case'hit':tn('sine',880,880,.1,.5);tn('sine',1320,1320,.16,.5,t+.09);break;
case'head':tn('sine',1200,1200,.08,.6);tn('sine',1800,1800,.2,.6,t+.07);break;
case'hurt':tn('sawtooth',160,90,.18,.3);break;
case'buy':tn('triangle',1100,1100,.1,.4);tn('triangle',1650,1650,.2,.4,t+.09);break;
case'frag':nz(1.4,'lowpass',1200,50,1.4,t);tn('sine',80,22,.9,1.1);nz(.1,'highpass',2000,5000,.6,t);break;
case'smoke':nz(1,'bandpass',3500,900,.35,t,.7);break;
case'molo':nz(.12,'highpass',4000,8000,.6,t);nz(.7,'lowpass',900,200,.7,t+.05);break;
case'die':tn('sawtooth',230,45,.65,.3);break;
case'tick':tn('sine',660,660,.1,.4);break;
case'go':tn('sine',990,990,.4,.5);break;
case'win':[523,659,784,1047].forEach((f,i)=>tn('triangle',f,f,.3,.4,t+i*.12));break;
case'lose':[392,330,262].forEach((f,i)=>tn('triangle',f,f*.97,.4,.35,t+i*.18));break}}
addEventListener('pointerdown',()=>ac(),{once:true});
function setSnd(){const h=IC[cfg.snd?'on':'off'];$('#bsnd').innerHTML=h;$('#sn1').classList.toggle('on',!!cfg.snd);$('#sn0').classList.toggle('on',!cfg.snd)}
/* ---------- settings + layout editor ---------- */
function applyCfg(){document.documentElement.style.setProperty('--bs',cfg.bs);document.body.classList.toggle('fixedjoy',cfg.joy==='fixed');
$$('[data-ctl]').forEach(el=>{const p=cfg.pos[el.dataset.ctl];if(p){el.style.left=p[0]+'%';el.style.top=p[1]+'%';el.style.right=el.style.bottom='auto'}else{el.style.left=el.style.top=el.style.right=el.style.bottom=''}});
setSnd();$('#jf').classList.toggle('on',cfg.joy==='float');$('#jx').classList.toggle('on',cfg.joy==='fixed');$('#sdL').classList.toggle('on',cfg.side==='L');$('#sdR').classList.toggle('on',cfg.side==='R');
$('#rsens').value=cfg.sens;$('#vsens').textContent=(+cfg.sens).toFixed(1);$('#rbs').value=cfg.bs;$('#vbs').textContent=(+cfg.bs).toFixed(2)}
$('#rsens').addEventListener('input',e=>{cfg.sens=+e.target.value;$('#vsens').textContent=cfg.sens.toFixed(1);saveCfg()});
$('#rbs').addEventListener('input',e=>{cfg.bs=+e.target.value;$('#vbs').textContent=cfg.bs.toFixed(2);document.documentElement.style.setProperty('--bs',cfg.bs);saveCfg()});
function openSet(){show('#set','flex');document.exitPointerLock&&document.exitPointerLock()}
function startEdit(){show('#set',0);editing=true;document.body.classList.add('editing')}
function endEdit(){editing=false;document.body.classList.remove('editing');saveCfg()}
let drag=null;
document.addEventListener('pointerdown',e=>{if(!editing)return;const el=e.target.closest('.ed');if(!el)return;e.preventDefault();const r=el.getBoundingClientRect();drag={el,dx:e.clientX-(r.left+r.width/2),dy:e.clientY-(r.top+r.height/2)};try{el.setPointerCapture(e.pointerId)}catch(_){}});
document.addEventListener('pointermove',e=>{if(!drag)return;const el=drag.el,w=el.offsetWidth,h=el.offsetHeight,l=(e.clientX-drag.dx-w/2)/innerWidth*100,t=(e.clientY-drag.dy-h/2)/innerHeight*100;el.style.left=l+'%';el.style.top=t+'%';el.style.right=el.style.bottom='auto';cfg.pos[el.dataset.ctl]=[+l.toFixed(2),+t.toFixed(2)]});
document.addEventListener('pointerup',()=>{if(drag){drag=null;saveCfg()}});
/* ---------- network ---------- */
let reconT=0;
function connect(){ws=new WebSocket((location.protocol==='https:'?'wss://':'ws://')+location.host+'/ws');
ws.onopen=()=>{$('#cn').classList.add('ok');$('#cn span').textContent='متصل';if(ROOM&&!joined&&!qs.get('x')){joinRoom(ROOM)}};
ws.onclose=()=>{$('#cn').classList.remove('ok');$('#cn span').textContent='انقطع الاتصال... جاري إعادة المحاولة';if(joined){note('انقطع الاتصال بالسيرفر',1)}joined=false;Rm=null;endGame();showScr('menu');clearTimeout(reconT);reconT=setTimeout(connect,2000)};
ws.onmessage=e=>on(JSON.parse(e.data))}
const initD=()=>TG?TG.initData:'';
function joinRoom(code){if(!code)return note('اكتب كود الغرفة');send({t:'join',init:initD(),room:code,guest:qs.get('guest')||''})}
setInterval(()=>send({t:'ping',c:performance.now()}),2000);
function showScr(s){screen=s;show('#menu',s==='menu'?1:0);show('#lobby',s==='lobby'?1:0);show('#bg',s==='game'?0:1);show('#hud',s==='game'?1:0)}
function on(m){switch(m.t){
case'pong':rtt=rtt?rtt*.6+(performance.now()-m.c)*.4:performance.now()-m.c;send({t:'rtt',v:Math.round(rtt)});updKD();break;
case'err':note(m.m);break;
case'toast':note(m.m);break;
case'me':me=m.id;joined=true;break;
case'room':Rm=m;joined=true;if(m.state==='lobby'){endGame();lobby()}break;
case'start':startGame(m);break;
case'spawn':P.x=m.x;P.y=m.y;P.z=m.z;P.yaw=m.yaw;P.pitch=0;P.vy=0;P.ground=true;stance=0;slideT=0;alive=true;hp=100;updHp(0);show('#death',0);wp==='k'&&!inv.kn&&setWp('s');setWp(wp);break;
case'dead':alive=false;scoped=false;stance=0;fireHeld=false;setWp(wp);deathEnd=performance.now()+m.sec*1000;$('#death').innerHTML='<div class="dt">تم القضاء عليك</div>'+(m.by?'<div class="dby">بواسطة <b>'+esc(m.by)+'</b></div>':'')+'<div class="dsec" id="dsec">'+m.sec+'</div><div class="dh">'+IC.coin.replace('<svg','<svg style="width:14px;height:14px;display:inline;vertical-align:-2px"')+' عملاتك: '+inv.coins+' — اشتري من المتجر 🛒</div>';show('#death','flex');break;
case'hp':{const old=hp;hp=m.hp;updHp(old-hp);if(m.a&&old>hp)dirInd(m.a);break}
case'hit':{const h=document.querySelector('#hm');h.classList.remove('f','h');void h.offsetWidth;h.classList.add('f');if(m.h)h.classList.add('h');snd(m.h?'head':'hit');const d=document.createElement('div');d.className='dn'+(m.h?' h':'');d.textContent='-'+m.d;$('#hud').appendChild(d);setTimeout(()=>d.remove(),800);hap(m.h?'heavy':'light');break}
case'inv':inv=m;updInv();break;
case'bought':snd('buy');if(m.i==='m4'||m.i==='pkc')setWp(m.i);break;
case'ammo':if(m.n!=null)inv.ammo[m.w]=m.n;if(m.rl){reloadEnd=performance.now()+m.rl*1000;reloadLen=m.rl*1000;if(m.w===wp)snd('reload')}else{reloadEnd=0}updAmmo();break;
case'snap':snap(m);break;
case'kill':{const c=t=>TCOL[t]||'#fff',d=document.createElement('div');d.className='kf'+(m.kid===me?' me':'');
d.innerHTML=(m.k?`<b style="color:${c(m.kt)}">${esc(m.k)}</b>`:'')+`<i>${WIC[m.w]||IC.skull}</i>`+(m.hs?`<em>${IC.skull}</em>`:'')+`<b style="color:${c(m.vt)}">${esc(m.v)}</b>`;$('#feed').prepend(d);while($('#feed').children.length>5)$('#feed').lastChild.remove();setTimeout(()=>d.remove(),4500);
if(m.kid===me&&m.k&&m.kid!==m.vid){kills++;banner(m.v,m.hs?8:5,m.hs)}
if(m.vid===me){deaths++;snd('die');hap('rigid')}updKD();break}
case'shot':onShot(m);break;
case'thr':spawnProj(m);break;
case'knh':knifeStuck(m);break;
case'knp':removeProj(m.id);break;
case'boom':boom(m);break;
case'end':{alive=false;scoped=false;fireHeld=false;document.exitPointerLock&&document.exitPointerLock();const w=m.win,cls=w==='T'?'t':w===myTeam?'w':'l',txt=w==='T'?'تعادل':w===myTeam?'النصر':'الهزيمة';
$('#over').innerHTML=`<div class="rs ${cls}">${txt}</div><div class="big"><span style="color:#3ee6d0">${lastSc[0]}</span> : <span style="color:#ff5a6e">${lastSc[1]}</span></div><div class="sm">${w==='T'?'':'فاز فريق '+TN[w]}</div><div class="sm">قتلاتك ${kills} • موتاتك ${deaths}</div><div class="sm" style="opacity:.6;margin-top:10px">العودة إلى الغرفة خلال ثوانٍ...</div>`;closeShop();show('#over','flex');snd(cls==='w'?'win':'lose');hap(cls==='w'?'heavy':'light');break}
}}
function banner(n,c,hs){const b=$('#ban');b.innerHTML='<small>'+(hs?'هيدشوت! تم القضاء على':'تم القضاء على')+'</small><b>'+esc(n)+'</b><u>+'+c+' عملات</u>';b.classList.remove('f');void b.offsetWidth;b.classList.add('f')}
function updKD(){$('#kd').innerHTML='قتل '+kills+' • موت '+deaths+(rtt?'<br>📶 '+Math.round(rtt)+'ms':'')}
function updHp(lost){$('#hpi').style.width=Math.max(0,hp)+'%';$('#hpn').textContent=Math.max(0,Math.round(hp));$('#hpw').classList.toggle('lo',hp<35);$('#dmg').classList.toggle('lo',hp<35&&hp>0&&alive);if(lost>1){const d=$('#dmg');d.classList.add('on');setTimeout(()=>{d.classList.remove('on')},60);snd('hurt');hap('medium')}}
function dirInd(a){const dx=a[0]-P.x,dz=a[1]-P.z,c=Math.cos(P.yaw),sn=Math.sin(P.yaw),sx=dx*c-dz*sn,sy=dx*sn+dz*c,th=Math.atan2(sx,-sy)*180/Math.PI,w=document.createElement('div');w.style.cssText='position:absolute;left:0;top:0;width:0;height:0;transform:rotate('+th+'deg)';w.innerHTML='<i>'+IC.arrow+'</i>';$('#dir').appendChild(w);setTimeout(()=>w.remove(),1200)}
/* ---------- inventory / shop ---------- */
const SHOPW=[{id:'m4',n:'M4',d:'رشاش 30 طلقة • جسم 20 / راس 40 • دقة جيدة ومرن',p:20},{id:'pkc',n:'PKC',d:'رشاش ثقيل 100 طلقة • جسم 24 / راس 48 • أبطأ حركة وارتداد أقوى',p:35}];
const SHOPG=[{id:'frag',n:'قنبلة يدوية',ic:IC.frag,d:'تنفجر بعد 2.4 ثانية • حتى 120 دمج قريب • تقتل حتى بدون إصابة مباشرة',p:6},{id:'smoke',n:'قنبلة دخانية',ic:IC.smoke,d:'سحابة دخان تحجب الرؤية 12 ثانية • تغطي هجومك أو انسحابك',p:4},{id:'molo',n:'مولوتوف',ic:IC.molo,d:'يحرق المنطقة 5.5 ثانية • 12 دمج كل نصف ثانية',p:8}];
function renderShop(){$('#shopcoins').innerHTML=coinH(inv.coins);
$('#shopw').innerHTML=SHOPW.map(w=>{const own=inv.own.includes(w.id);return `<div class="sh${own?' own':''}"><div class="si">${IC[w.id]}</div><div class="sd"><b>${w.n}</b><small>${w.d}</small></div>${own?'<span class="chip H">مملوك ✓</span>':`<button class="btn pri" data-buy="${w.id}">${IC.coin}<span>${w.p}</span></button>`}</div>`}).join('');
$('#shopg').innerHTML=SHOPG.map(g=>{const n=inv.gr[g.id]||0;return `<div class="sh"><div class="si" style="width:40px">${g.ic}</div><div class="sd"><b>${g.n} <span style="color:#ffe9a0">(${n}/2)</span></b><small>${g.d}</small></div>${n>=2?'<span class="chip">ممتلئ</span>':`<button class="btn pri" data-buy="${g.id}">${IC.coin}<span>${g.p}</span></button>`}</div>`}).join('')}
function openShop(){if(screen!=='game'||!joined)return;shopOpen=true;fireHeld=false;renderShop();show('#shop','flex');document.exitPointerLock&&document.exitPointerLock()}
function closeShop(){shopOpen=false;show('#shop',0)}
$('#shop').addEventListener('click',e=>{const b=e.target.closest('[data-buy]');if(b)send({t:'buy',i:b.dataset.buy})});
const isAuto=w=>w==='m4'||w==='pkc';
function updInv(){$('#coins').innerHTML=coinH(inv.coins);if(shopOpen)renderShop();
[['#s1','k'],['#s2','s'],['#s3','m4'],['#s4','pkc']].forEach(([id,w])=>$(id).classList.toggle('lk',!inv.own.includes(w)||(w==='k'&&!inv.kn)));
$('#bk').classList.toggle('off',!inv.kn);[['#bg_','frag'],['#bh','smoke'],['#bm','molo']].forEach(([id,k])=>{$(id).classList.toggle('off',!inv.gr[k]);$(id+' .n').textContent=inv.gr[k]||''});
if(wp==='k'&&!inv.kn&&alive)setWp('s');updAmmo()}
function updAmmo(){const a=$('#ammo');$('#br').style.visibility=isAuto(wp)?'visible':'hidden';if(!isAuto(wp)){a.style.display='none';return}const n=inv.ammo[wp];a.style.display='block';a.className=n<=0?'z':'';a.innerHTML=(reloadEnd>performance.now()?'تعبئة...':n)+' <small>/ '+(wp==='m4'?30:100)+'</small>'}
/* ---------- lobby ---------- */
function lobby(){showScr('lobby');const host=Rm.host===me;$('#code').textContent=Rm.code;$('#pc').textContent=Rm.players.length+'/8';
$('#plist').innerHTML=Rm.players.map(p=>`<div class="row"><span class="av ${p.team||''}">${p.photo?`<img src="${esc(p.photo)}">`:esc((p.name||'?')[0])}</span><b>${esc(p.name)}${p.id===Rm.host?' 👑':''}${p.id===me?' (أنت)':''}</b><em class="chip ${p.team||''}">${p.team?TN[p.team]:'—'}</em></div>`).join('');
const mine=(Rm.players.find(p=>p.id===me)||{}).team,cnt=t=>Rm.players.filter(p=>p.team===t).length;
show('#teams',Rm.mode==='manual'?1:0);$('#tH').classList.toggle('on',mine==='H');$('#tV').classList.toggle('on',mine==='V');$('#cH').textContent=cnt('H')+' لاعب';$('#cV').textContent=cnt('V')+' لاعب';
show('#hostctl',host?1:0);show('#wait',host?0:1);$('#mm').classList.toggle('on',Rm.mode==='manual');$('#mr').classList.toggle('on',Rm.mode==='random');[0,1,2].forEach(i=>$('#m'+i).classList.toggle('on',Rm.map===i))}
document.addEventListener('click',e=>{const b=e.target.closest('[data-a]');if(!b)return;const[a,v]=b.dataset.a.split(':');ac();
switch(a){
case'create':send({t:'join',init:initD(),create:1,guest:qs.get('guest')||''});break;
case'join':joinRoom(($('#jin').value||'').trim().toUpperCase());break;
case'leave':send({t:'leave'});joined=false;Rm=null;endGame();history.replaceState(null,'',location.pathname);showScr('menu');break;
case'team':send({t:'team',team:v});break;case'mode':send({t:'mode',m:v});break;case'map':send({t:'map',m:+v});break;case'start':send({t:'start'});break;
case'snd':cfg.snd=v===undefined?(cfg.snd?0:1):+v;saveCfg();setSnd();break;
case'settings':openSet();break;case'closeset':show('#set',0);break;
case'shop':shopOpen?closeShop():openShop();break;case'closeshop':closeShop();break;
case'joy':cfg.joy=v;saveCfg();applyCfg();break;case'side':cfg.side=v;saveCfg();applyCfg();break;
case'edit':startEdit();break;case'editdone':endEdit();openSet();break;
case'resetlay':cfg.pos={};saveCfg();applyCfg();break;
case'share':if(Rm){const u='https://t.me/share/url?url='+encodeURIComponent(Rm.link)+'&text='+encodeURIComponent('تعال العب CALL OF DUSY معي! كود الغرفة '+Rm.code);TG?TG.openTelegramLink(u):window.open(u)}break;
case'copy':if(Rm){try{navigator.clipboard.writeText(Rm.link);note('تم نسخ الرابط')}catch(_){note(Rm.link)}}break}});
$('#jin').addEventListener('keydown',e=>{if(e.key==='Enter')joinRoom(($('#jin').value||'').trim().toUpperCase())});
applyCfg();updInv();updKD();showScr('menu');
/* ---------- three.js setup ---------- */
const renderer=new THREE.WebGLRenderer({canvas:$('#cv'),antialias:!touch}),scene=new THREE.Scene(),cam=new THREE.PerspectiveCamera(75,1,.1,600);cam.rotation.order='YXZ';scene.add(cam);
renderer.autoClear=false;
const hemi=new THREE.HemisphereLight(0xffffff,0x556677,.9),sun=new THREE.DirectionalLight(0xffffff,.7);scene.add(hemi,sun);
const wScene=new THREE.Scene(),wCam=new THREE.PerspectiveCamera(58,1,.02,10),wHemi=new THREE.HemisphereLight(0xffffff,0x555566,.85),wSun=new THREE.DirectionalLight(0xffffff,1);wSun.position.set(1,1.6,1.2);wScene.add(wHemi,wSun);
let baseFov=75;function fit(){renderer.setPixelRatio(Math.min(devicePixelRatio||1,1.6));renderer.setSize(innerWidth,innerHeight,false);cam.aspect=wCam.aspect=innerWidth/innerHeight;baseFov=cam.aspect<1?92:75;cam.updateProjectionMatrix();wCam.updateProjectionMatrix()}addEventListener('resize',fit);fit();
const mkL=c=>new THREE.MeshLambertMaterial({color:c});
/* ---------- procedural textures ---------- */
const TC={};
function tex(name){if(TC[name])return TC[name];const S=256,c=document.createElement('canvas');c.width=c.height=S;const x=c.getContext('2d'),rnd=(a,b)=>a+Math.random()*(b-a);
const fill=col=>{x.fillStyle=col;x.fillRect(0,0,S,S)},speck=(n,cols,s0,s1)=>{for(let i=0;i<n;i++){x.fillStyle=cols[i%cols.length];x.globalAlpha=rnd(.08,.32);const s=rnd(s0,s1);x.fillRect(rnd(0,S),rnd(0,S),s,s)}x.globalAlpha=1};
const line=(a,b,c2,d,col,w)=>{x.strokeStyle=col;x.lineWidth=w;x.beginPath();x.moveTo(a,b);x.lineTo(c2,d);x.stroke()};
switch(name){
case'sand':fill('#c79a5c');speck(2800,['#e0b573','#a97b45','#d6a867'],1,4);x.strokeStyle='rgba(120,80,40,.13)';x.lineWidth=2;for(let i=0;i<14;i++){x.beginPath();x.moveTo(0,i*19+rnd(-4,4));for(let u=0;u<=S;u+=32)x.lineTo(u,i*19+rnd(-5,5));x.stroke()}break;
case'sandstone':fill('#b58a5a');for(let r=0;r<8;r++){const off=(r%2)*32;for(let u=-off;u<S;u+=64){x.fillStyle=['#b98e5e','#a8804f','#c49a68','#b08556'][(r*3+(u>>6)+4)%4];x.fillRect(u+1,r*32+1,62,30)}}speck(1000,['#8a6338','#d9b585'],1,3);for(let r=0;r<=8;r++)line(0,r*32,S,r*32,'rgba(60,35,15,.5)',2);for(let r=0;r<8;r++){const off=(r%2)*32;for(let u=-off;u<=S;u+=64)line(u,r*32,u,r*32+32,'rgba(60,35,15,.5)',2)}break;
case'woodcrate':fill('#8b5a2b');for(let i=0;i<5;i++){x.fillStyle=i%2?'#94622f':'#80502a';x.fillRect(0,i*51,S,49);line(0,i*51+50,S,i*51+50,'#3d2410',2)}speck(800,['#5c3a18','#b0803f'],1,3);x.strokeStyle='#4a2d12';x.lineWidth=16;x.strokeRect(8,8,S-16,S-16);line(14,14,S-14,S-14,'#5b3a18',14);line(S-14,14,14,S-14,'#5b3a18',14);x.fillStyle='#caa46a';for(const[a,b]of[[22,22],[S-22,22],[22,S-22],[S-22,S-22]]){x.beginPath();x.arc(a,b,4,0,7);x.fill()}break;
case'snow':fill('#e9f0f7');speck(3200,['#ffffff','#c9d8e8','#d9e6f2'],1,3);break;
case'panel':fill('#7d8fa3');for(let a=0;a<2;a++)for(let b=0;b<2;b++){x.fillStyle=(a+b)%2?'#8799ad':'#74879b';x.fillRect(a*128+3,b*128+3,122,122);x.fillStyle='#4b5a6b';for(const[u,v]of[[12,12],[116,12],[12,116],[116,116]]){x.beginPath();x.arc(a*128+u,b*128+v,3.5,0,7);x.fill()}}for(let i=0;i<=2;i++){line(i*128,0,i*128,S,'#38465a',4);line(0,i*128,S,i*128,'#38465a',4)}x.fillStyle='#e6b21f';for(let i=0;i<8;i++){x.beginPath();x.moveTo(i*32,S-18);x.lineTo(i*32+16,S-18);x.lineTo(i*32+8,S-4);x.lineTo(i*32-8,S-4);x.fill()}speck(900,['#5a6a7c','#a9b9c9'],1,3);break;
case'icecrate':fill('#5b86b0');speck(900,['#a9d4ff','#3f6a96'],1,3);x.strokeStyle='#cfe6ff';x.lineWidth=16;x.strokeRect(8,8,S-16,S-16);line(14,14,S-14,S-14,'#8fb8e0',12);line(S-14,14,14,S-14,'#8fb8e0',12);x.fillStyle='#fff';for(const[a,b]of[[22,22],[S-22,22],[22,S-22],[S-22,S-22]]){x.beginPath();x.arc(a,b,4,0,7);x.fill()}break;
case'asphalt':fill('#2c2c36');speck(3500,['#3b3b48','#1f1f27','#4a4a58'],1,3);for(let i=0;i<4;i++){x.strokeStyle='rgba(0,0,0,.45)';x.lineWidth=1.5;x.beginPath();let px=rnd(0,S),py=rnd(0,S);x.moveTo(px,py);for(let k=0;k<6;k++){px+=rnd(-22,22);py+=rnd(-22,22);x.lineTo(px,py)}x.stroke()}break;
case'concrete':fill('#6b6a7a');speck(2600,['#7c7b8c','#585768','#8a8a99'],1,4);for(let i=0;i<=2;i++){line(i*128,0,i*128,S,'rgba(20,18,35,.55)',3);line(0,i*128,S,i*128,'rgba(20,18,35,.55)',3)}x.fillStyle='rgba(0,0,0,.12)';for(let i=0;i<5;i++)x.fillRect(rnd(0,S),rnd(0,S),rnd(6,18),rnd(30,90));break;
case'container':case'container2':{const c1=name==='container'?['#a63d40','#bd4a4d','#6e2224']:['#2f6b9a','#3f80b3','#1d4566'];fill(c1[0]);for(let u=0;u<S;u+=16){x.fillStyle=c1[1];x.fillRect(u,0,7,S);x.fillStyle='rgba(0,0,0,.25)';x.fillRect(u+9,0,3,S)}x.strokeStyle=c1[2];x.lineWidth=14;x.strokeRect(7,7,S-14,S-14);speck(700,['#000','#fff'],1,3);break}
case'win':fill('#0e0d22');for(let a=0;a<8;a++)for(let b=0;b<8;b++){const r=Math.random();x.fillStyle=r<.38?['#ffd27a','#8fe9ff','#ff9ad5','#fff1b8'][(Math.random()*4)|0]:'#1b1838';x.fillRect(a*32+6,b*32+6,20,20)}break}
const t=new THREE.CanvasTexture(c);t.wrapS=t.wrapT=THREE.RepeatWrapping;t.anisotropy=4;return TC[name]=t}
const MC={};function matFor(n,v){const k=n+v;return MC[k]||(MC[k]=new THREE.MeshLambertMaterial({map:tex(n),color:[0xffffff,0xe8e0d6,0xd6cec6][v]}))}
function boxG(w,h,d,t){const g=new THREE.BoxGeometry(w,h,d),uv=g.attributes.uv,D=[[d,h],[d,h],[w,d],[w,d],[w,h],[w,h]];for(let f=0;f<6;f++)for(let i=0;i<4;i++){const k=f*4+i;uv.setXY(k,uv.getX(k)*D[f][0]/t,uv.getY(k)*D[f][1]/t)}return g}
/* ---------- maps / sky / decor ---------- */
const MAPS=[
{sky:['#24226b','#a74e84','#ff9d58','#ffcf8a'],fog:0xdf9764,fd:[22,120],hemi:[0xffd9b0,0x7a5a3a,.95],sun:[0xffc27a,1,[-30,40,-40]],gr:'sand',og:0x9a6a40,wall:'sandstone',block:'sandstone',crate:['woodcrate'],orb:{c:'#ffb266',d:[-.55,.13,-.82],s:90,core:.2},stars:.3,fx:{c:0xf0c890,s:.12,v:[1.6,-.15,.6],o:.55,n:260}},
{sky:['#16254f','#5a72ae','#c9b6d6','#e9dfe9'],fog:0xaeb8d8,fd:[20,110],hemi:[0xdbe8ff,0x8095b5,1.05],sun:[0xe6eeff,.75,[25,45,15]],gr:'snow',og:0xcfd8e8,wall:'panel',block:'panel',crate:['icecrate','panel'],orb:{c:'#f0f4ff',d:[.4,.5,-.8],s:44,core:.3},stars:1,fx:{c:0xffffff,s:.14,v:[.6,-2.2,.3],o:.9,n:520}},
{sky:['#050512','#17104a','#6a2a78','#c4506a'],fog:0x2d1d4f,fd:[18,125],hemi:[0x7f7ee0,0x251f3f,.9],sun:[0xa8b6ff,.6,[-20,40,20]],gr:'asphalt',og:0x1b1a2b,wall:'concrete',block:'concrete',crate:['container','container2'],orb:{c:'#f4f0ff',d:[-.3,.45,-.85],s:40,core:.28},stars:1,fx:{c:0xffa066,s:.1,v:[.2,.5,.2],o:.85,n:240}}];
let world=new THREE.Group(),skyG=new THREE.Group(),parts=null,partCfg=null;scene.add(world,skyG);
const _gt={};function glowTex(col,core){const k=col+core;return _gt[k]||(_gt[k]=glowTex0(col,core))}function glowTex0(col,core){const c=document.createElement('canvas');c.width=c.height=128;const x=c.getContext('2d'),g=x.createRadialGradient(64,64,0,64,64,64);g.addColorStop(0,col);g.addColorStop(core,col);g.addColorStop(core+.04,col+'66');g.addColorStop(1,'rgba(0,0,0,0)');x.fillStyle=g;x.fillRect(0,0,128,128);return new THREE.CanvasTexture(c)}
function buildSky(C){scene.remove(skyG);skyG.traverse(o=>{if(o.geometry)o.geometry.dispose();if(o.material){if(o.material.map)o.material.map.dispose();o.material.dispose()}});skyG=new THREE.Group();
const c=document.createElement('canvas');c.width=4;c.height=256;const x=c.getContext('2d'),g=x.createLinearGradient(0,0,0,256),fh='#'+C.fog.toString(16).padStart(6,'0');
g.addColorStop(0,C.sky[0]);g.addColorStop(.28,C.sky[1]);g.addColorStop(.44,C.sky[2]);g.addColorStop(.5,C.sky[3]);g.addColorStop(.505,fh);g.addColorStop(1,fh);x.fillStyle=g;x.fillRect(0,0,4,256);
const dome=new THREE.Mesh(new THREE.SphereGeometry(300,24,16),new THREE.MeshBasicMaterial({map:new THREE.CanvasTexture(c),side:THREE.BackSide,fog:false,depthWrite:false}));dome.renderOrder=-3;skyG.add(dome);
const o=C.orb,d=new THREE.Vector3(...o.d).normalize().multiplyScalar(280),sp=new THREE.Sprite(new THREE.SpriteMaterial({map:glowTex(o.c,o.core),transparent:true,fog:false,depthWrite:false}));sp.scale.set(o.s*2.4,o.s*2.4,1);sp.position.copy(d);sp.renderOrder=-2;skyG.add(sp);
const n=Math.floor(450*C.stars),pos=new Float32Array(n*3);for(let i=0;i<n;i++){const a=Math.random()*6.283,y=.06+Math.random()*.94,r=Math.sqrt(1-y*y)*285;pos[i*3]=Math.cos(a)*r;pos[i*3+1]=y*285;pos[i*3+2]=Math.sin(a)*r}
const sg=new THREE.BufferGeometry();sg.setAttribute('position',new THREE.BufferAttribute(pos,3));const st=new THREE.Points(sg,new THREE.PointsMaterial({color:0xffffff,size:1.7,sizeAttenuation:false,fog:false,transparent:true,opacity:.85,depthWrite:false}));st.renderOrder=-2;skyG.add(st);scene.add(skyG)}
function mkParts(C){if(parts){scene.remove(parts);parts.geometry.dispose()}const f=C.fx,pos=new Float32Array(f.n*3);for(let k=0;k<f.n;k++){pos[k*3]=Math.random()*60-30;pos[k*3+1]=Math.random()*22;pos[k*3+2]=Math.random()*60-30}
const g=new THREE.BufferGeometry();g.setAttribute('position',new THREE.BufferAttribute(pos,3));parts=new THREE.Points(g,new THREE.PointsMaterial({color:f.c,size:f.s,transparent:true,opacity:f.o,depthWrite:false}));parts.frustumCulled=false;partCfg=f;scene.add(parts)}
function updParts(dt){if(!parts)return;const a=parts.geometry.attributes.position,v=partCfg.v,cx=cam.position.x,cz=cam.position.z;for(let k=0;k<a.count;k++){let x=a.getX(k)+v[0]*dt,y=a.getY(k)+v[1]*dt,z=a.getZ(k)+v[2]*dt;if(x>cx+30)x-=60;else if(x<cx-30)x+=60;if(z>cz+30)z-=60;else if(z<cz-30)z+=60;if(y<0)y+=22;else if(y>22)y-=22;a.setXYZ(k,x,y,z)}a.needsUpdate=true}
function pine(x,z,s){const g=new THREE.Group();const tr=new THREE.Mesh(new THREE.CylinderGeometry(.35*s,.5*s,3*s,6),mkL(0x4a3426));tr.position.y=1.5*s;g.add(tr);for(let i=0;i<4;i++){const c=new THREE.Mesh(new THREE.ConeGeometry((3.6-i*.7)*s,(3.6-i*.3)*s,8),mkL(i%2?0x2d5a45:0x244c3a));c.position.y=(3+i*2.1)*s;g.add(c);const sn=new THREE.Mesh(new THREE.ConeGeometry((2.6-i*.6)*s,1.4*s,8),mkL(0xf2f6fb));sn.position.y=(4.1+i*2.1)*s;g.add(sn)}g.position.set(x,0,z);return g}
function buildWorld(i){scene.remove(world);world.traverse(o=>{if(o.geometry)o.geometry.dispose()});world=new THREE.Group();scene.add(world);const C=MAPS[i],rnd=(a,b)=>a+Math.random()*(b-a);
scene.background=new THREE.Color(C.fog);scene.fog=new THREE.Fog(C.fog,C.fd[0],C.fd[1]);
for(const[h,s,w]of[[hemi,sun,0],[wHemi,wSun,1]]){h.color.setHex(C.hemi[0]);h.groundColor.setHex(C.hemi[1]);h.intensity=w?C.hemi[2]*.85:C.hemi[2];s.color.setHex(C.sun[0]);s.intensity=w?1:C.sun[1]}sun.position.set(...C.sun[2]);
buildSky(C);mkParts(C);
const gt=tex(C.gr);gt.repeat.set(20,20);const g=new THREE.Mesh(new THREE.PlaneGeometry(80,80),new THREE.MeshLambertMaterial({map:gt}));g.rotation.x=-Math.PI/2;world.add(g);
const og=new THREE.Mesh(new THREE.PlaneGeometry(900,900),mkL(C.og));og.rotation.x=-Math.PI/2;og.position.y=-.03;world.add(og);
boxes.forEach((b,k)=>{const[x,y0,z,w,h,d]=b,crate=w<=4.5&&Math.abs(w-d)<=.7&&h<=2.2&&w>=1.9,n=crate?C.crate[k%C.crate.length]:(h>=6?C.wall:C.block),m=new THREE.Mesh(boxG(w,h,d,crate?2:3),matFor(n,k%3));m.position.set(x,y0+h/2,z);world.add(m)});
if(i===0){for(let k=0;k<16;k++){const a=k/16*6.283+rnd(0,.3),r=rnd(85,125),m=new THREE.Mesh(new THREE.SphereGeometry(1,14,8),mkL(0xb7824a));m.scale.set(rnd(28,60),rnd(7,16),rnd(28,55));m.position.set(Math.cos(a)*r,-2,Math.sin(a)*r);world.add(m)}
for(let k=0;k<8;k++){const a=rnd(0,6.283),r=rnd(78,105),w=rnd(10,18),h=rnd(14,28),m=new THREE.Mesh(new THREE.BoxGeometry(w,h,w*rnd(.6,1.1)),matFor('sandstone',1));m.position.set(Math.cos(a)*r,h/2-1,Math.sin(a)*r);m.rotation.y=rnd(0,3);world.add(m)}}
else if(i===1){for(let k=0;k<12;k++){const a=k/12*6.283+rnd(0,.3),r=rnd(110,150),R=rnd(26,44),H=rnd(40,70),m=new THREE.Mesh(new THREE.ConeGeometry(R,H,7),mkL(0x7f8da6)),cap=new THREE.Mesh(new THREE.ConeGeometry(R*.42,H*.42,7),mkL(0xf4f7fb));m.position.set(Math.cos(a)*r,H/2-2,Math.sin(a)*r);cap.position.set(m.position.x,H*.79-2,m.position.z);world.add(m,cap)}
for(let k=0;k<46;k++){const a=rnd(0,6.283),r=rnd(42,75);world.add(pine(Math.cos(a)*r,Math.sin(a)*r,rnd(.9,1.6)))}}
else{const wm=[];for(let k=0;k<4;k++){const t=tex('win').clone();t.needsUpdate=true;wm.push(new THREE.MeshLambertMaterial({map:t,emissive:0xffffff,emissiveMap:t}))}
const tall=[];for(let k=0;k<48;k++){const a=k/48*6.283+rnd(-.05,.05),r=rnd(52,100),w=rnd(8,18),d=rnd(8,18),h=rnd(18,75),m=new THREE.Mesh(boxG(w,h,d,8),wm[k%4]);m.position.set(Math.cos(a)*r,h/2-1,Math.sin(a)*r);m.rotation.y=rnd(-.2,.2);world.add(m);if(h>58)tall.push([m.position.x,h,m.position.z])}
const bm=new THREE.MeshBasicMaterial({color:0xff3344});tall.forEach(([x,h,z])=>{const s=new THREE.Mesh(new THREE.SphereGeometry(.8,6,6),bm);s.position.set(x,h-.4,z);world.add(s)})}}
/* ---------- weapon models ---------- */
const PH=(c,s,sh)=>new THREE.MeshPhongMaterial({color:c,specular:s==null?0x333333:s,shininess:sh||30});
const B3=(w,h,d)=>new THREE.BoxGeometry(w,h,d),cyl=(r1,r2,l,sg)=>{const g=new THREE.CylinderGeometry(r1,r2,l,sg||12);g.rotateX(Math.PI/2);return g};
function mk(g,geo,mat,x,y,z){const m=new THREE.Mesh(geo,mat);m.position.set(x||0,y||0,z||0);g.add(m);return m}
function limb(g,a,b,w,mat){const d=new THREE.Vector3(...b).sub(new THREE.Vector3(...a)),l=d.length(),m=new THREE.Mesh(B3(w,w,l),mat);m.position.set((a[0]+b[0])/2,(a[1]+b[1])/2,(a[2]+b[2])/2);m.quaternion.setFromUnitVectors(new THREE.Vector3(0,0,1),d.normalize());g.add(m);return m}
const sleeveM=PH(0x1e5a55,0x111111,10),gloveM=PH(0x15161a,0x444444,25);
function makeKnife(fp){const g=new THREE.Group(),steel=PH(0xd8dfe6,0xffffff,140),dark=PH(0x1b1d22,0x555555,30),rub=PH(0x2a2d33,0x222222,10);
const sh=new THREE.Shape();sh.moveTo(0,.03);sh.lineTo(.2,.03);sh.quadraticCurveTo(.285,.03,.32,-.012);sh.quadraticCurveTo(.26,-.046,.19,-.04);sh.lineTo(0,-.032);sh.lineTo(0,.03);
const bg=new THREE.ExtrudeGeometry(sh,{depth:.009,bevelEnabled:false});bg.translate(0,0,-.0045);bg.rotateY(Math.PI/2);mk(g,bg,steel);
mk(g,B3(.0105,.009,.2),PH(0x8f99a3,0xffffff,60),0,.014,-.1); // fuller groove
mk(g,B3(.0105,.006,.17),PH(0xffffff,0xffffff,200),0,-.034,-.1); // sharpened edge highlight
mk(g,B3(.022,.09,.016),dark,0,0,.004);
mk(g,cyl(.017,.019,.135,10),rub,0,0,.0725);
for(let i=0;i<5;i++)mk(g,cyl(.0205,.0205,.006,10),dark,0,0,.025+i*.024);
mk(g,new THREE.SphereGeometry(.022,10,8),steel,0,0,.142);
if(fp){mk(g,B3(.074,.07,.1),gloveM,0,-.008,.075);mk(g,B3(.068,.022,.09),gloveM,0,.034,.075);mk(g,B3(.026,.026,.06),gloveM,-.038,.016,.03);limb(g,[0,-.015,.12],[.07,-.17,.7],.085,sleeveM)}
return g}
function makeSniper(fp){const g=new THREE.Group(),gm=PH(0x2a2e35,0x777b83,70),gm2=PH(0x1a1c21,0x444444,35),olive=PH(0x3b4636,0x222222,15),glass=new THREE.MeshPhongMaterial({color:0x3a7bd5,emissive:0x0a2a55,specular:0xffffff,shininess:160,transparent:true,opacity:.88});
mk(g,B3(.062,.085,.42),gm,0,0,-.02);mk(g,B3(.03,.012,.4),gm2,0,.048,-.02);
mk(g,cyl(.027,.027,.3,10),gm2,0,-.004,-.36);mk(g,cyl(.0135,.0135,.62,10),gm,0,0,-.66);
mk(g,cyl(.022,.022,.09,8),gm2,0,0,-.955);for(let i=0;i<3;i++)mk(g,B3(.056,.012,.01),gm,0,0,-.93-i*.024);
const st=mk(g,B3(.052,.095,.3),olive,0,-.012,.39);st.rotation.x=.05;mk(g,B3(.05,.04,.16),olive,0,.062,.34);mk(g,B3(.056,.115,.025),PH(0x15161a),0,-.016,.545);
const gr=mk(g,B3(.038,.1,.05),gm2,0,-.085,.17);gr.rotation.x=-.35;mk(g,B3(.034,.09,.075),gm2,0,-.082,-.06);
const tg=mk(g,new THREE.TorusGeometry(.03,.004,6,12),gm2,0,-.062,.05);tg.geometry.rotateY(Math.PI/2);
mk(g,cyl(.027,.027,.3,14),gm,0,.098,-.06);mk(g,cyl(.027,.042,.09,14),gm,0,.098,-.255);mk(g,cyl(.036,.027,.06,14),gm,0,.098,.125);
const ln=mk(g,new THREE.CircleGeometry(.038,16),glass,0,.098,-.3015);ln.rotation.y=Math.PI;
mk(g,new THREE.CylinderGeometry(.01,.01,.025,8),gm2,0,.128,-.06);const tr=mk(g,new THREE.CylinderGeometry(.01,.01,.025,8),gm2,.034,.098,-.06);tr.rotation.z=Math.PI/2;
mk(g,B3(.03,.04,.03),gm2,0,.07,-.15);mk(g,B3(.03,.04,.03),gm2,0,.07,.03);
const bolt=new THREE.Group();bolt.position.set(.045,.014,.04);const bh=new THREE.CylinderGeometry(.006,.006,.07,6);bh.rotateZ(Math.PI/2);mk(bolt,bh,gm,.035,0,0);mk(bolt,new THREE.SphereGeometry(.014,8,6),gm2,.073,0,0);g.add(bolt);
for(const s of[-1,1]){const l=mk(g,new THREE.CylinderGeometry(.005,.005,.14,5),gm2,s*.03,-.04,-.5);l.rotation.x=1.45;l.rotation.z=s*.12}
const flash=new THREE.Group();flash.position.z=-1.02;flash.visible=false;const fm=new THREE.MeshBasicMaterial({map:glowTex('#ffd27a',.1),transparent:true,blending:THREE.AdditiveBlending,depthWrite:false,side:THREE.DoubleSide});mk(flash,new THREE.PlaneGeometry(.34,.34),fm);const f2=mk(flash,new THREE.PlaneGeometry(.34,.34),fm);f2.rotation.y=Math.PI/2;g.add(flash);
if(fp){mk(g,B3(.07,.075,.09),gloveM,.002,-.1,.17);limb(g,[.005,-.1,.2],[.12,-.3,.75],.085,sleeveM);mk(g,B3(.08,.06,.1),gloveM,-.002,-.05,-.36);limb(g,[-.002,-.06,-.32],[-.2,-.34,.25],.085,sleeveM)}
g.userData={bolt,flash};return g}
/* ---------- characters ---------- */
const skins=[0xf1c9a5,0xe0ac82,0xc68863,0x9a6a47,0x6f4a30],hairs=[0x1a1410,0x3a2616,0x6b4a2a,0x151515,0x8a8a8a],hex6=n=>'#'+n.toString(16).padStart(6,'0');
function hash(s){let h=0;for(const c of String(s))h=(h*31+c.charCodeAt(0))>>>0;return h}
const faceC={};
function faceTex(h){const k=h%15;if(faceC[k])return faceC[k];const si=k%5,hi=(k>>1)%5,beard=k%3===0,c=document.createElement('canvas');c.width=c.height=64;const x=c.getContext('2d'),sk=hex6(skins[si]),hr=hex6(hairs[hi]);
x.fillStyle=sk;x.fillRect(0,0,64,64);x.fillStyle='rgba(0,0,0,.08)';x.fillRect(0,50,64,14);
x.fillStyle=hr;x.fillRect(0,0,64,11);x.fillRect(0,0,5,24);x.fillRect(59,0,5,24);x.fillRect(11,19,16,3);x.fillRect(37,19,16,3);
x.fillStyle='#fff';x.fillRect(12,25,14,8);x.fillRect(38,25,14,8);x.fillStyle='#3a2414';x.fillRect(16,25,7,8);x.fillRect(42,25,7,8);x.fillStyle='#000';x.fillRect(18,26,3,6);x.fillRect(44,26,3,6);x.fillStyle='rgba(255,255,255,.9)';x.fillRect(19,26,1,1);x.fillRect(45,26,1,1);
x.fillStyle='rgba(0,0,0,.2)';x.fillRect(29,31,6,11);x.fillRect(26,40,12,3);
if(beard){x.fillStyle=hr;x.fillRect(7,40,50,24);x.fillRect(5,28,4,16);x.fillRect(55,28,4,16);x.fillStyle=sk;x.fillRect(23,47,18,6);x.fillStyle='#7a2e2e';x.fillRect(25,48,14,2)}else{x.fillStyle='#7a2e2e';x.fillRect(24,48,16,3);x.fillStyle='rgba(0,0,0,.14)';x.fillRect(22,46,2,5);x.fillRect(40,46,2,5)}
const t=new THREE.CanvasTexture(c);t.magFilter=THREE.NearestFilter;return faceC[k]=t}
const bxm=(par,w,h,d,mat,x,y,z)=>{const m=new THREE.Mesh(B3(w,h,d),mat);m.position.set(x,y,z);par.add(m);return m};
function makeM4(fp){const g=new THREE.Group(),gm=PH(0x23262b,0x666a72,60),gm2=PH(0x15171b,0x3a3a3a,30),glass=new THREE.MeshPhongMaterial({color:0xff2a2a,emissive:0xff1010,transparent:true,opacity:.7});
mk(g,B3(.052,.07,.3),gm,0,0,-.03);mk(g,B3(.05,.055,.2),gm2,0,-.058,.02);mk(g,B3(.026,.012,.5),gm2,0,.042,-.06);
mk(g,cyl(.029,.029,.28,10),gm2,0,0,-.33);mk(g,cyl(.0095,.0095,.16,8),gm,0,0,-.52);mk(g,cyl(.014,.014,.07,8),gm2,0,0,-.62);mk(g,B3(.009,.04,.009),gm2,0,.06,-.47);
mk(g,B3(.036,.05,.07),gm2,0,.068,.02);mk(g,new THREE.CircleGeometry(.014,10),glass,0,.07,.0565);mk(g,B3(.03,.02,.04),gm,0,.04,.14);
const mg=mk(g,B3(.034,.12,.056),gm2,0,-.13,-.025);mg.rotation.x=.18;const gr=mk(g,B3(.036,.1,.046),gm2,0,-.11,.1);gr.rotation.x=-.3;
mk(g,cyl(.017,.017,.15,8),gm,0,-.002,.19);mk(g,B3(.05,.09,.13),gm2,0,-.012,.3);mk(g,B3(.052,.1,.02),PH(0x111114),0,-.012,.37);
const flash=new THREE.Group();flash.position.z=-.68;flash.visible=false;const fm=new THREE.MeshBasicMaterial({map:glowTex('#ffd27a',.1),transparent:true,blending:THREE.AdditiveBlending,depthWrite:false,side:THREE.DoubleSide});mk(flash,new THREE.PlaneGeometry(.26,.26),fm);const f2=mk(flash,new THREE.PlaneGeometry(.26,.26),fm);f2.rotation.y=Math.PI/2;g.add(flash);
if(fp){mk(g,B3(.07,.075,.09),gloveM,0,-.12,.1);limb(g,[0,-.13,.12],[.12,-.34,.65],.085,sleeveM);mk(g,B3(.08,.06,.1),gloveM,0,-.045,-.3);limb(g,[0,-.06,-.28],[-.2,-.34,.3],.085,sleeveM)}
g.userData={flash,bolt:null};return g}
function makePKC(fp){const g=new THREE.Group(),gm=PH(0x2a2d31,0x666a72,55),gm2=PH(0x17181c,0x3a3a3a,30),wood=PH(0x5a3b22,0x2a1a0c,14),brass=PH(0xc9a640,0xffe9a0,80);
mk(g,B3(.07,.09,.5),gm,0,0,0);mk(g,B3(.058,.03,.34),gm2,0,.06,-.02);mk(g,B3(.02,.04,.2),gm2,0,.095,0);mk(g,B3(.12,.1,.13),gm2,0,-.095,-.02);
for(let i=0;i<4;i++)mk(g,B3(.04,.022,.02),brass,0,-.05+i*.02,-.06);
mk(g,cyl(.027,.027,.24,10),gm2,0,-.002,-.38);mk(g,cyl(.016,.016,.5,10),gm,0,0,-.62);mk(g,cyl(.022,.022,.08,8),gm2,0,0,-.9);mk(g,B3(.012,.045,.012),gm2,0,.05,-.8);
mk(g,B3(.055,.11,.34),wood,0,-.02,.43);mk(g,B3(.058,.12,.022),PH(0x111114),0,-.02,.61);const gr=mk(g,B3(.04,.11,.05),wood,0,-.1,.2);gr.rotation.x=-.3;
for(const s of[-1,1]){const l=mk(g,new THREE.CylinderGeometry(.005,.005,.15,5),gm2,s*.035,-.05,-.58);l.rotation.x=1.45;l.rotation.z=s*.1}
const flash=new THREE.Group();flash.position.z=-.97;flash.visible=false;const fm=new THREE.MeshBasicMaterial({map:glowTex('#ffd27a',.1),transparent:true,blending:THREE.AdditiveBlending,depthWrite:false,side:THREE.DoubleSide});mk(flash,new THREE.PlaneGeometry(.34,.34),fm);const f2=mk(flash,new THREE.PlaneGeometry(.34,.34),fm);f2.rotation.y=Math.PI/2;g.add(flash);
if(fp){mk(g,B3(.07,.075,.09),gloveM,0,-.12,.2);limb(g,[0,-.13,.22],[.12,-.34,.75],.085,sleeveM);mk(g,B3(.08,.06,.1),gloveM,0,-.045,-.38);limb(g,[0,-.06,-.34],[-.2,-.34,.25],.085,sleeveM)}
g.userData={flash,bolt:null};return g}
/* first-person rigs (separate scene, drawn over the world) */
const rigs={};
function mkRig(id,model,base,rot,sc){const r=new THREE.Group();model.rotation.set(rot[0],rot[1],rot[2]);model.scale.setScalar(sc||1);r.add(model);r.visible=false;wScene.add(r);rigs[id]={r,base,flash:model.userData.flash,bolt:model.userData.bolt,bz:model.userData.bolt?model.userData.bolt.position.z:0}}
mkRig('k',makeKnife(true),{x:.2,y:-.23,z:-.42},[.45,.4,-.25]);mkRig('s',makeSniper(true),{x:.17,y:-.2,z:-.3},[0,0,0]);
mkRig('m4',makeM4(true),{x:.15,y:-.19,z:-.3},[0,.03,0]);mkRig('pkc',makePKC(true),{x:.15,y:-.2,z:-.3},[0,.03,0],.85);
let swapT=1,slashT=-1,fireT=-1,boltOk=true,bobT=0,kick=0,flashT=0,shake=0;
function wAnim(dt){swapT=Math.min(1,swapT+dt*3.2);const ax=Math.min(1,cam.aspect/1.25),e=1-Math.pow(1-swapT,3),amp=.3+mv*1.2;bobT+=dt*(5+mv*7);const bx=Math.sin(bobT)*.006*amp,by=Math.abs(Math.cos(bobT))*.006*amp;
kick=Math.max(0,kick-dt*12);if(flashT>0)flashT-=dt;let sl=0;if(slashT>=0){slashT+=dt/.34;if(slashT>=1)slashT=-1;else sl=Math.sin(slashT*Math.PI)}
let r=0;if(fireT>=0){fireT+=dt;r=Math.exp(-fireT*13);if(fireT>1.1)fireT=-1}
for(const id in rigs){const R=rigs[id];if(!R.r.visible)continue;let px=R.base.x*ax+bx,py=R.base.y+by-(1-e)*.45,pz=R.base.z,rx=0,ry=0,rz=0;
if(id==='k'){px-=sl*.3;py+=sl*.05;pz-=sl*.2;rx=sl*.55;ry=sl*1.2;rz=-sl*1.1}
else if(id==='s'){pz+=r*.1;rx=r*.12;R.flash.visible=fireT>=0&&fireT<.07;R.flash.rotation.z=Math.random()*6;
if(fireT>.45&&fireT<1){const q=(fireT-.45)/.55;if(!boltOk){boltOk=true;snd('bolt')}R.bolt.position.z=R.bz+Math.sin(q*Math.PI)*.06;R.bolt.rotation.z=-Math.sin(Math.min(1,q*1.1)*Math.PI)}else{R.bolt.position.z=R.bz;R.bolt.rotation.z=0}}
else{pz+=kick*.04;rx=kick*.05;ry=Math.sin(bobT*7)*kick*.01;R.flash.visible=flashT>0;R.flash.rotation.z=Math.random()*6}
R.r.position.set(px,py,pz);R.r.rotation.set(rx,ry,rz)}}
/* ---------- characters ---------- */
const GUNPOS={s:{s:.92,z:.17},m4:{s:1,z:.1},pkc:{s:.8,z:.2}};
function avatar(p){const H=p.team==='H',tc=H?0x2fd6c0:0xff5a6e,td=H?0x146b62:0x8a2332,g=new THREE.Group(),body=new THREE.Group(),hh=hash(p.id||p.name);g.add(body);
const pants=mkL(H?0x2c3a3a:0x3a2c30),shirt=mkL(0x23262d),vest=mkL(td),vest2=mkL(0x1b1d22),glove=mkL(0x111114),boot=mkL(0x15151a),skin=mkL(skins[hh%5]);
const mkLeg=s=>{const pv=new THREE.Group();pv.position.set(s*.16,.88,0);bxm(pv,.24,.82,.28,pants,0,-.41,0);bxm(pv,.26,.16,.36,boot,0,-.8,-.04);bxm(pv,.27,.2,.29,vest2,0,-.3,0);body.add(pv);return pv};
const lL=mkLeg(-1),lR=mkLeg(1);
bxm(body,.6,.64,.34,shirt,0,1.2,0);bxm(body,.66,.5,.4,vest,0,1.26,0);bxm(body,.18,.14,.08,vest2,-.16,1.16,-.22);bxm(body,.18,.14,.08,vest2,.16,1.16,-.22);bxm(body,.1,.1,.05,mkL(tc),.17,1.4,-.21);bxm(body,.64,.08,.38,boot,0,.9,0);bxm(body,.3,.34,.12,vest2,0,1.3,.24);
const hd=new THREE.Group();hd.position.set(0,1.56,0);body.add(hd);bxm(hd,.12,.1,.12,skin,0,.04,0);
const fm=mkL(0xffffff);fm.map=faceTex(hh);const hairM=mkL(hairs[(hh>>1)%5]),head=new THREE.Mesh(B3(.32,.34,.32),[skin,skin,hairM,skin,hairM,fm]);head.position.y=.25;hd.add(head);
if(H){const hl=new THREE.Mesh(new THREE.SphereGeometry(.215,12,8,0,6.283,0,1.571),PH(0x1e8f84,0x88ffee,40));hl.scale.set(1,.95,1.08);hl.position.set(0,.33,0);hd.add(hl);bxm(hd,.34,.04,.3,PH(0x15665f),0,.325,-.02);
bxm(hd,.3,.075,.06,vest2,0,.37,-.19);const lm=new THREE.MeshBasicMaterial({color:0x66ffcc});for(const s of[-1,1])mk(hd,cyl(.032,.032,.07,8),lm,s*.08,.37,-.24)}
else{const cp=new THREE.Mesh(new THREE.SphereGeometry(.2,12,8,0,6.283,0,1.571),mkL(0x8a1f2e));cp.scale.set(1,.8,1.05);cp.position.set(0,.33,0);hd.add(cp);bxm(hd,.3,.03,.16,mkL(0x6a1622),0,.335,-.2);bxm(hd,.36,.12,.36,mkL(tc),0,.03,0)}
const mkArm=s=>{const pv=new THREE.Group();pv.position.set(s*.4,1.46,0);bxm(pv,.16,.6,.16,shirt,0,-.3,0);bxm(pv,.19,.16,.19,vest,0,-.06,0);bxm(pv,.15,.13,.15,glove,0,-.64,0);body.add(pv);return pv};
const aL=mkArm(-1),aR=mkArm(1),W={};
const mkW=id=>{let m;if(id==='k'){m=makeKnife(false);m.scale.setScalar(1.5);m.position.set(0,-.64,0)}else{m=id==='s'?makeSniper(false):id==='m4'?makeM4(false):makePKC(false);const c=GUNPOS[id];m.scale.setScalar(c.s);m.position.set(0,-.64-c.z*c.s,0);m.userData.flash.visible=false}m.rotation.x=-Math.PI/2;aR.add(m);W[id]=m;return m};
const sh=new THREE.Mesh(new THREE.CircleGeometry(.55,16),new THREE.MeshBasicMaterial({color:0,transparent:true,opacity:.35,depthWrite:false}));sh.rotation.x=-Math.PI/2;sh.position.y=.03;g.add(sh);
let tag=null;if(p.team===myTeam){const c=document.createElement('canvas');c.width=256;c.height=64;const x=c.getContext('2d');x.font='bold 30px sans-serif';x.textAlign='center';x.fillStyle=TCOL[p.team];x.strokeStyle='#000';x.lineWidth=6;x.strokeText(p.name,128,42);x.fillText(p.name,128,42);tag=new THREE.Sprite(new THREE.SpriteMaterial({map:new THREE.CanvasTexture(c),depthTest:false,transparent:true}));tag.scale.set(2.2,.55,1);tag.position.y=2.45;tag.renderOrder=5;g.add(tag)}
scene.add(g);return{g,body,hd,lL,lR,aL,aR,W,mkW,tag,team:p.team,ph:0,sp:0,dt:9,alive:false,wp:'k',sa:0,rx:0,pitch:0,buf:[]}}
const INTERP=100;
function animOthers(dt){const rt=performance.now()-INTERP;
for(const k in others){const o=others[k],p=o.g.position,ox=p.x,oz=p.z,bf=o.buf;
while(bf.length>2&&bf[1].t<rt)bf.shift();
if(bf.length){const a=bf[0],b=bf[1];if(!b||rt<=a.t){p.set(a.x,a.y,a.z);o.g.rotation.y=a.yaw}else{const f=Math.min(1,Math.max(0,(rt-a.t)/Math.max(1,b.t-a.t)));p.set(a.x+(b.x-a.x)*f,a.y+(b.y-a.y)*f,a.z+(b.z-a.z)*f);let dy=b.yaw-a.yaw;dy-=Math.round(dy/6.2832)*6.2832;o.g.rotation.y=a.yaw+dy*f}}
if(!o.alive){o.dt+=dt;o.body.rotation.x=Math.min(1,o.dt*3)*1.5;o.g.visible=o.dt<2.2;continue}o.g.visible=true;
const spd=Math.hypot(p.x-ox,p.z-oz)/Math.max(dt,.001);o.sp+=(spd-o.sp)*.2;const m=Math.min(1,o.sp/4)*(o.sa===2?.4:1);o.ph+=dt*(4+o.sp*1.3);const sw=Math.sin(o.ph)*.85*m,gun=o.wp!=='k',up=o.pitch;
if(!o.W[o.wp])o.mkW(o.wp);for(const id in o.W)o.W[id].visible=id===o.wp;
o.lL.rotation.x=sw;o.lR.rotation.x=-sw;
const trx=o.sa===1?.9:o.sa===2?-1.45:0;o.rx+=(trx-o.rx)*Math.min(1,dt*12);o.body.rotation.x=o.rx;o.hd.rotation.x=up*.7-o.rx*.8;o.body.position.y=(o.sa===0?Math.abs(Math.sin(o.ph))*.04*m:(o.sa===1?.12:.05));
if(o.tag)o.tag.position.y=o.sa===2?.95:o.sa===1?1.8:2.45;
o.aR.rotation.set(gun?1.5+up:1.25+up*.8,0,gun?-.1:0);if(gun)o.aL.rotation.set(1.45+up,0,.42);else o.aL.rotation.set(-sw*.8,0,.05)}}
/* ---------- tracers ---------- */
const TRG=new THREE.CylinderGeometry(.02,.02,1,5),tracers=[],V3=(a,b,c)=>new THREE.Vector3(a,b,c);
function tracer(o,dv,mine,w){const auto=w==='m4'||w==='pkc';if(tracers.length>34){const t=tracers.shift();scene.remove(t.m);t.mat.dispose()}
const s=o.clone().addScaledVector(dv,mine?.9:1.2),e=o.clone().addScaledVector(dv,auto?70:95);if(mine){s.x+=Math.cos(P.yaw)*.16;s.z-=Math.sin(P.yaw)*.16;s.y-=.13}
const dir=e.sub(s),len=dir.length();dir.normalize();const mat=new THREE.MeshBasicMaterial({color:auto?0xffd27a:0xffe3a0,transparent:true,opacity:.9,fog:false,depthWrite:false}),m=new THREE.Mesh(TRG,mat);m.scale.set(auto?.6:1,len,auto?.6:1);m.position.copy(s).addScaledVector(dir,len/2);m.quaternion.setFromUnitVectors(V3(0,1,0),dir);scene.add(m);tracers.push({m,mat,t:0,life:auto?.1:.28})}
function updTracers(dt){for(let i=tracers.length-1;i>=0;i--){const t=tracers[i];t.t+=dt;t.mat.opacity=Math.max(0,.9*(1-t.t/t.life));if(t.t>=t.life){scene.remove(t.m);t.mat.dispose();tracers.splice(i,1)}}}
function onShot(m){const mine=m.id===me,o=V3(...m.o),dv=V3(...m.d);tracer(o,dv,mine,m.w);if(!mine)snd(m.w==='s'?'snipe':m.w,Math.max(.08,Math.min(1,1/(1+o.distanceTo(cam.position)*.07))))}
/* ---------- radar ---------- */
const rdr=$('#radar'),rx=rdr.getContext('2d');
function radar(){const S=200,c=S/2,sc=c/32;rx.clearRect(0,0,S,S);rx.save();rx.beginPath();rx.arc(c,c,c-2,0,7);rx.clip();rx.fillStyle='rgba(12,7,28,.68)';rx.fillRect(0,0,S,S);
const cy=Math.cos(P.yaw),sy=Math.sin(P.yaw),tr=(wx,wz)=>{const dx=wx-P.x,dz=wz-P.z;return[c+(dx*cy-dz*sy)*sc,c+(dx*sy+dz*cy)*sc]};
rx.fillStyle='rgba(255,190,120,.3)';rx.strokeStyle='rgba(255,205,150,.7)';rx.lineWidth=2;
for(const[x,y0,z,w,h,d]of boxes){if(Math.abs(x-P.x)>w/2+34||Math.abs(z-P.z)>d/2+34)continue;rx.beginPath();[[x-w/2,z-d/2],[x+w/2,z-d/2],[x+w/2,z+d/2],[x-w/2,z+d/2]].forEach(([a,b],i)=>{const[u,v]=tr(a,b);i?rx.lineTo(u,v):rx.moveTo(u,v)});rx.closePath();rx.fill();rx.stroke()}
for(const f of fires){const[u,v]=tr(f.p[0],f.p[2]);rx.fillStyle='rgba(255,120,30,.5)';rx.beginPath();rx.arc(u,v,3.3*sc,0,7);rx.fill()}
for(const s of smokes){const[u,v]=tr(s.p[0],s.p[2]);rx.fillStyle='rgba(200,200,210,.45)';rx.beginPath();rx.arc(u,v,5*sc,0,7);rx.fill()}
for(const k in others){const o=others[k];if(o.team!==myTeam||!o.alive)continue;const[u,v]=tr(o.g.position.x,o.g.position.z);rx.fillStyle=TCOL[myTeam];rx.beginPath();rx.arc(u,v,7,0,7);rx.fill();rx.strokeStyle='#000';rx.lineWidth=2;rx.stroke()}
rx.fillStyle='#fff';rx.strokeStyle='#000';rx.lineWidth=2;rx.beginPath();rx.moveTo(c,c-13);rx.lineTo(c+9,c+10);rx.lineTo(c,c+5);rx.lineTo(c-9,c+10);rx.closePath();rx.fill();rx.stroke();rx.restore()}
/* ---------- thrown items: knife / frag / smoke / molotov ---------- */
const projs={},fx=[],smokes=[],fires=[];
let _smk=null;function smokeTex(){if(_smk)return _smk;const c=document.createElement('canvas');c.width=c.height=128;const x=c.getContext('2d'),g=x.createRadialGradient(64,64,4,64,64,62);g.addColorStop(0,'rgba(215,215,222,.95)');g.addColorStop(.55,'rgba(185,185,195,.7)');g.addColorStop(1,'rgba(160,160,170,0)');x.fillStyle=g;x.fillRect(0,0,128,128);return _smk=new THREE.CanvasTexture(c)}
function projMesh(k){const g=new THREE.Group();
if(k==='kn'){const m=makeKnife(false);m.scale.setScalar(1.4);g.add(m)}
else if(k==='frag'){mk(g,new THREE.SphereGeometry(.06,10,8),PH(0x3d4a2c,0x333333,20));mk(g,new THREE.CylinderGeometry(.012,.012,.05,6),PH(0x777777),0,.07,0);mk(g,B3(.012,.012,.06),PH(0x999999),0,.09,.025)}
else if(k==='smoke'){mk(g,new THREE.CylinderGeometry(.045,.045,.17,10),PH(0x8a8f95,0x888888,40));mk(g,new THREE.CylinderGeometry(.02,.02,.04,8),PH(0x333333),0,.1,0)}
else{mk(g,new THREE.CylinderGeometry(.05,.05,.15,10),PH(0x3d6b3a,0xaaffaa,70));mk(g,new THREE.CylinderGeometry(.018,.022,.08,8),PH(0x3d6b3a,0xaaffaa,70),0,.11,0);const f=new THREE.Sprite(new THREE.SpriteMaterial({map:glowTex('#ff9a2a',.15),transparent:true,blending:THREE.AdditiveBlending,depthWrite:false}));f.scale.set(.35,.35,1);f.position.y=.2;g.add(f)}
scene.add(g);return g}
function spawnProj(m){const mesh=projMesh(m.k);mesh.position.set(...m.o);projs[m.id]={id:m.id,k:m.k,m:mesh,p:[...m.o],v:[...m.v],g:m.g,st:'fly',own:m.by};snd('throw',m.by===me?.7:.4)}
function stepProj(q,dt){const r=.12,v=q.v,p=q.p;v[1]-=q.g*dt;const n=[p[0]+v[0]*dt,p[1]+v[1]*dt,p[2]+v[2]*dt];let hit=false;
if(n[1]<r){n[1]=r;hit=true;if(v[1]<0){v[1]=-v[1]*.35;v[0]*=.65;v[2]*=.65}}
for(const[x,y0,z,w,h,d]of boxes){if(Math.abs(n[0]-x)<w/2+r&&Math.abs(n[2]-z)<d/2+r&&y0-r<n[1]&&n[1]<y0+h+r){
const c=[[x+w/2+r-n[0],0,1],[n[0]-(x-w/2-r),0,-1],[z+d/2+r-n[2],2,1],[n[2]-(z-d/2-r),2,-1],[y0+h+r-n[1],1,1],[n[1]-(y0-r),1,-1]];let b=c[0];for(const e of c)if(e[0]<b[0])b=e;
n[b[1]]+=b[2]*b[0];hit=true;if(v[b[1]]*b[2]<0)v[b[1]]=-v[b[1]]*.35;for(let k=0;k<3;k++)if(k!==b[1])v[k]*=.75}}
q.p=n;return hit}
function updProj(dt){for(const id in projs){const q=projs[id];if(q.st==='fly'){for(let i=0;i<2;i++){const h=stepProj(q,dt/2);if(h&&q.k==='kn'){q.v=[0,0,0];q.st='wait';break}}
q.m.position.set(q.p[0],q.p[1],q.p[2]);if(q.k==='kn'){const d=V3(q.v[0],q.v[1],q.v[2]);if(d.lengthSq()>.01)q.m.quaternion.setFromUnitVectors(V3(0,0,-1),d.normalize())}else{q.m.rotation.x+=dt*9;q.m.rotation.z+=dt*5}}}}
function knifeStuck(m){const q=projs[m.id];if(!q)return;q.p=[...m.p];q.v=[0,0,0];q.st='stuck';q.m.position.set(...m.p);if(q.own===me){const s=new THREE.Sprite(new THREE.SpriteMaterial({map:glowTex('#ffd27a',.1),transparent:true,blending:THREE.AdditiveBlending,depthWrite:false,depthTest:false}));s.scale.set(1.1,1.1,1);s.position.y=.2;q.m.add(s);q.glow=s}}
function removeProj(id){const q=projs[id];if(q){scene.remove(q.m);delete projs[id]}}
function addFx(o){o.t=0;fx.push(o)}
function updFx(dt){for(let i=fx.length-1;i>=0;i--){const f=fx[i];f.t+=dt;if(f.t>=f.dur){f.end&&f.end();fx.splice(i,1)}else f.upd(f.t/f.dur,dt)}}
function spr(tex,col,add,x,y,z,s){const m=new THREE.SpriteMaterial({map:tex,color:col,transparent:true,depthWrite:false,blending:add?THREE.AdditiveBlending:THREE.NormalBlending}),sp=new THREE.Sprite(m);sp.position.set(x,y,z);sp.scale.set(s,s,1);scene.add(sp);return sp}
const rmSp=sp=>{scene.remove(sp);sp.material.dispose()};
function boom(m){removeProj(m.id);const p=m.p;
if(m.k==='frag')explosion(p);else if(m.k==='smoke')smokeCloud(p,m.dur);else fireZone(p,m.dur)}
function explosion(p){const d=Math.hypot(cam.position.x-p[0],cam.position.y-p[1],cam.position.z-p[2]);snd('frag',Math.min(1,16/(d+4)));shake=Math.max(shake,Math.min(1.3,12/(d+1)));
if(d<10){const f=$('#flash');f.style.transition='none';f.style.opacity=Math.min(.9,.15+(10-d)*.1);void f.offsetWidth;f.style.transition='opacity .6s';f.style.opacity=0}
const gt=glowTex('#ff9a3a',.2),a=spr(gt,0xffffff,true,p[0],p[1]+.8,p[2],2),b=spr(glowTex('#ffffff',.4),0xffffff,true,p[0],p[1]+.8,p[2],6);
const ring=new THREE.Mesh(new THREE.RingGeometry(.85,1,32),new THREE.MeshBasicMaterial({color:0xffc070,transparent:true,blending:THREE.AdditiveBlending,depthWrite:false,side:THREE.DoubleSide}));ring.rotation.x=-Math.PI/2;ring.position.set(p[0],.15,p[2]);scene.add(ring);
const N=70,pos=new Float32Array(N*3),vel=[];for(let i=0;i<N;i++){pos[i*3]=p[0];pos[i*3+1]=p[1]+.3;pos[i*3+2]=p[2];const a=Math.random()*6.28,e=Math.random()*1.3,s=6+Math.random()*10;vel.push([Math.cos(a)*Math.cos(e)*s,Math.sin(e)*s+3,Math.sin(a)*Math.cos(e)*s])}
const sg=new THREE.BufferGeometry();sg.setAttribute('position',new THREE.BufferAttribute(pos,3));const sp=new THREE.Points(sg,new THREE.PointsMaterial({color:0xffb050,size:.22,transparent:true,depthWrite:false,blending:THREE.AdditiveBlending}));sp.frustumCulled=false;scene.add(sp);
const smk=[];for(let i=0;i<6;i++)smk.push(spr(smokeTex(),0x444444,false,p[0]+(Math.random()-.5)*2,p[1]+.5,p[2]+(Math.random()-.5)*2,3));
addFx({dur:2.8,upd(u,dt){const s=1+u*0;a.scale.setScalar(2+Math.min(1,u*5)*9);a.material.opacity=Math.max(0,1-u*3);b.scale.setScalar(6*Math.max(0,1-u*8));ring.scale.setScalar(1+u*14);ring.material.opacity=Math.max(0,.9-u*3);
const ps=sg.attributes.position;for(let i=0;i<N;i++){vel[i][1]-=22*dt;ps.setXYZ(i,ps.getX(i)+vel[i][0]*dt,Math.max(.05,ps.getY(i)+vel[i][1]*dt),ps.getZ(i)+vel[i][2]*dt)}ps.needsUpdate=true;sp.material.opacity=Math.max(0,1-u*2.2);
smk.forEach((q,i)=>{q.position.y+=dt*(1.2+i*.1);q.scale.setScalar(3+u*7);q.material.opacity=Math.max(0,.75*(1-u))})},end(){rmSp(a);rmSp(b);scene.remove(ring);ring.material.dispose();scene.remove(sp);sg.dispose();sp.material.dispose();smk.forEach(rmSp)}})}
function smokeCloud(p,dur){snd('smoke',Math.min(1,14/(Math.hypot(cam.position.x-p[0],cam.position.z-p[2])+4)));const items=[];for(let i=0;i<20;i++){const a=Math.random()*6.28,r=Math.random()*2.6,h=Math.random()*3.4;const s=spr(smokeTex(),0xffffff,false,p[0]+Math.cos(a)*r,p[1]+h,p[2]+Math.sin(a)*r,.5);s.material.rotation=Math.random()*6;items.push({s,sz:4.5+Math.random()*2.5,sp:(Math.random()-.5)*.2})}
const rec={p:[p[0],p[1],p[2]],end:performance.now()+dur*1000};smokes.push(rec);
addFx({dur,upd(u,dt){const g=Math.min(1,u*dur/2.2),fade=Math.min(1,(1-u)*dur/2.5);items.forEach(q=>{q.s.scale.setScalar(.5+q.sz*g);q.s.material.opacity=.92*fade;q.s.material.rotation+=q.sp*dt})},end(){items.forEach(q=>rmSp(q.s));const i=smokes.indexOf(rec);if(i>=0)smokes.splice(i,1)}})}
function fireZone(p,dur){snd('molo',Math.min(1,14/(Math.hypot(cam.position.x-p[0],cam.position.z-p[2])+4)));
const gl=new THREE.Mesh(new THREE.CircleGeometry(3.4,28),new THREE.MeshBasicMaterial({map:glowTex('#ff7a20',.2),transparent:true,blending:THREE.AdditiveBlending,depthWrite:false}));gl.rotation.x=-Math.PI/2;gl.position.set(p[0],p[1]+.06,p[2]);scene.add(gl);
const fl=[];for(let i=0;i<18;i++){const a=Math.random()*6.28,r=Math.sqrt(Math.random())*3;fl.push({s:spr(glowTex('#ff8a20',.12),0xffffff,true,p[0]+Math.cos(a)*r,p[1]+.6,p[2]+Math.sin(a)*r,1.6),ph:Math.random()*6,b:p[1]})}
const rec={p:[p[0],p[1],p[2]],end:performance.now()+dur*1000};fires.push(rec);
addFx({dur,upd(u,dt){const fade=Math.min(1,(1-u)*dur/1.2),t=performance.now()/1000;gl.material.opacity=.8*fade;fl.forEach(q=>{const k=Math.sin(t*9+q.ph)*.5+.5;q.s.scale.set(1.2+k*.9,1.6+k*1.4,1);q.s.position.y=q.b+.5+k*.5;q.s.material.opacity=fade*(.55+k*.4)})},end(){scene.remove(gl);gl.geometry.dispose();gl.material.dispose();fl.forEach(q=>rmSp(q.s));const i=fires.indexOf(rec);if(i>=0)fires.splice(i,1)}})}
/* ---------- game flow ---------- */
const EYEH=[1.6,1.0,.55],HGT=[1.7,1.0,.5],SPD={k:7,s:4.8,m4:5.8,pkc:4.3};
let stance=0,slideT=0,slideCD=0,slideV=[0,0],camH=1.6,T=0;
function snap(m){lastSc=m.sc;$('#sH').textContent=m.sc[0];$('#sV').textContent=m.sc[1];$('#bH').style.width=Math.min(100,m.sc[0]/WIN*100)+'%';$('#bV').style.width=Math.min(100,m.sc[1]/WIN*100)+'%';
const clk=$('#clk');clk.textContent=Math.floor(m.left/60)+':'+String(m.left%60).padStart(2,'0');clk.classList.toggle('lo',m.left<=30);const now=performance.now();
for(const[id,x,y,z,yaw,al,pitch,w,sa]of m.p){if(id===me)continue;let o=others[id];if(!o){const pl=Rm&&Rm.players.find(p=>p.id===id);if(!pl)continue;o=others[id]=avatar(pl);o.g.position.set(x,y,z)}
if(al&&!o.alive){o.buf=[];o.g.position.set(x,y,z);o.dt=0}if(!al&&o.alive)o.dt=0;o.alive=!!al;o.buf.push({t:now,x,y,z,yaw});if(o.buf.length>14)o.buf.shift();o.pitch=pitch||0;o.wp=w||'k';o.sa=sa||0}}
function endGame(){playing=false;alive=false;scoped=false;fireHeld=false;stance=0;for(const k in others){scene.remove(others[k].g)}others={};for(const t of tracers){scene.remove(t.m)}tracers.length=0;
for(const id in projs)removeProj(id);fx.slice().forEach(f=>{f.end&&f.end()});fx.length=0;smokes.length=0;fires.length=0;show('#over',0);show('#death',0);show('#scope',0);show('#cdn',0);closeShop();$('#smk').style.opacity=0;$('#fir').style.opacity=0}
function startGame(m){endGame();boxes=m.boxes;mapI=m.map;myTeam=m.team;WIN=m.win||25;kills=0;deaths=0;hp=100;updHp(0);updKD();lastSc=[0,0];buildWorld(m.map);sleeveM.color.setHex(myTeam==='H'?0x146b62:0x8a2332);
show('#set',0);showScr('game');show('#over',0);$('#feed').innerHTML='';$('#sH').textContent=$('#sV').textContent='0';$('#bH').style.width=$('#bV').style.width='0';playing=true;goAt=performance.now()+m.cd*1000;lastCd=0;reloadEnd=0;wp='s';setWp('k');swapT=0;
hintT=performance.now()+9000;$('#hint').style.opacity=.85;$('#hint').textContent=touch?'عصا يسار للحركة • اسحب باليمين للتصويب • 🛒 المتجر فوق: اشترِ M4 و PKC والقنابل':'WASD حركة • ماوس تصويب • كليك يسار ضرب • يمين منظار • 1-4 أسلحة • C تزحلق • Z انبطاح • B متجر • F/G/H/V رمي'}
function setWp(w){if(w!==wp){swapT=0;snd('swap')}wp=w;if(w!=='s')scoped=false;for(const id in rigs)rigs[id].r.visible=id===wp&&!(scoped&&id==='s');show('#scope',scoped?1:0);show('#xh',scoped?0:1);$('#bs').style.visibility=wp==='s'?'visible':'hidden';
for(const[id,k]of[['#s1','k'],['#s2','s'],['#s3','m4'],['#s4','pkc']])$(id).classList.toggle('on',wp===k);
bt('#bf',wp==='k'?IC.k:IC.cross,wp==='k'?'اضرب':'أطلق');$('#cdbar').style.opacity=0;updAmmo()}
function trySlot(w){if(!playing||!alive)return;if(!inv.own.includes(w)){openShop();return}if(w==='k'&&!inv.kn){note('السكين مرمية، اجمعها من الأرض أو انتظر الموت');return}setWp(w)}
function toggleScope(){if(wp==='s'&&alive&&stance!==1){scoped=!scoped;setWp('s');snd('swap')}}
function doFire(){const n=performance.now();if(!playing||!alive||n<goAt||n<cd||shopOpen||editing)return;const w=wp;if(w==='k'&&!inv.kn)return;
if(isAuto(w)){if(inv.ammo[w]<=0){doReload();return}if(reloadEnd>n)return}
const L=w==='k'?450:w==='s'?1600:w==='m4'?90:85;cdLen=L;cd=n+L;cdStart=n;send({t:'fire',w,x:P.x,y:P.y,z:P.z,yaw:P.yaw,pitch:P.pitch,sa:stance,sc:scoped?1:0});
if(w==='k'){slashT=0;snd('knife');hap('light')}
else if(w==='s'){fireT=0;boltOk=false;P.pitch=Math.min(1.45,P.pitch+.014);snd('snipe');hap('heavy')}
else{inv.ammo[w]--;updAmmo();kick=1.2;flashT=.045;P.pitch=Math.min(1.45,P.pitch+(w==='m4'?.0085:.012));P.yaw+=(Math.random()-.5)*(w==='m4'?.004:.007);snd(w);hap('light')}}
function doReload(){const n=performance.now();if(!alive||!isAuto(wp)||reloadEnd>n||inv.ammo[wp]>=(wp==='m4'?30:100))return;send({t:'reload',w:wp})}
function doThrow(k){const n=performance.now();if(!playing||!alive||n<goAt||shopOpen||editing)return;
if(k==='kn'){if(!inv.kn){note('ما عندك سكين');return}}else if(!inv.gr[k]){note('ما عندك، اشتريها من المتجر 🛒');return}
send({t:'throw',k,x:P.x,y:P.y,z:P.z,yaw:P.yaw,pitch:P.pitch,sa:stance})}
function doSlide(){const n=performance.now();if(!playing||!alive||n<goAt||n<slideCD||stance!==0||!P.ground||shopOpen||editing)return;scoped=false;setWp(wp);
let fx=joy.x+(keys.KeyD?1:0)-(keys.KeyA?1:0),fz=joy.y+(keys.KeyS?1:0)-(keys.KeyW?1:0);if(Math.hypot(fx,fz)<.25){fx=0;fz=-1}const l=Math.hypot(fx,fz);fx/=l;fz/=l;const s=Math.sin(P.yaw),c=Math.cos(P.yaw);
slideV=[fx*c+fz*s,-fx*s+fz*c];stance=1;slideT=.75;slideCD=n+2000;snd('slide');hap('medium')}
function toggleProne(){if(!playing||!alive||editing||shopOpen)return;if(stance===2)stance=0;else if(stance===0&&P.ground){stance=2;scoped=false;setWp(wp)}}
function look(dx,dy){const s=(scoped?.0013:.0036)*cfg.sens;P.yaw-=dx*s;P.pitch=Math.max(-1.45,Math.min(1.45,P.pitch-dy*s))}
const PR=.4;
function move(dt){let fx=0,fz=0;
if(stance===1){slideT-=dt;const k=Math.max(0,slideT/.75),sp=4+7*k;var nx=P.x+slideV[0]*sp*dt,nz=P.z+slideV[1]*sp*dt;mv=1;if(slideT<=0)stance=0}
else{if(keys.KeyW)fz--;if(keys.KeyS)fz++;if(keys.KeyA)fx--;if(keys.KeyD)fx++;fx+=joy.x;fz+=joy.y;const l=Math.hypot(fx,fz);if(l>1){fx/=l;fz/=l}mv=Math.min(1,l);
const sp=(SPD[wp]||6)*(scoped?.45:1)*(stance===2?.35:1),s=Math.sin(P.yaw),c=Math.cos(P.yaw);nx=P.x+(fx*c+fz*s)*sp*dt;nz=P.z+(-fx*s+fz*c)*sp*dt}
const H=HGT[stance];
for(const[x,y0,z,w,h,d]of boxes){if(P.y<y0+h-.55&&P.y+H>y0){const ox=w/2+PR-Math.abs(nx-x),oz=d/2+PR-Math.abs(nz-z);if(ox>0&&oz>0){if(ox<oz)nx+=Math.sign(nx-x||1)*ox;else nz+=Math.sign(nz-z||1)*oz}}}
P.x=Math.max(-34,Math.min(34,nx));P.z=Math.max(-34,Math.min(34,nz));let gr=0;
for(const[x,y0,z,w,h,d]of boxes){const top=y0+h;if(Math.abs(P.x-x)<w/2+PR-.02&&Math.abs(P.z-z)<d/2+PR-.02&&P.y>=top-.55&&top>gr)gr=top}
if(keys.Space&&P.ground){if(stance===2){stance=0;keys.Space=false}else if(stance===0)P.vy=9}P.vy-=25*dt;P.y+=P.vy*dt;if(P.y<=gr){P.y=gr;P.vy=0;P.ground=true}else P.ground=false}
let last=performance.now(),lastSend=0,fr=0;
function frame(n){requestAnimationFrame(frame);const dt=Math.min((n-last)/1000,.05);last=n;fr++;T+=dt;
if(!playing)return;
if(n<goAt){const c=Math.ceil((goAt-n)/1000);$('#cdn').innerHTML=c+'<small>استعد!</small>';show('#cdn','flex');if(c!==lastCd){lastCd=c;snd('tick')}}else{if(lastCd){lastCd=0;snd('go');$('#cdn').innerHTML='ابدأ!';setTimeout(()=>show('#cdn',0),700)}}
mv=0;if(alive&&n>=goAt){move(dt);if(fireHeld&&(wp==='k'||isAuto(wp)))doFire();if(n-lastSend>33){lastSend=n;send({t:'st',x:P.x,y:P.y,z:P.z,yaw:P.yaw,pitch:P.pitch,wp,sa:stance})}if(P.y<-12){send({t:'fall'});alive=false}}
if(!alive&&deathEnd){const el=$('#dsec');if(el)el.textContent=Math.max(0,Math.ceil((deathEnd-n)/1000))}
camH+=(EYEH[stance]-camH)*Math.min(1,dt*12);
let sx=0,sy=0;if(shake>0){shake=Math.max(0,shake-dt*2.2);sx=(Math.random()-.5)*shake*.18;sy=(Math.random()-.5)*shake*.18}
cam.position.set(P.x+sx,P.y+camH+sy,P.z);cam.rotation.set(P.pitch+sy*.3,P.yaw+sx*.3,stance===1?.06:0);const tf=scoped?16:baseFov;cam.fov+=(tf-cam.fov)*Math.min(1,dt*14);cam.updateProjectionMatrix();
skyG.position.copy(cam.position);wAnim(dt);updParts(dt);updTracers(dt);updProj(dt);updFx(dt);animOthers(dt);
if(fr%3===0)radar();
let sm=0;for(const s of smokes){const d=Math.hypot(cam.position.x-s.p[0],cam.position.z-s.p[2]);if(d<5&&cam.position.y<s.p[1]+4.5)sm=Math.max(sm,Math.min(1,(5-d)/2.2))}$('#smk').style.opacity=sm*.93;
let fo=0;for(const f of fires){if(Math.hypot(P.x-f.p[0],P.z-f.p[2])<3.3&&Math.abs(P.y-f.p[1])<2)fo=1}$('#fir').style.opacity=fo&&alive?.55+Math.sin(T*12)*.2:0;
const cdb=$('#cdbar');if(reloadEnd>n&&reloadLen){cdb.style.opacity=1;cdb.firstChild.style.width=((1-(reloadEnd-n)/reloadLen)*100)+'%'}else if(wp==='s'&&n<cdStart+cdLen&&alive){cdb.style.opacity=1;cdb.firstChild.style.width=((n-cdStart)/cdLen*100)+'%'}else if(cdb.style.opacity!=='0'){cdb.style.opacity=0;if(reloadLen&&reloadEnd&&reloadEnd<=n){reloadEnd=0;updAmmo()}}
$('#bl .cdr').style.setProperty('--p',Math.max(0,(slideCD-n)/2000*100));
if(hintT&&n>hintT){hintT=0;$('#hint').style.opacity=0}
renderer.clear();renderer.render(scene,cam);if(alive&&!scoped){renderer.clearDepth();renderer.render(wScene,wCam)}}
requestAnimationFrame(frame);
/* ---------- input ---------- */
const cv=$('#cv'),free=()=>shopOpen||editing||!playing||!alive;
cv.addEventListener('click',()=>{if(!touch&&!free()&&cv.requestPointerLock)cv.requestPointerLock()});
document.addEventListener('mousemove',e=>{if(document.pointerLockElement===cv&&!free())look(e.movementX,e.movementY)});
cv.addEventListener('mousedown',e=>{if(document.pointerLockElement!==cv)return;if(e.button===0){fireHeld=true;doFire()}if(e.button===2)toggleScope()});
addEventListener('mouseup',e=>{if(e.button===0)fireHeld=false});cv.addEventListener('contextmenu',e=>e.preventDefault());
addEventListener('keydown',e=>{if(e.target&&e.target.tagName==='INPUT')return;keys[e.code]=true;
if(e.code==='KeyB'&&screen==='game'){shopOpen?closeShop():openShop();return}if(e.code==='Escape'){closeShop();show('#set',0)}
if(!playing||shopOpen||editing)return;
if(e.code==='Digit1')trySlot('k');if(e.code==='Digit2')trySlot('s');if(e.code==='Digit3')trySlot('m4');if(e.code==='Digit4')trySlot('pkc');
if(e.code==='KeyQ')trySlot(wp==='k'?'s':'k');if(e.code==='KeyC'||e.code==='ShiftLeft')doSlide();if(e.code==='KeyZ')toggleProne();if(e.code==='KeyR')doReload();
if(e.code==='KeyF')doThrow('kn');if(e.code==='KeyG')doThrow('frag');if(e.code==='KeyH')doThrow('smoke');if(e.code==='KeyV')doThrow('molo')});
addEventListener('keyup',e=>keys[e.code]=false);
let joyId=null,joyO=null,lookId=null,lx=0,ly=0;const jy=$('#joy'),jfix=$('#joyfix');
cv.addEventListener('touchstart',e=>{e.preventDefault();if(free()&&!playing)return;for(const t of e.changedTouches){const fixed=cfg.joy==='fixed',r=jfix.getBoundingClientRect(),cx=r.left+r.width/2,cy=r.top+r.height/2;
const zone=fixed?Math.hypot(t.clientX-cx,t.clientY-cy)<85:(cfg.side==='L'?t.clientX<innerWidth*.45:t.clientX>innerWidth*.55);
if(zone&&joyId===null){joyId=t.identifier;joyO=fixed?[cx,cy]:[t.clientX,t.clientY];if(!fixed){jy.style.left=t.clientX+'px';jy.style.top=t.clientY+'px';jy.style.display='block';jy.firstChild.style.transform='none'}}
else if(lookId===null){lookId=t.identifier;lx=t.clientX;ly=t.clientY}}},{passive:false});
cv.addEventListener('touchmove',e=>{e.preventDefault();for(const t of e.changedTouches){if(t.identifier===joyId){let dx=(t.clientX-joyO[0])/50,dy=(t.clientY-joyO[1])/50;const l=Math.hypot(dx,dy);if(l>1){dx/=l;dy/=l}joy.x=dx;joy.y=dy;(cfg.joy==='fixed'?jfix:jy).firstChild.style.transform=`translate(${dx*40}px,${dy*40}px)`}else if(t.identifier===lookId){if(!free())look((t.clientX-lx)*1.5,(t.clientY-ly)*1.5);lx=t.clientX;ly=t.clientY}}},{passive:false});
const tend=e=>{for(const t of e.changedTouches){if(t.identifier===joyId){joyId=null;joy.x=joy.y=0;jy.style.display='none';jfix.firstChild.style.transform='none'}if(t.identifier===lookId)lookId=null}};cv.addEventListener('touchend',tend);cv.addEventListener('touchcancel',tend);
const bind=(id,dn,up)=>{const b=$(id);b.addEventListener('pointerdown',e=>{if(editing)return;e.preventDefault();dn()});['pointerup','pointerleave','pointercancel'].forEach(k=>b.addEventListener(k,()=>{if(!editing&&up)up()}))};
bind('#bf',()=>{fireHeld=true;doFire()},()=>fireHeld=false);bind('#bj',()=>keys.Space=true,()=>keys.Space=false);bind('#bs',toggleScope);bind('#bl',doSlide);bind('#bp',toggleProne);bind('#br',doReload);
bind('#bk',()=>doThrow('kn'));bind('#bg_',()=>doThrow('frag'));bind('#bh',()=>doThrow('smoke'));bind('#bm',()=>doThrow('molo'));
$$('.slot').forEach(s=>s.addEventListener('pointerdown',e=>{if(editing)return;e.preventDefault();trySlot(s.dataset.w)}));
setWp('k');updInv();
connect();
</script></body></html>'''
if __name__ == "__main__":
asyncio.run(main())
|