commit ce2962e39e72be05798d3a591c12c4277f3233b2 Author: Bruno Rybársky Date: Tue Nov 17 17:51:13 2026 +0100 init diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..2fa1544 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,12 @@ +node_modules +npm-debug.log +*.log +*.bak +.DS_Store +.git +docs +tests +deploy +Dockerfile +docker-compose.yml +.dockerignore diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..01f0f30 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +node_modules/ +*.log +*.bak +.DS_Store diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..eae8e7b --- /dev/null +++ b/Dockerfile @@ -0,0 +1,18 @@ +# Politické karty – no npm dependencies, so no install step is needed. +FROM node:22-alpine + +ENV NODE_ENV=production PORT=3000 +WORKDIR /app + +# Copy only what the server needs at runtime; files stay owned by root (read-only for the app user). +COPY package.json server.js ./ +COPY public ./public + +# Run as the unprivileged "node" user that ships with the image. +USER node +EXPOSE 3000 + +HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \ + CMD node -e "fetch('http://127.0.0.1:'+(process.env.PORT||3000)+'/api/ping').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))" + +CMD ["node", "server.js"] diff --git a/README.md b/README.md new file mode 100644 index 0000000..cd1d814 --- /dev/null +++ b/README.md @@ -0,0 +1,117 @@ +# Politické karty + +Kompletný samostatný projekt hry: Node.js server, prehliadačové rozhranie a pravidlá. Nepotrebuje npm závislosti; stačí Node.js 18 alebo novší. + +## Spustenie + +```bash +node server.js +``` + +Potom otvor `http://localhost:3000`. Port je možné zmeniť premennou prostredia `PORT`. + +Alternatívne: + +```bash +npm start +npm test +``` + +## Nasadenie na server (Docker + nginx s HTTPS) + +Kontajner počúva iba na `127.0.0.1:8347`, takže z internetu je dostupný len cez nginx na tom istom serveri. Vo vnútri kontajnera beží aplikácia na porte 3000, ten však navonok viditeľný nie je. + +### 1. Spusti kontajner + +Skopíruj priečinok projektu na server a v ňom spusti: + +```bash +docker compose up -d --build +curl http://127.0.0.1:8347/api/ping # {"ok":true} +``` + +Iný port: `HOST_PORT=9000 docker compose up -d` (potom zmeň aj riadok `upstream` v `deploy/nginx.conf`). + +Kontajner beží ako neprivilegovaný používateľ `node`, so súborovým systémom iba na čítanie, bez Linuxových capabilities, s limitom 256 MB pamäte a 100 procesov. Pri páde sa automaticky reštartuje (`restart: unless-stopped`) a má health check na `/api/ping`. + +### 2. Nastav nginx + +```bash +sed -i 's/karty.example.com/tvoja.domena.sk/g' deploy/nginx.conf +sudo cp deploy/nginx.conf /etc/nginx/conf.d/politicke-karty.conf +# ak ešte nemáš certifikát: +sudo certbot certonly --webroot -w /var/www/html -d tvoja.domena.sk +sudo nginx -t && sudo systemctl reload nginx +``` + +`deploy/nginx.conf`: + +- presmeruje HTTP na HTTPS (cesta `/.well-known/acme-challenge/` ostáva na HTTP kvôli obnove certifikátov), +- používa TLS 1.2/1.3, HTTP/2 a HSTS, +- pre `/api/events` (SSE živé aktualizácie) vypína buffering a dovoľuje hodinu otvorené spojenia; bez toho by hra zamŕzala, +- obmedzuje API požiadavky (10/s na IP, burst 30) a živé spojenia (20 na IP), +- nezapisuje `/api/events` do access logu, lebo URL obsahuje token hráča. + +Poznámky: + +- Cesty k certifikátu sú predvolené pre certbot (`/etc/letsencrypt/live//`). Pri vlastnom certifikáte uprav `ssl_certificate` a `ssl_certificate_key`. +- `http2 on;` vyžaduje nginx 1.25.1 alebo novší. Na staršom nginx ten riadok zmaž a použi `listen 443 ssl http2;`. +- Súbor musí byť načítaný v kontexte `http {}` (to platí pre `conf.d/` aj `sites-enabled/`), lebo obsahuje `limit_req_zone` a `limit_conn_zone`. + +### 3. Aktualizácia a správa + +```bash +docker compose up -d --build # po zmene kódu +docker compose logs -f # logy +docker compose down # zastavenie +``` + +Reštart kontajnera ukončí všetky rozohrané hry (stav je len v pamäti). + +### Limity a premenné prostredia + +| Premenná | Predvolené | Význam | +| --- | --- | --- | +| `HOST_PORT` | `8347` | port na `127.0.0.1` hostiteľa (iba docker compose) | +| `PORT` | `3000` | port aplikácie vo vnútri kontajnera | +| `MAX_CLIENTS_PER_ROOM` | `64` | max. živých spojení divákov v jednej miestnosti (hráči sa pripoja vždy) | +| `MAX_CLIENTS_TOTAL` | `2000` | max. živých spojení na celom serveri | + +Server má aj pevný limit 500 miestností a 20 kB na telo požiadavky. + +## Herné režimy + +- **Balanced** – prvý návrh úprav podľa statickej analýzy kariet. Oslabuje najextrémnejšie pasívne a okamžité efekty a posilňuje niekoľko výrazne slabých kariet. +- **Fun** – pôvodné hodnoty kariet a schopností. Multiplayerové pravidlá a časovanie celých kôl sú rovnaké v oboch režimoch. + +Režim sa vyberá v hlavnom menu alebo pri vytváraní online miestnosti. Online miestnosť si ho uloží a server je autoritatívny. + +## Online multiplayer + +- Free-for-all pre 2 až 8 hráčov. +- Pri vytváraní miestnosti sa volí kapacita; predvolená hodnota je 6. +- Každý hráč si vyberie vlastný tím štyroch kariet. Karty sa môžu opakovať medzi tímami. +- Tvorca miestnosti (hráč 1) spustí hru tlačidlom **Spustiť hru**, keď sú pripravení aspoň dvaja hráči a každý aktuálne pripojený hráč má potvrdený tím. +- Hrá sa každý proti každému; útoky a nepriateľské schopnosti môžu cieliť na ktoréhokoľvek súpera. +- Ťahy rotujú v poradí hráčov. Vyradení hráči sa preskakujú. +- Vyhráva posledný hráč, ktorému zostala aspoň jedna karta na stole alebo v rezerve. +- Po začatí hry sa ďalší návštevníci pripájajú ako diváci. +- Stav miestností sa drží v pamäti procesu; po reštarte servera sa miestnosti stratia. + +## Obrázky kariet + +Obrázky sú voliteľné. Vlož ich do `public/img/` a pomenuj podľa kľúča karty, napríklad: + +```text +public/img/meciar.jpg +public/img/caputova.webp +``` + +Podporované prípony: `.jpg`, `.jpeg`, `.png`, `.webp`, `.gif`. Dočasné obrázky možno pomenovať napríklad `meciar.kandidat.webp`; hotový `meciar.webp` má prednosť. + +## Poznámky + +- `public/game.js` obsahuje karty aj pravidlá a používa ho prehliadač i server. +- `server.js` implementuje miestnosti, SSE aktualizácie a serverové vyhodnocovanie akcií. +- Online server nemá používateľské účty ani databázu. Zoznam miestností je verejný a ktokoľvek môže sledovať hru ako divák. Pre verejné nasadenie používaj HTTPS a obmedzenie požiadaviek (viď [Nasadenie na server](#nasadenie-na-server-docker--nginx-s-https)). Rate limiting sťaží, ale úplne nezabráni tomu, aby niekto zaplnil všetkých 500 miestností. +- Balanced je počiatočný návrh, nie výsledok simulácií ani dlhodobého playtestovania. Číselné zmeny sú popísané v `docs/BALANCE.md`. diff --git a/deploy/nginx.conf b/deploy/nginx.conf new file mode 100644 index 0000000..df2ff03 --- /dev/null +++ b/deploy/nginx.conf @@ -0,0 +1,74 @@ +# nginx site for Politické karty (HTTPS reverse proxy -> Docker container on 127.0.0.1:8347). +# +# 1. Replace karty.example.com with your domain (4 places below). +# 2. Install: sudo cp deploy/nginx.conf /etc/nginx/conf.d/politicke-karty.conf +# (conf.d/ and sites-enabled/ are included inside http{}, which the two *_zone lines need) +# 3. Certificates: the paths below are certbot's defaults. If you don't have a cert yet: +# sudo certbot certonly --webroot -w /var/www/html -d karty.example.com +# or point ssl_certificate / ssl_certificate_key at your own files. +# 4. sudo nginx -t && sudo systemctl reload nginx + +limit_req_zone $binary_remote_addr zone=karty_api:10m rate=10r/s; +limit_conn_zone $binary_remote_addr zone=karty_conn:10m; + +upstream politicke_karty { + server 127.0.0.1:8347; + keepalive 16; +} + +# HTTP -> HTTPS (keeps the ACME path open for certbot renewals) +server { + listen 80; + listen [::]:80; + server_name karty.example.com; + + location /.well-known/acme-challenge/ { root /var/www/html; } + location / { return 301 https://$host$request_uri; } +} + +server { + listen 443 ssl; + listen [::]:443 ssl; + http2 on; # nginx >= 1.25.1; on older versions use "listen 443 ssl http2;" instead + server_name karty.example.com; + + ssl_certificate /etc/letsencrypt/live/karty.example.com/fullchain.pem; + ssl_certificate_key /etc/letsencrypt/live/karty.example.com/privkey.pem; + ssl_protocols TLSv1.2 TLSv1.3; + ssl_prefer_server_ciphers off; + ssl_session_cache shared:karty_ssl:10m; + ssl_session_timeout 1d; + + client_max_body_size 32k; + + add_header Strict-Transport-Security "max-age=31536000" always; + add_header X-Content-Type-Options nosniff always; + add_header Referrer-Policy same-origin always; + add_header X-Frame-Options SAMEORIGIN always; + + proxy_http_version 1.1; + proxy_set_header Connection ""; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto https; + + # Live game updates (Server-Sent Events): no buffering, long-lived connections. + location = /api/events { + limit_conn karty_conn 20; # simultaneous live connections per IP + proxy_pass http://politicke_karty; + proxy_buffering off; + proxy_cache off; + proxy_read_timeout 1h; # the app pings every 25 s + access_log off; # query string contains the player's seat token + } + + location /api/ { + limit_req zone=karty_api burst=30 nodelay; + proxy_pass http://politicke_karty; + } + + location / { + proxy_pass http://politicke_karty; + } +} diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..deb37b7 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,22 @@ +services: + politicke-karty: + build: . + image: politicke-karty:latest + container_name: politicke-karty + restart: unless-stopped + init: true # forwards SIGTERM so `docker stop` is instant + environment: + PORT: "3000" + # MAX_CLIENTS_PER_ROOM: "64" # live connections per room (spectators) + # MAX_CLIENTS_TOTAL: "2000" # live connections across the whole server + ports: + # Bound to localhost only: reachable by nginx on the host, not from the internet. + - "127.0.0.1:${HOST_PORT:-8347}:3000" + read_only: true + cap_drop: [ALL] + security_opt: ["no-new-privileges:true"] + mem_limit: 256m + pids_limit: 100 + logging: + driver: json-file + options: { max-size: "10m", max-file: "3" } diff --git a/docs/BALANCE.md b/docs/BALANCE.md new file mode 100644 index 0000000..7884dd4 --- /dev/null +++ b/docs/BALANCE.md @@ -0,0 +1,26 @@ +# Balanced – počiatočný návrh + +Fun používa pôvodné štatistiky a silu schopností. Balanced je samostatný preset s týmito zmenami: + +| Karta / efekt | Fun | Balanced | +|---|---:|---:| +| Kažimír – pasívne poškodenie | 100 HP každému súperovi za ťah | 50 HP každému súperovi za ťah | +| Dzurinda – jeden náhodný súper | okamžité vyradenie | 400 HP poškodenia | +| Kamenický – regenerácia | 6 % HP za vlastný ťah | 3 % HP za vlastný ťah | +| Belousovová – zníženie ATK | −100 ATK | −50 ATK | +| Hlavaj – štít | 90 % redukcia | 60 % redukcia | +| Lenárt – vyhodenie z okna | každý nekomunista | len nekomunista s najviac 500 HP | +| Gašpar – nákup ATK | opakovane | každá karta najviac raz za vlastný ťah | +| Radačovský – holubica | 10 HP | 30 HP | +| Richter – odvetné poškodenie | 2 HP | 15 HP | +| Mihal – bonus pri príchode | +5 HP | +25 HP | +| Horváth | 80 HP / 20 ATK | 250 HP / 60 ATK | +| Remišová | 300 HP / 50 ATK | 450 HP / 100 ATK | +| Gaulieder | 100 HP / 90 ATK | 275 HP / 90 ATK | +| Spišiak | 200 HP / 80 ATK | 350 HP / 140 ATK | +| Pellegrini – 0 rezerv | bez modifikácie | všetky karty tímu −15 % HP a ATK | +| Pellegrini – 2 rezervy | bez modifikácie | všetky karty tímu +15 % HP a ATK | + +Hlavajov štít, Hurbanova imunita, Slotov časovač a oneskorené poškodenie Spišiaka sa odpočítavajú podľa celého kola, nie po každom jednotlivom hráčskom ťahu. + +Tieto hodnoty sú iba prvý odhad zo statickej analýzy schopností. Pred turnajovým použitím odporúčam vyhodnotiť herné záznamy a urobiť viacero testovacích zápasov. diff --git a/package.json b/package.json new file mode 100644 index 0000000..afe071e --- /dev/null +++ b/package.json @@ -0,0 +1,14 @@ +{ + "name": "politicke-karty", + "version": "1.1.0", + "private": true, + "description": "Online kartová hra Politické karty s FFA multiplayerom a Balanced/Fun režimami", + "scripts": { + "start": "node server.js", + "check": "node --check server.js && node --check public/game.js && node tests/smoke.js", + "test": "node tests/smoke.js" + }, + "engines": { + "node": ">=18" + } +} diff --git a/public/game.js b/public/game.js new file mode 100644 index 0000000..d912c15 --- /dev/null +++ b/public/game.js @@ -0,0 +1,375 @@ +"use strict"; +// Karty a pravidlá. Ten istý súbor používa prehliadač aj server. +const TEAM=4; // kariet v tíme (1 z nich v rezerve) +const F={ + prorusky:{n:"Proruský",c:"#a8262c"}, provychodny:{n:"Provýchodný",c:"#b85c14"}, + prozapadny:{n:"Prozápadný",c:"#1f5cc0"}, komunista:{n:"Komunista",c:"#7d1238"}, + fasista:{n:"Fašista",c:"#3b3b3b"}, historicky:{n:"Historický",c:"#7b5b1a"}, + prvorep:{n:"Prvorepublikový",c:"#23765a"} +}; +// [kľúč, meno, orientácia, názov schopnosti, popis, HP, ATK] +const CARDS=[ +["radacovsky","Peter Radačovský","prorusky","Holubica mieru","Môže na stôl vypustiť holubicu mieru, ktorá každé kolo narazí do náhodného politika na stole a uberie mu 10HP (použiteľné 1x)",400,50], +["lenart","Jozef Lenárt","komunista","Normalizácia na rozpočte","Môže vyhodiť jedného ne-komunistu z okna (použiteľné 1x)",100,350], +["babis","Andrej Babiš","prorusky","Slovensky Export","Babiš sedí v čapím hnízde, a může hodit čápa do jiného politika, což mu odebere 300HP (použitelné 3x)",1100,90], +["sutaj","Matúš Šutaj-Eštok","prorusky","Matúš Kukaj-Tiktok","Môže kúpiť jednému spoluhráčovi monitor za 3000€ a pridať mu tak 300HP",700,250], +["uhrik","Milan Uhrík","fasista","Neviem sa k tomu vyjadriť, niesom historik","Uhrík môže zabudnúť na holokaust a získať tak 250ATK, abilita neplatí ak je v nepriateľskom tíme člen SNP",600,150], +["hlavaj","Samuel Hlavaj","prozapadny","Olimpíjsky minister obrany","Jedno kolo aktivuje schopnosť, najbližšie 3 kolá má celý tím zníženie všetkého poškodenia o 90% (použiteľné 1x)",900,50], +["janosik","Juraj Jánošík","historicky","Biorę od bogatych i biednym... I zatrzymuję","Kradnie 200 HP politykowi z najwyższym HP (1x użytelne)",1000,300], +["hurban","Jozef Miloslav Hurban","historicky","Farár Lite","Na jedno kolo sú všetky historické karty imúnne od poškodenia (použiteľné 1x)",600,300], +["mmhodza","Michal Miloslav Hodža","historicky","Prvý úspešný slovenský crowdfunder","Môže založiť maticu slovenskú, čím odoberie 200HP každému proruskému politikovi alebo Maďarovi na stole (použiteľné 1x)",1000,400], +["kamenicky","Ladislav Kamenický","prorusky","Pán je ekonóm","Každé kolo získa 6% úrok zo svojich životov",800,600], +["gaulieder","František Gaulieder","prorusky","Ja som sa mandátu nevzdal","Zoberie 100ATK členovi HZDS podľa výberu (použiteľné 2x)",100,90], +["valek","Miroslav Válek","komunista","Počkaj, zavolám Zorinovi","Ak je v rezervách, môže bez použitia ťahu zavolať Zorinovi a vyjsť na stôl",700,300], +["gal","Fedor Gál","prozapadny","Demokrat se vším všudy","Kým je na stole, všetky útoky možu smerovať iba naňho",1600,1], +["moravcik","Jozef Moravčík","prozapadny","Dočasná vláda","Je imúnny na schopnosti členov HZDS",500,450], +["kazimir","Peter Kažimír","prorusky","Krádež slovenského zlata","Každému nepriateľovi odoberie 100HP za kolo (nemôže odobrať posledných 100)",700,300], +["grohling","Branislav Gröhling","prozapadny","Opis diplomovky od samého seba","Môže vymeniť štatistiky dvoch ľubovoľných kariet",750,300], +["sakova","Denisa Saková","prorusky","Pozemok pri nemocníci","Vždy keď umrie niekto na stole, získa 100HP",600,250], +["mach","Alexander Mach","fasista","Od Žiliny ide vlak...","Ak Mach umrie, všetky karty Husáka na stole sú odstránené z hry",900,700], +["horvath","Ján Horváth","provychodny","Korupcia sa nevyšetruje, pretože sa žiadna nedeje","Prvý útok v hre mu nedáva žiadne poškodenie",80,20], +["tuka","Vojtech Tuka","fasista","Maďarský špión","Ak je v nepriateľskom tíme maďar, Tuka mu každé kolo odovzdá 50HP od náhodného spojenca (iného než seba)",600,800], +["paska","Pavol Paška","provychodny","Kachličkoval kúpeľnu v novembri '89","Má polovičný ATK proti komunistom",300,300], +["korcok","Ivan Korčok","prozapadny","Rozplače sa po prehratých prezidentských voľbách","Dáva -10HP každému proruskému politikovi v nepriateľskom tíme za kolo",800,0], +["rasi","Richard Raši","provychodny","Minister zdravotníctva je kinda sus","Raši môže ukradnúť celú nemocnícu a pripísať spojencovi (aj sebe) 450HP za cenu 50ATK (použiteľné 2x)",900,450], +["kolikova","Mária Kolíková","prozapadny","Nová súdna mapa","Môže prekresliť súdnu mapu a prehádzať tak aj svoje, aj nepriateľove rezervy (použiteľné 1x)",600,350], +["gaspar","Tibor Gašpar","provychodny","Policajný prezident","Politici v jeho tíme budú môcť od Gašpara „kúpiť“ 100 ATK za cenu 100HP, nepriatelia môžu kúpiť 100ATK za 125HP",800,0], +["huliak","Rudolf Huliak","provychodny","Medveď je biologická zbraň!","Huliak môže poslať medveďa na jedného protivníka a ubrať mu 500HP (použiteľné 1x)",500,250], +["belousovova","Anna Belousovová","provychodny","Učiteľka matematiky","Môže presvedčiť nepriateľa že si zle spočítal ATK a dostať tak o 100 menej (použiteľné 3x, nepoužíva ťah)",500,150], +["seliga","Juraj Šeliga","prozapadny","Nám nikto nebude strieľať novinárov!","Dáva dvojnásobné poškodenie proti členom Smeru a Hlasu",300,100], +["drucker","Tomáš Drucker","provychodny","Psie oči","Drucker vyzerá neškodný a dostáva o 25% menšie poškodenie od iných",800,300], +["nikolsonova","Lucia Ďuriš Nicholsonová","provychodny","Jablko","Nikolsonová sa môže odkotúľať do inej strany, ktorá má aspoň jedného člena v jej tíme (použiteľné 1x)",100,40], +["zaborska","Anna Záborská","provychodny","Potraty sú zlo!","Zvýši svoj útok o 30% za každého provýchodného politika vo svojom tíme za kolo (Max 300%)",400,100], +["mihal","Jozef Mihál","prozapadny","","Vždy keď sa objaví politik v jeho tíme, daný politik získa 5HP",300,60], +["budaj","Ján Budaj","prozapadny","Budajka","Môže natiahnuť nepriateľovi budajku cez oči a ukradnúť mu 100HP",800,150], +["richter","Ján Richter","provychodny","Viagra v aute","Vždy keď na Richtera niekto zaútočí, hodí po ňom viagru a odoberie mu 2HP",180,100], +["bugar","Béla Bugár","provychodny","O tom potom","Bugár môže útočiť aj jedno kolo po smrti",600,270], +["spisiak","Jaroslav Spišiak","prozapadny","Pomaličky máme čas","Spišiak dostáva aj udeľuje poškodenie s oneskorením jedného kola",200,80], +["remisova","Veronika Remišová","prozapadny","Charisma zdochnutej žaby","Nemá žiadnu schopnosť",300,50], +["mhodza","Milan Hodža","prvorep","Hodža mladší","Môže začať brojiť proti Sudetským Nemcom a získať 200ATK (použiteľné 1x)",800,450], +["slota","Ján Slota","prorusky","Pôjdeme do tankoch a zrovnáme Budapešť","Slota získa na 3 kolá 500ATK proti všetkým okrem iných členov SNS, ale po troch kolách umrie na otravu alkoholom",850,400], +["husak","Gustáv Husák","komunista","Normalizácia","Husák môže zavrieť jedného člena KSČ do gulagu a zobrať mu tak HP (použiteľné 1x)",1000,600], +["blaha","Ľuboš Blaha","provychodny","Spasiba!","Blaha môže získať 300HP od FSB (použiteľné 1x)",600,250], +["tiso","Jozef Tiso","fasista","Hlinkova Garda","Môže si pridať 400ATK ale stratí možnosť útočiť na fašistov (použiteľné 1x)",950,400], +["majersky","Milan Majerský","prozapadny","Je to pliaga!","Majerský ma permanentne +100ATK proti prozápadným politikom a -100ATK proti proruským a fašistickým politikom",700,400], +["carnogursky","Ján Čarnogurský","prorusky","Mentálna flexibilita","Čarnogurský si môže zmeniť politickú orientáciu",600,350], +["kotleba","Marián Kotleba","fasista","V jednote je sila","Kotleba môže raz za hru ísť do Coop Jednoty, kúpiť vodku s brohmexinom a zvýšiť oba svoje staty o 100 za každého fašistu vo svojom tíme (použiteľné 1x)",900,300], +["bilak","Vasil Biľak","komunista","Sovieti, zachráňte nás!","Zavolá do kremlu a vyhodí dvoch náhodne vybraných komunistov na stole z okna (ak nie je dosť komunistov, doplní sa inými)",300,450], +["heger","Eduard Heger","prozapadny","Neschopný vodca","Heger každé kolo odovzdá 10HP každému zo svojich spojencov",500,80], +["hlinka","Andrej Hlinka","fasista","HSLS","Môže nahradiť jedného fašistu vo svojom tíme Tisom",800,350], +["schuster","Rudolf Schuster","provychodny","Drienkovica","Schuster môže jednému spojencovi naliať drienkovicu, bude tak do konca hry strácať 1HP za kolo, ale okamžite získa 100ATK (použiteľné 1x)",800,350], +["danko","Andrej Danko","prorusky","Iba clovek cloveku...","Danko môže predniesť nezmyselnú reč a zmiasť tak náhodného nepriateľa na 2 kolá (použiteľné 1x)",600,250], +["dubcek","Alexander Dubček","komunista","Pražská Jar","Keď Dubček umrie, v nepriateľskom tíme sa objaví Husák s 0ATK",1500,900], +["kolar","Boris Kollár","prozapadny","13 detí s 11 ženami","Kolár sa každé kolo rozdelí na dvoch a každá jeho kópia bude mať polovičné HP a ATK tej predchádzajúcej, ak má však akákoľvek jeho kópia menej ako 15HP, okamžite umrie",350,200], +["caputova","Zuzana Čaputová","prozapadny","Prezidentské veto","Čaputová môže zrušiť ability jedného proruského politika v nepriateľskom tíme (použiteľné 1x)",1250,500], +["pellegrini","Peter Pellegrini","provychodny","Pordž tašku","Pellegrini dovolí hráčovi začínať s dvoma alebo žiadnou kartou v rezervách",900,250], +["tabak","Romana Tabák","prorusky","Facka sem, facka tam","Môže dať facku jednému svojmu spojencovi a zobrať mu tak 50HP, ale pridať mu 50ATK (použiteľné 5x)",450,100], +["matovic","Igor Matovič","prozapadny","Psychopat","Vždy keď Matovič zaútočí, dá náhodný ATK medzi 10-1000",1050,0], +["sulik","Richard Sulík","prozapadny","Kúpiť testy, či nekúpiť, toť otázka","Sulík môže dva krát za hru kúpiť testy a získať tak 100ATK, alebo ich nekúpiť a získať tak 100HP, ak je na stole Matovič, ukradne tieto staty jemu",850,500], +["dzurinda","Mikuláš Dzurinda","prozapadny","Ty si modrí, a ty si modrí, všetci ste modrí","Dzurinda môže raz za hru zmeniť všetkých politikov na Šmolkov a každé kolo jedného zjesť, vždy ale stratí 500HP a 500ATK",1300,800], +["meciar","Vladimír Mečiar","provychodny","Auto robí bum","Môže odpáliť auto s nepriateľským politikom a zobrať mu tak 500HP (použiteľné 1x, Michal Kováč je imúnny)",1400,800] +]; +const DB={};CARDS.forEach(a=>DB[a[0]]={key:a[0],name:a[1],fk:a[2],ab:a[3],desc:a[4],hp:a[5],atk:a[6]}); +// príslušnosti, na ktoré sa odvolávajú schopnosti +const TAG={ + hzds:["meciar","gaulieder"], sns:["slota","danko","belousovova"], madar:["bugar"], snp:["husak","dubcek"], + smer:["blaha","gaspar","kamenicky","kazimir","paska","richter","sutaj","sakova","rasi","pellegrini","drucker"] +}; + +/* ============ STAV ============ */ +let G=null, GID=0, SPEED=750, onChange=()=>{}; +const rnd=a=>a[Math.floor(Math.random()*a.length)]; +const shuffle=a=>{a=[...a];for(let i=a.length-1;i>0;i--){const j=Math.floor(Math.random()*(i+1));[a[i],a[j]]=[a[j],a[i]]}return a}; +const sleep=ms=>new Promise(r=>setTimeout(r,ms)); +const BALANCED_STATS={horvath:[250,60],remisova:[450,100],gaulieder:[275,90],spisiak:[350,140]}; +const mk=(key,owner)=>{const d=DB[key],c={...d,uid:++G.uid,owner,base:d.atk,uses:AB[key]&&AB[key].uses||999,acted:false};if(G.mode==="balanced"&&BALANCED_STATS[key]){[c.hp,c.atk]=BALANCED_STATS[key];c.base=c.atk}return c}; +const on=(c,key)=>c.key===key&&!c.silenced; +const tbl=p=>G.p[p].table.filter(c=>!c.ghost&&!c.dead); +const allies=c=>tbl(c.owner), enemies=c=>G.p.flatMap((P,i)=>i===c.owner?[]:tbl(i)), all=()=>G.p.flatMap((P,i)=>tbl(i)); +const alive=P=>P.table.length+P.reserve.length>0; +const find=uid=>{for(const P of G.p)for(const c of [...P.table,...P.reserve])if(c.uid===uid)return c;return null}; +const inReserve=c=>G.p[c.owner].reserve.includes(c); +function log(t,sep){G.log.unshift({t,sep});if(G.log.length>120)G.log.pop()} + +/* ============ SCHOPNOSTI ============ + t: none | enemy | ally | allyOther | any | any2 | choice ; uses: počet použití ; free: nepoužíva ťah */ +const AB={ +radacovsky:{t:"none",uses:1,run(c){G.pigeons.push(c.owner)}}, +lenart:{t:"enemy",uses:1,ok:(c,t)=>t.fk!=="komunista"&&(G.mode!=="balanced"||t.hp<=500),run(c,t){log(`${t.name} letí z okna.`);t.hp=0}}, +babis:{t:"enemy",uses:3,run(c,t){hurt(t,300,c)}}, +sutaj:{t:"allyOther",run(c,t){t.hp+=300;log(`${t.name} +300 HP`)}}, +uhrik:{t:"none",uses:1,can:c=>G.p.some((P,i)=>i!==c.owner&&[...P.table,...P.reserve].some(x=>TAG.snp.includes(x.key)))?"V nepriateľskom tíme je člen SNP.":"",run(c){c.atk+=250}}, +hlavaj:{t:"none",uses:1,run(c){G.p[c.owner].shield=3}}, +janosik:{t:"none",uses:1,run(c){const t=all().filter(x=>x!==c).sort((a,b)=>b.hp-a.hp)[0];if(t)c.hp+=hurt(t,200,c)}}, +hurban:{t:"none",uses:1,run(){G.histImmune=1}}, +mmhodza:{t:"none",uses:1,run(c){all().filter(x=>x.fk==="prorusky"||TAG.madar.includes(x.key)).forEach(x=>hurt(x,200,c))}}, +gaulieder:{t:"any",uses:2,ok:(c,t)=>t!==c&&TAG.hzds.includes(t.key),run(c,t){const n=Math.min(100,t.atk);t.atk-=n;c.atk+=n;log(`${t.name} −${n} ATK`)}}, +grohling:{t:"any2",uses:1,run(c,a,b){[a.hp,b.hp]=[b.hp,a.hp];[a.atk,b.atk]=[b.atk,a.atk];log(`${a.name} a ${b.name} si vymenili štatistiky.`)}}, +rasi:{t:"ally",uses:2,run(c,t){t.hp+=450;c.atk=Math.max(0,c.atk-50);log(`${t.name} +450 HP`)}}, +kolikova:{t:"none",uses:1,run(){for(const P of G.p)P.reserve=P.reserve.map(r=>{const live=P.table.filter(x=>!x.ghost);if(!live.length)return r;const out=rnd(live);P.table[P.table.indexOf(out)]=r;r.acted=true;log(`${r.name} ide na stôl, ${out.name} do rezervy.`);return out})}}, +huliak:{t:"enemy",uses:1,run(c,t){hurt(t,500,c)}}, +belousovova:{t:"enemy",uses:3,free:1,ok:(c,t)=>t.atk>0,run(c,t){const n=G.mode==="balanced"?50:100;t.atk=Math.max(0,t.atk-n);log(`${t.name} −${n} ATK`)}}, +nikolsonova:{t:"allyOther",uses:1,ok:(c,t)=>t.fk!==c.fk,run(c,t){c.fk=t.fk;log(`${c.name} je odteraz ${F[c.fk].n.toLowerCase()}.`)}}, +budaj:{t:"enemy",run(c,t){c.hp+=hurt(t,100,c)}}, +mhodza:{t:"none",uses:1,run(c){c.atk+=200}}, +slota:{t:"none",uses:1,run(c){c.slota=3}}, +husak:{t:"any",uses:1,ok:(c,t)=>t!==c&&t.fk==="komunista",run(c,t){c.hp+=hurt(t,300,c)}}, +blaha:{t:"none",uses:1,run(c){c.hp+=300}}, +tiso:{t:"none",uses:1,run(c){c.atk+=400;c.noFa=1}}, +carnogursky:{t:"choice",opts:c=>Object.keys(F).filter(k=>k!==c.fk).map(k=>[k,F[k].n]),run(c,k){c.fk=k;log(`${c.name} je odteraz ${F[k].n.toLowerCase()}.`)}}, +kotleba:{t:"none",uses:1,run(c){const n=allies(c).filter(x=>x.fk==="fasista").length*100;c.hp+=n;c.atk+=n;log(`${c.name} +${n} HP a ATK`)}}, +bilak:{t:"none",uses:1,run(c){const pool=all().filter(x=>x!==c);const k=shuffle(pool.filter(x=>x.fk==="komunista")).slice(0,2);const rest=shuffle(pool.filter(x=>!k.includes(x)));while(k.length<2&&rest.length)k.push(rest.pop());k.forEach(x=>{log(`${x.name} letí z okna.`);x.hp=0})}}, +hlinka:{t:"ally",uses:1,ok:(c,t)=>t.fk==="fasista",run(c,t){const P=G.p[t.owner],n=mk("tiso",t.owner);n.acted=true;P.table[P.table.indexOf(t)]=n;t.dead=true;entered(n);log(`${t.name} odchádza, nastupuje Tiso.`)}}, +schuster:{t:"allyOther",uses:1,run(c,t){t.atk+=100;t.drunk=1;log(`${t.name} +100 ATK, ale pije.`)}}, +danko:{t:"none",uses:1,run(c){const t=rnd(enemies(c));if(t){t.confused=2;log(`${t.name} je zmätený na 2 kolá.`)} }}, +caputova:{t:"enemy",uses:1,ok:(c,t)=>t.fk==="prorusky",run(c,t){t.silenced=1;log(`${t.name} prišiel o schopnosť.`)}}, +tabak:{t:"allyOther",uses:5,run(c,t){t.hp-=50;t.atk+=50;log(`${t.name} −50 HP, +50 ATK`)}}, +sulik:{t:"choice",uses:2,opts:()=>[["atk","Kúpiť testy (+100 ATK)"],["hp","Nekúpiť (+100 HP)"]],run(c,k){const m=all().find(x=>on(x,"matovic"));if(k==="atk"){c.atk+=100;if(m)m.atk-=100}else{c.hp+=100;if(m)m.hp-=100}if(m)log(`Zaplatil to ${m.name}.`)}}, +dzurinda:{t:"none",uses:1,run(c){c.smurf=1;G.smurfs=1;log("Všetci sú modrí.")}}, +meciar:{t:"enemy",uses:1,run(c,t){hurt(t,500,c)}} +}; +function targets(c,def){ + let ts=def.t==="enemy"?enemies(c):def.t==="ally"?allies(c):def.t==="allyOther"?allies(c).filter(x=>x!==c):all(); + return def.ok?ts.filter(t=>def.ok(c,t)):ts; +} +function abilityReady(c){ + const def=AB[c.key]; + if(!def||c.silenced||c.ghost||c.dead||c.uses<=0||inReserve(c)||c.confusedNow)return false; + if(!def.free&&c.acted)return false; + if(def.can&&def.can(c))return false; + if(def.t==="none"||def.t==="choice")return true; + return targets(c,def).length>=(def.t==="any2"?2:1); +} +function useAbility(c,a,b){ + const def=AB[c.key];c.uses--;if(!def.free)c.acted=true; + log(`${c.name} používa schopnosť „${c.ab}".`); + if(a&&a.uid&&on(a,"moravcik")&&TAG.hzds.includes(c.key))log(`${a.name} je imúnny na HZDS.`); + else def.run(c,a,b); + reap(); +} + +/* ============ BOJ ============ */ +function hurt(t,amt,src,kind){ + if(!t||t.dead||t.ghost||amt<=0)return 0; + if(kind!=="delayed"){ + if(t.fk==="historicky"&&G.histImmune>0){log(`${t.name} je imúnny.`);return 0} + if(kind==="attack"&&on(t,"horvath")&&!t.firstHit){t.firstHit=1;log(`${t.name}: žiadna korupcia, žiadne poškodenie.`);return 0} + if(on(t,"drucker"))amt*=.75; + if(G.p[t.owner].shield>0)amt*=G.mode==="balanced"?.4:.1; + amt=Math.round(amt); + if(on(t,"spisiak")||(src&&on(src,"spisiak")&&kind==="attack")){G.delayed.push({t,amt,n:1});log(`Poškodenie ${amt} pre ${t.name} príde o kolo neskôr.`);return 0} + } + t.hp-=amt;log(`${t.name} −${amt} HP`);return amt; +} +function effAtk(a,t,preview){ + let v=a.atk; + if(on(a,"matovic"))v+=preview?500:10+Math.floor(Math.random()*991); + if(a.slota>0&&!TAG.sns.includes(t.key))v+=500; + if(on(a,"majersky")){if(t.fk==="prozapadny")v+=100;if(t.fk==="prorusky"||t.fk==="fasista")v-=100} + if(on(a,"paska")&&t.fk==="komunista")v*=.5; + if(on(a,"seliga")&&TAG.smer.includes(t.key))v*=2; + return Math.max(0,Math.round(v)); +} +function attackTargets(a){ + if(a.acted||a.dead||inReserve(a))return []; + let ts=enemies(a);const gal=ts.filter(x=>on(x,"gal")); + if(gal.length)ts=gal; + if(a.noFa)ts=ts.filter(x=>x.fk!=="fasista"); + return ts; +} +function attack(a,t){ + const v=effAtk(a,t);a.acted=true; + log(`${a.name} útočí na ${t.name} silou ${v}.`); + hurt(t,v,a,"attack"); + if(on(t,"richter")){const n=G.mode==="balanced"?15:2;a.hp-=n;log(`${a.name} dostal viagrou, −${n} HP`)} + reap(); +} +function entered(c){allies(c).forEach(m=>{if(on(m,"mihal")&&m!==c)c.hp+=G.mode==="balanced"?25:5})} +function swap(s,r){ + const P=G.p[s.owner];P.table[P.table.indexOf(s)]=r;P.reserve[P.reserve.indexOf(r)]=s; + r.acted=true;s.acted=false;entered(r);log(`${s.name} strieda, nastupuje ${r.name}.`); +} +function valekIn(c){const P=G.p[c.owner];P.reserve.splice(P.reserve.indexOf(c),1);P.table.push(c);c.acted=false;entered(c);log(`${c.name} zavolal Zorinovi a je na stole.`)} +function buyAtk(c){const g=all().find(x=>on(x,"gaspar")&&x!==c);if(!g)return;const cost=g.owner===c.owner?100:125;if(c.hp<=cost)return;c.hp-=cost;c.atk+=100;log(`${c.name} si kúpil od Gašpara 100 ATK za ${cost} HP.`)} +const gasparCost=c=>{const g=all().find(x=>on(x,"gaspar")&&x!==c);return g?(g.owner===c.owner?100:125):0}; + +function reap(){ + let again=true; + while(again){again=false; + for(let p=0;p0&&!(on(c,"kolar")&&c.hp<15))continue; + again=true;const P=G.p[p]; + if(on(c,"bugar")){c.ghost=true;c.hp=0;c.ghostT=G.turn===p?2:1;log(`${c.name} padol, ale o tom potom.`)} + else{c.dead=true;P.table.splice(P.table.indexOf(c),1);log(`${c.name} je mimo hry.`)} + all().forEach(s=>{if(on(s,"sakova")){s.hp+=100;log(`${s.name} +100 HP`)}}); + if(on(c,"mach"))all().filter(x=>x.key==="husak").forEach(x=>{x.hp=0}); + if(on(c,"dubcek")){ + const foes=G.p.map((_,i)=>i).filter(i=>i!==p&&alive(G.p[i])); + if(foes.length){const target=rnd(foes),h=mk("husak",target);h.atk=0;h.base=0;h.acted=true;G.p[target].table.push(h);entered(h);log(`V tíme ${G.p[target].name} sa objavil Husák.`)} + } + if(P.reserve.length){const r=P.reserve.shift();r.acted=true;P.table.push(r);entered(r);log(`Z rezervy nastupuje ${r.name}.`)} + } + } + const remaining=G.p.map((P,i)=>({i,alive:alive(P)})).filter(x=>x.alive); + if(!G.over&&remaining.length<=1)G.over=remaining.length?`Vyhráva ${G.p[remaining[0].i].name}`:"Remíza"; +} +function roundEffects(p){ + for(const c of [...G.p[p].table]){ + if(c.dead||c.ghost)continue; + if(c.drunk)c.hp-=1; + if(on(c,"kamenicky")){const n=Math.round(c.hp*(G.mode==="balanced"?.03:.06));c.hp+=n;log(`${c.name} +${n} HP úrok`)} + if(on(c,"kazimir")){const dmg=G.mode==="balanced"?50:100;enemies(c).forEach(t=>{if(t.hp>100)hurt(t,Math.min(dmg,t.hp-100),c)})} + if(on(c,"korcok"))enemies(c).filter(t=>t.fk==="prorusky").forEach(t=>hurt(t,10,c)); + if(on(c,"tuka")){const m=enemies(c).filter(t=>TAG.madar.includes(t.key))[0],a=rnd(allies(c).filter(x=>x!==c));if(m&&a){a.hp-=50;m.hp+=50;log(`Tuka poslal 50 HP od ${a.name} pre ${m.name}.`)}} + if(on(c,"zaborska")){const n=allies(c).filter(x=>x.fk==="provychodny").length;const add=Math.min(Math.round(c.base*.3*n),2*c.base-(c.zb||0));if(add>0){c.zb=(c.zb||0)+add;c.atk+=add;log(`${c.name} +${add} ATK`)}} + if(on(c,"heger"))allies(c).forEach(a=>{if(a!==c&&c.hp>10){c.hp-=10;a.hp+=10}}); + if(on(c,"kolar")){c.hp=Math.floor(c.hp/2);c.atk=Math.floor(c.atk/2);const k={...c,uid:++G.uid};const T=G.p[p].table;T.splice(T.indexOf(c)+1,0,k);log(`${c.name} sa rozdelil.`)} + if(c.smurf&&!c.silenced){const t=rnd(enemies(c));if(t){log(`${c.name} zjedol Šmolka: ${t.name}.`);if(G.mode==="balanced")hurt(t,400,c);else t.hp=0;c.hp-=500;c.atk=Math.max(0,c.atk-500)}} + } + G.pigeons.filter(o=>o===p).forEach(()=>{const t=rnd(all());if(t){log("Holubica mieru narazila do politika.");hurt(t,G.mode==="balanced"?30:10,null)}}); +} +function tickRound(){ + // Durations advance once per complete table round, regardless of player count. + for(const c of all())if(c.slota>0&&--c.slota===0){log(`${c.name} umrel na otravu alkoholom.`);c.hp=0} + if(G.histImmune>0)G.histImmune--; + G.p.forEach(x=>{if(x.shield>0)x.shield--}); + G.delayed=G.delayed.filter(d=>{if(--d.n>0)return true;hurt(d.t,d.amt,null,"delayed");return false}); + reap(); +} +function startTurn(p){ + if(G.over)return; + G.turn=p; + const P=G.p[p];log(`Kolo ${G.round}: na ťahu ${P.name}`,1); + for(const c of P.table){c.acted=false;c.confusedNow=false;if(c.confused>0){c.confused--;c.acted=true;c.confusedNow=true}} + if(P.turns>0)roundEffects(p); + reap(); + if(G.over){onChange();return} + if(!alive(P)){endTurn();return} + if(G.round>150){G.over="Remíza";onChange();return} + onChange(); + if(P.ai)aiTurn(); +} +function endTurn(){ + if(G.over)return; + const p=G.turn,P=G.p[p]; + for(const c of [...P.table])if(c.ghost&&--c.ghostT<=0){c.dead=true;P.table.splice(P.table.indexOf(c),1);if(!P.table.length&&P.reserve.length)P.table.push(P.reserve.shift())} + reap();P.turns++; + if(G.over){onChange();return} + const pos=G.orderPos; + for(let step=1;step<=G.order.length;step++){ + const nextPos=(pos+step)%G.order.length,next=G.order[nextPos]; + if(!alive(G.p[next]))continue; + if(nextPos<=pos){G.round++;tickRound();if(G.over){onChange();return}} + G.orderPos=nextPos;startTurn(next);return; + } + G.over="Remíza";onChange(); +} + +/* ============ POČÍTAČ ============ */ +function aiArgs(c){ + const def=AB[c.key],en=enemies(c),al=allies(c); + const ts=def.t==="none"||def.t==="choice"?[]:targets(c,def); + const hi=a=>[...a].sort((x,y)=>y.hp-x.hp)[0],lo=a=>[...a].sort((x,y)=>x.hp-y.hp)[0]; + switch(c.key){ + case"carnogursky":case"nikolsonova":case"kolikova":return null; + case"tiso":return en.every(x=>x.fk==="fasista")?null:[]; + case"bilak":return al.length<=en.length?[]:null; + case"slota":return c.hp<450?[]:null; + case"sutaj":{const t=lo(ts);return t&&t.hp<350?[t]:null} + case"rasi":{const t=lo(ts);return t.hp<500?[t]:null} + case"hlinka":{const t=lo(ts);return t.hp<400?[t]:null} + case"tabak":{const t=hi(ts);return t&&t.hp>300?[t]:null} + case"schuster":return [hi(ts)]; + case"grohling":{const a=lo(al),b=hi(en);return a&&b&&b.hp>a.hp+200?[a,b]:null} + case"sulik":return [c.hp<400?"hp":"atk"]; + case"belousovova":return [[...ts].sort((x,y)=>y.atk-x.atk)[0]]; + case"hurban":return G.round>1?[]:null; + } + if(def.t==="none")return []; + if(!ts.length)return null; + if(def.t==="enemy")return [hi(ts)]; + if(def.t==="any"){const t=ts.find(x=>x.owner!==c.owner);return t?[t]:null} + return [lo(ts)]; +} +const AIV={babis:300,huliak:500,meciar:500,budaj:200,janosik:400,dzurinda:1200,caputova:350,danko:300,hlavaj:500,hurban:150,sutaj:300,rasi:450,blaha:250,uhrik:200,mhodza:180,tiso:300,slota:500,schuster:90,tabak:40,sulik:90,radacovsky:40,gaulieder:100,hlinka:450,bilak:700,grohling:400}; +function aiValue(c,a){ + if(c.key==="lenart")return a[0].hp; + if(c.key==="kotleba")return 150*allies(c).filter(x=>x.fk==="fasista").length; + if(c.key==="mmhodza"){const hit=x=>x.fk==="prorusky"||TAG.madar.includes(x.key);return 200*(enemies(c).filter(hit).length-allies(c).filter(hit).length)} + return AIV[c.key]||100; +} +// Počítač má ako každý hráč jednu akciu za ťah: vyberie tú s najvyššou hodnotou. +async function aiTurn(){ + const gid=GID,p=G.turn,P=G.p[p];G.busy=true; + await sleep(SPEED);if(gid!==GID)return; + const v=P.reserve.find(x=>on(x,"valek"));if(v){valekIn(v);onChange();await sleep(SPEED);if(gid!==GID)return} + for(const c of P.table.filter(x=>AB[x.key]&&AB[x.key].free)){let n=0;while(!G.over&&abilityReady(c)&&n++<5){const a=aiArgs(c);if(!a||!a[0])break;useAbility(c,...a)}} + let best=null; + if(!G.over)for(const c of P.table){ + if(c.acted||c.dead)continue; + if(abilityReady(c)&&!AB[c.key].free){const a=aiArgs(c);if(a){const s=aiValue(c,a);if(s>0&&(!best||s>best.s))best={s,c,a}}} + for(const t of attackTargets(c)){const d=effAtk(c,t,1),s=Math.min(d,t.hp)+(d>=t.hp?150:0);if(d>0&&(!best||s>best.s))best={s,c,t}} + } + if(best){if(best.a)useAbility(best.c,...best.a);else attack(best.c,best.t);onChange();await sleep(SPEED);if(gid!==GID)return} + G.busy=false; + if(G.over){onChange();return} + endTurn(); +} + +/* ============ NOVÁ HRA ============ */ +function newGame(teams,res,opt={}){ + if(!Array.isArray(teams)||teams.length<2||teams.length>8||!Array.isArray(res)||res.length!==teams.length) + throw new Error("Hra potrebuje 2 až 8 hráčov a nastavenie rezerv pre každého."); + opt=opt||{}; + GID++; + const mode=opt.mode==="balanced"?"balanced":"fun"; + G={uid:0,busy:false,mode,p:teams.map((team,i)=>({name:(opt.names&&opt.names[i])||`Hráč ${i+1}`,ai:!!(opt.ai&&opt.ai[i]),table:[],reserve:[],shield:0,turns:0})), + turn:0,first:0,round:1,order:[],orderPos:0,pigeons:[],histImmune:0,delayed:[],log:[],over:null,smurfs:0}; + teams.forEach((team,i)=>{ + const cs=team.map(k=>mk(k,i)); + const r=Math.max(0,Math.min(cs.length-1,Number(res[i])||0)); + if(mode==="balanced"&&team.includes("pellegrini")){ + const mult=r===0?.85:r===2?1.15:1; + if(mult!==1)cs.forEach(c=>{c.hp=Math.round(c.hp*mult);c.atk=Math.round(c.atk*mult);c.base=Math.round(c.base*mult)}); + } + G.p[i].table=cs.slice(0,cs.length-r);G.p[i].reserve=r?cs.slice(-r):[]; + }); + G.first=Math.floor(Math.random()*G.p.length); + G.order=G.p.map((_,i)=>(G.first+i)%G.p.length); + G.orderPos=0; + log(`Hra sa začína (${mode===`balanced`?`Balanced`:`Fun`}).`); + startTurn(G.first); + return G; +} +/* ============ ŤAH HRÁČA ============ + Jediný vstup pre ľudské akcie (lokálne aj na serveri). Hráč má jednu akciu za ťah, po nej ťah končí. Vráti text chyby, alebo nič. */ +function applyAction(seat,a){ + if(!G||G.over)return "Hra nebeží."; + if(!Number.isInteger(seat)||seat<0||seat>=G.p.length)return "Neplatný hráč."; + if(a&&a.type==="resign"){const P=G.p[seat];if(!alive(P))return "Už si mimo hry.";log(`${P.name} sa vzdal.`);P.table=[];P.reserve=[];reap();if(!G.over&&G.turn===seat)endTurn();else onChange();return} + if(G.turn!==seat)return "Nie si na ťahu."; + if(a.type==="end"){endTurn();return} + const c=find(a.c); + if(!c||c.owner!==seat||c.dead)return "Neplatná karta."; + if(a.type==="attack"){const t=find(a.t);if(!t||!attackTargets(c).includes(t))return "Neplatný cieľ útoku.";attack(c,t);endTurn()} + else if(a.type==="ability"){ + if(!abilityReady(c))return "Schopnosť sa teraz nedá použiť."; + const def=AB[c.key]; + if(def.t==="none")useAbility(c); + else if(def.t==="choice"){if(!def.opts(c).some(o=>o[0]===a.a))return "Neplatná voľba.";useAbility(c,a.a)} + else{ + const ts=targets(c,def),x=find(a.a); + if(!x||!ts.includes(x))return "Neplatný cieľ schopnosti."; + if(def.t==="any2"){const y=find(a.b);if(!y||y===x||!ts.includes(y))return "Neplatný druhý cieľ.";useAbility(c,x,y)} + else useAbility(c,x); + } + if(!def.free)endTurn(); + } + else if(a.type==="swap"){const r=find(a.t);if(c.acted||c.ghost||inReserve(c)||!r||r.owner!==seat||!inReserve(r))return "Striedanie nie je možné.";swap(c,r);endTurn()} + else if(a.type==="buy"){if(inReserve(c)||c.ghost||!gasparCost(c)||c.hp<=gasparCost(c))return "Nákup nie je možný.";if(G.mode==="balanced"&&c.boughtTurn===G.p[seat].turns)return "Táto karta už v tomto ťahu nakúpila.";buyAtk(c);if(G.mode==="balanced")c.boughtTurn=G.p[seat].turns} + else if(a.type==="valek"){if(!inReserve(c)||!on(c,"valek"))return "Táto karta to nevie.";valekIn(c)} + else return "Neznáma akcia."; +} +if(typeof module!=="undefined")module.exports={TEAM,CARDS,DB,newGame,applyAction,shuffle,rnd,all,sleep, + get G(){return G},set G(v){G=v},set SPEED(v){SPEED=v}}; diff --git a/public/img/README.txt b/public/img/README.txt new file mode 100644 index 0000000..abfb66c --- /dev/null +++ b/public/img/README.txt @@ -0,0 +1 @@ +Voliteľné obrázky kariet ukladaj sem. Názov súboru musí zodpovedať kľúču karty, napr. meciar.jpg alebo caputova.webp. diff --git a/public/img/babis.kandidat.webp b/public/img/babis.kandidat.webp new file mode 100644 index 0000000..89537fb Binary files /dev/null and b/public/img/babis.kandidat.webp differ diff --git a/public/img/belousovova.kandidat.webp b/public/img/belousovova.kandidat.webp new file mode 100644 index 0000000..241e918 Binary files /dev/null and b/public/img/belousovova.kandidat.webp differ diff --git a/public/img/bilak.webp b/public/img/bilak.webp new file mode 100644 index 0000000..f8aeaed Binary files /dev/null and b/public/img/bilak.webp differ diff --git a/public/img/blaha.webp b/public/img/blaha.webp new file mode 100644 index 0000000..9a4f4d9 Binary files /dev/null and b/public/img/blaha.webp differ diff --git a/public/img/budaj.webp b/public/img/budaj.webp new file mode 100644 index 0000000..ac72ac1 Binary files /dev/null and b/public/img/budaj.webp differ diff --git a/public/img/bugar.webp b/public/img/bugar.webp new file mode 100644 index 0000000..0480279 Binary files /dev/null and b/public/img/bugar.webp differ diff --git a/public/img/caputova.webp b/public/img/caputova.webp new file mode 100644 index 0000000..24bd421 Binary files /dev/null and b/public/img/caputova.webp differ diff --git a/public/img/carnogursky.webp b/public/img/carnogursky.webp new file mode 100644 index 0000000..ede9ce0 Binary files /dev/null and b/public/img/carnogursky.webp differ diff --git a/public/img/danko.webp b/public/img/danko.webp new file mode 100644 index 0000000..0deee4c Binary files /dev/null and b/public/img/danko.webp differ diff --git a/public/img/drucker.webp b/public/img/drucker.webp new file mode 100644 index 0000000..62bdd5e Binary files /dev/null and b/public/img/drucker.webp differ diff --git a/public/img/dubcek.webp b/public/img/dubcek.webp new file mode 100644 index 0000000..865da45 Binary files /dev/null and b/public/img/dubcek.webp differ diff --git a/public/img/dzurinda.webp b/public/img/dzurinda.webp new file mode 100644 index 0000000..a434b74 Binary files /dev/null and b/public/img/dzurinda.webp differ diff --git a/public/img/gal.webp b/public/img/gal.webp new file mode 100644 index 0000000..87d1d79 Binary files /dev/null and b/public/img/gal.webp differ diff --git a/public/img/gaspar.kandidat.webp b/public/img/gaspar.kandidat.webp new file mode 100644 index 0000000..726c1ae Binary files /dev/null and b/public/img/gaspar.kandidat.webp differ diff --git a/public/img/gaulieder.webp b/public/img/gaulieder.webp new file mode 100644 index 0000000..a5f204e Binary files /dev/null and b/public/img/gaulieder.webp differ diff --git a/public/img/grohling.webp b/public/img/grohling.webp new file mode 100644 index 0000000..2fffac3 Binary files /dev/null and b/public/img/grohling.webp differ diff --git a/public/img/heger.webp b/public/img/heger.webp new file mode 100644 index 0000000..3506c21 Binary files /dev/null and b/public/img/heger.webp differ diff --git a/public/img/hlavaj.kandidat.webp b/public/img/hlavaj.kandidat.webp new file mode 100644 index 0000000..738f73f Binary files /dev/null and b/public/img/hlavaj.kandidat.webp differ diff --git a/public/img/hlinka.webp b/public/img/hlinka.webp new file mode 100644 index 0000000..a3ab9d2 Binary files /dev/null and b/public/img/hlinka.webp differ diff --git a/public/img/huliak.webp b/public/img/huliak.webp new file mode 100644 index 0000000..dc6380c Binary files /dev/null and b/public/img/huliak.webp differ diff --git a/public/img/hurban.kandidat.webp b/public/img/hurban.kandidat.webp new file mode 100644 index 0000000..29571e7 Binary files /dev/null and b/public/img/hurban.kandidat.webp differ diff --git a/public/img/husak.webp b/public/img/husak.webp new file mode 100644 index 0000000..1317068 Binary files /dev/null and b/public/img/husak.webp differ diff --git a/public/img/janosik.kandidat.webp b/public/img/janosik.kandidat.webp new file mode 100644 index 0000000..c68a65f Binary files /dev/null and b/public/img/janosik.kandidat.webp differ diff --git a/public/img/kamenicky.kandidat.webp b/public/img/kamenicky.kandidat.webp new file mode 100644 index 0000000..dfafe20 Binary files /dev/null and b/public/img/kamenicky.kandidat.webp differ diff --git a/public/img/kazimir.kandidat.webp b/public/img/kazimir.kandidat.webp new file mode 100644 index 0000000..d4512cd Binary files /dev/null and b/public/img/kazimir.kandidat.webp differ diff --git a/public/img/kolar.webp b/public/img/kolar.webp new file mode 100644 index 0000000..226db75 Binary files /dev/null and b/public/img/kolar.webp differ diff --git a/public/img/kolikova.kandidat.webp b/public/img/kolikova.kandidat.webp new file mode 100644 index 0000000..7ac3a45 Binary files /dev/null and b/public/img/kolikova.kandidat.webp differ diff --git a/public/img/korcok.webp b/public/img/korcok.webp new file mode 100644 index 0000000..378cec0 Binary files /dev/null and b/public/img/korcok.webp differ diff --git a/public/img/kotleba.webp b/public/img/kotleba.webp new file mode 100644 index 0000000..1508b08 Binary files /dev/null and b/public/img/kotleba.webp differ diff --git a/public/img/lenart.webp b/public/img/lenart.webp new file mode 100644 index 0000000..33ec450 Binary files /dev/null and b/public/img/lenart.webp differ diff --git a/public/img/mach.webp b/public/img/mach.webp new file mode 100644 index 0000000..2c29da0 Binary files /dev/null and b/public/img/mach.webp differ diff --git a/public/img/majersky.webp b/public/img/majersky.webp new file mode 100644 index 0000000..e78f3f7 Binary files /dev/null and b/public/img/majersky.webp differ diff --git a/public/img/matovic.webp b/public/img/matovic.webp new file mode 100644 index 0000000..85dfe39 Binary files /dev/null and b/public/img/matovic.webp differ diff --git a/public/img/meciar.webp b/public/img/meciar.webp new file mode 100644 index 0000000..784f198 Binary files /dev/null and b/public/img/meciar.webp differ diff --git a/public/img/mhodza.webp b/public/img/mhodza.webp new file mode 100644 index 0000000..56bde0b Binary files /dev/null and b/public/img/mhodza.webp differ diff --git a/public/img/mihal.webp b/public/img/mihal.webp new file mode 100644 index 0000000..ae723ac Binary files /dev/null and b/public/img/mihal.webp differ diff --git a/public/img/mmhodza.kandidat.webp b/public/img/mmhodza.kandidat.webp new file mode 100644 index 0000000..cca1083 Binary files /dev/null and b/public/img/mmhodza.kandidat.webp differ diff --git a/public/img/moravcik.webp b/public/img/moravcik.webp new file mode 100644 index 0000000..561d33b Binary files /dev/null and b/public/img/moravcik.webp differ diff --git a/public/img/nikolsonova.webp b/public/img/nikolsonova.webp new file mode 100644 index 0000000..6db10d8 Binary files /dev/null and b/public/img/nikolsonova.webp differ diff --git a/public/img/paska.webp b/public/img/paska.webp new file mode 100644 index 0000000..a6cca23 Binary files /dev/null and b/public/img/paska.webp differ diff --git a/public/img/pellegrini.webp b/public/img/pellegrini.webp new file mode 100644 index 0000000..5ba58a4 Binary files /dev/null and b/public/img/pellegrini.webp differ diff --git a/public/img/radacovsky.kandidat.webp b/public/img/radacovsky.kandidat.webp new file mode 100644 index 0000000..27da934 Binary files /dev/null and b/public/img/radacovsky.kandidat.webp differ diff --git a/public/img/rasi.kandidat.webp b/public/img/rasi.kandidat.webp new file mode 100644 index 0000000..1b18834 Binary files /dev/null and b/public/img/rasi.kandidat.webp differ diff --git a/public/img/remisova.webp b/public/img/remisova.webp new file mode 100644 index 0000000..1cf836a Binary files /dev/null and b/public/img/remisova.webp differ diff --git a/public/img/richter.webp b/public/img/richter.webp new file mode 100644 index 0000000..934de54 Binary files /dev/null and b/public/img/richter.webp differ diff --git a/public/img/sakova.kandidat.webp b/public/img/sakova.kandidat.webp new file mode 100644 index 0000000..04229c8 Binary files /dev/null and b/public/img/sakova.kandidat.webp differ diff --git a/public/img/schuster.webp b/public/img/schuster.webp new file mode 100644 index 0000000..75ecc5e Binary files /dev/null and b/public/img/schuster.webp differ diff --git a/public/img/seliga.kandidat.webp b/public/img/seliga.kandidat.webp new file mode 100644 index 0000000..8222bfc Binary files /dev/null and b/public/img/seliga.kandidat.webp differ diff --git a/public/img/slota.webp b/public/img/slota.webp new file mode 100644 index 0000000..d7aae37 Binary files /dev/null and b/public/img/slota.webp differ diff --git a/public/img/spisiak.webp b/public/img/spisiak.webp new file mode 100644 index 0000000..4789516 Binary files /dev/null and b/public/img/spisiak.webp differ diff --git a/public/img/sulik.webp b/public/img/sulik.webp new file mode 100644 index 0000000..622ca09 Binary files /dev/null and b/public/img/sulik.webp differ diff --git a/public/img/sutaj.kandidat.webp b/public/img/sutaj.kandidat.webp new file mode 100644 index 0000000..78d2736 Binary files /dev/null and b/public/img/sutaj.kandidat.webp differ diff --git a/public/img/tabak.webp b/public/img/tabak.webp new file mode 100644 index 0000000..6fc0f40 Binary files /dev/null and b/public/img/tabak.webp differ diff --git a/public/img/tiso.webp b/public/img/tiso.webp new file mode 100644 index 0000000..e026eab Binary files /dev/null and b/public/img/tiso.webp differ diff --git a/public/img/tuka.webp b/public/img/tuka.webp new file mode 100644 index 0000000..a3b4c5c Binary files /dev/null and b/public/img/tuka.webp differ diff --git a/public/img/uhrik.webp b/public/img/uhrik.webp new file mode 100644 index 0000000..b8177f9 Binary files /dev/null and b/public/img/uhrik.webp differ diff --git a/public/img/valek.webp b/public/img/valek.webp new file mode 100644 index 0000000..3081be5 Binary files /dev/null and b/public/img/valek.webp differ diff --git a/public/img/zaborska.webp b/public/img/zaborska.webp new file mode 100644 index 0000000..290871c Binary files /dev/null and b/public/img/zaborska.webp differ diff --git a/public/index.html b/public/index.html new file mode 100644 index 0000000..d40c809 --- /dev/null +++ b/public/index.html @@ -0,0 +1,110 @@ + + + + + +Politické karty + + + + +
+ + + + diff --git a/server.js b/server.js new file mode 100644 index 0000000..308a5f3 --- /dev/null +++ b/server.js @@ -0,0 +1,157 @@ +// Politické karty – jednoduchý server na online hru. +// Bez závislostí: stačí Node.js 18+ a príkaz `node server.js`. +// Server drží stav každej miestnosti, sám vyhodnocuje pravidlá (public/game.js) +// a posiela stav všetkým pripojeným cez Server-Sent Events. +"use strict"; +const http = require("http"), fs = require("fs"), path = require("path"), crypto = require("crypto"); +const E = require("./public/game.js"); + +const PORT = process.env.PORT || 3000; +const PUB = path.join(__dirname, "public"); +const MIME = { ".html": "text/html; charset=utf-8", ".js": "text/javascript; charset=utf-8", ".css": "text/css; charset=utf-8", + ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".webp": "image/webp", ".gif": "image/gif", ".svg": "image/svg+xml" }; +const IMG_EXT = [".jpg", ".jpeg", ".png", ".webp", ".gif"]; + +const rooms = new Map(); // kód -> miestnosť +// limity živých SSE spojení (ochrana pred vyčerpaním pamäte) +const MAX_CLIENTS_PER_ROOM = Number(process.env.MAX_CLIENTS_PER_ROOM) || 64; +const MAX_CLIENTS_TOTAL = Number(process.env.MAX_CLIENTS_TOTAL) || 2000; +let totalClients = 0; +const tok = () => crypto.randomBytes(12).toString("hex"); +const clean = s => String(s || "").replace(/[<>&"'`]/g, "").trim().slice(0, 20) || "Hráč"; +function roomCode() { + const A = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"; + for (;;) { let c = ""; for (let i = 0; i < 4; i++) c += A[crypto.randomInt(A.length)]; if (!rooms.has(c)) return c; } +} +const newSeat = name => ({ name, token: tok(), team: null, res: 1, conns: 0, lastSeen: Date.now() }); +const seatOf = (room, token) => room.seats.findIndex(s => s && s.token === token); + +function view(room, seat) { + return { room: room.id, phase: room.G ? "battle" : "pick", you: seat, maxPlayers: room.seats.length, mode: room.mode, + players: room.seats.map(s => s && { name: s.name, ready: !!s.team, online: s.conns > 0 }), + spectators: [...room.clients].filter(c => c.seat < 0).length, G: room.G }; +} +function broadcast(room) { + room.touched = Date.now(); + for (const c of room.clients) c.res.write(`data: ${JSON.stringify(view(room, c.seat))}\n\n`); +} + +function json(res, code, obj) { res.writeHead(code, { "Content-Type": "application/json; charset=utf-8", "Cache-Control": "no-store" }); res.end(JSON.stringify(obj)); } +function body(req) { + return new Promise((ok, bad) => { + let d = ""; req.on("data", c => { d += c; if (d.length > 20000) { bad(new Error("big")); req.destroy(); } }); + req.on("end", () => { try { ok(JSON.parse(d || "{}")); } catch (e) { bad(e); } }); + }); +} + +function join(room, name, token) { + let seat = token ? seatOf(room, token) : -1; + if (seat >= 0) return { room: room.id, token, seat }; // návrat toho istého hráča + if (room.G) return { room: room.id, token: tok(), seat: -1 }; // po začiatku hry už len divák + seat = room.seats.findIndex(s => !s); + // pred začiatkom hry sa dá prevziať miesto po hráčovi, ktorý je dlhšie preč + if (seat < 0) seat = room.seats.findIndex(s => s.conns === 0 && Date.now() - s.lastSeen > 30000); + if (seat < 0) return { room: room.id, token: tok(), seat: -1 }; // divák + room.seats[seat] = newSeat(name); + return { room: room.id, token: room.seats[seat].token, seat }; +} + +function act(room, seat, a) { + if (seat < 0) return "Diváci nehrajú."; + const me = room.seats[seat]; + if (!a || typeof a.type !== "string") return "Neplatná akcia."; + if (a.type === "team") { + if (room.G) return "Hra už beží."; + const t = a.team; + if (!Array.isArray(t) || t.length !== E.TEAM || new Set(t).size !== t.length || !t.every(k => typeof k === "string" && Object.hasOwn(E.DB, k))) return "Neplatný tím."; + me.team = t; me.res = t.includes("pellegrini") && [0, 1, 2].includes(a.res) ? a.res : 1; + return; + } + if (a.type === "start") { + if (seat !== 0) return "Hru môže spustiť iba tvorca miestnosti."; + if (room.G) return "Hra už beží."; + const players = room.seats.filter(Boolean); + if (players.length < 2) return "Na hru treba aspoň dvoch hráčov."; + if (!players.every(s => s.team)) return "Všetci pripojení hráči musia mať pripravený tím."; + room.G = E.newGame(players.map(s => s.team), players.map(s => s.res), { names: players.map(s => s.name), ai: players.map(() => false), mode: room.mode }); + return; + } + if (a.type === "unready") { if (!room.G) me.team = null; return; } + if (a.type === "rematch") { if (room.G && room.G.over) { room.G = null; room.seats.forEach(s => { if (s) s.team = null; }); } return; } + if (!room.G) return "Hra ešte nezačala."; + E.G = room.G; // pravidlá pracujú nad stavom tejto miestnosti + return E.applyAction(seat, a); +} + +const server = http.createServer(async (req, res) => { + const u = new URL(req.url, "http://x"); + try { + if (u.pathname === "/api/ping") return json(res, 200, { ok: true }); + if (u.pathname === "/api/rooms") + return json(res, 200, [...rooms.values()].map(r => ({ id: r.id, phase: r.G ? "battle" : "pick", players: r.seats.filter(Boolean).map(s => s.name), maxPlayers: r.seats.length, mode: r.mode }))); + if (u.pathname === "/api/images") { + const out = {}; + // meciar.webp = hotový obrázok, meciar.kandidat.webp = dočasný kandidát z webu (hotový má prednosť) + try { for (const f of fs.readdirSync(path.join(PUB, "img"))) { + const e = path.extname(f).toLowerCase(), b = path.basename(f, path.extname(f)).toLowerCase(); + const cand = b.endsWith(".kandidat"), k = cand ? b.slice(0, -9) : b; + if (IMG_EXT.includes(e) && Object.hasOwn(E.DB, k) && (!out[k] || !cand)) out[k] = "img/" + encodeURIComponent(f); + } } catch (e) {} + return json(res, 200, out); + } + if (u.pathname === "/api/events") { + const room = rooms.get(u.searchParams.get("room")); + if (!room) return json(res, 404, { error: "Miestnosť neexistuje." }); + const seat = seatOf(room, u.searchParams.get("token")); + if (totalClients >= MAX_CLIENTS_TOTAL || (seat < 0 && room.clients.size >= MAX_CLIENTS_PER_ROOM)) + return json(res, 503, { error: "Príliš veľa pripojení, skús neskôr." }); + res.writeHead(200, { "Content-Type": "text/event-stream; charset=utf-8", "Cache-Control": "no-store", Connection: "keep-alive", "X-Accel-Buffering": "no" }); + const client = { res, seat }; room.clients.add(client); totalClients++; + if (seat >= 0) room.seats[seat].conns++; + broadcast(room); + req.on("close", () => { + if (room.clients.delete(client)) totalClients--; + const s = seat >= 0 && room.seats[seat]; if (s) { s.conns = Math.max(0, s.conns - 1); s.lastSeen = Date.now(); } + broadcast(room); + }); + return; + } + if (req.method === "POST" && u.pathname.startsWith("/api/")) { + const b = await body(req); + if (u.pathname === "/api/create") { + if (rooms.size >= 500) return json(res, 200, { error: "Server je plný, skús neskôr." }); + const requested = Number(b.maxPlayers); + const maxPlayers = Number.isInteger(requested) ? Math.max(2, Math.min(8, requested)) : 6; + const mode = b.mode === "balanced" ? "balanced" : "fun"; + const room = { id: roomCode(), seats: Array(maxPlayers).fill(null), G: null, mode, clients: new Set(), touched: Date.now() }; + room.seats[0] = newSeat(clean(b.name)); + rooms.set(room.id, room); + return json(res, 200, { room: room.id, token: room.seats[0].token, seat: 0, maxPlayers, mode }); + } + const room = rooms.get(String(b.room || "").toUpperCase()); + if (!room) return json(res, 200, { error: "Miestnosť neexistuje." }); + if (u.pathname === "/api/join") { const r = join(room, clean(b.name), b.token); broadcast(room); return json(res, 200, r); } + if (u.pathname === "/api/act") { + let err; try { err = act(room, seatOf(room, b.token), b.action); } catch (e) { console.error(e); err = "Chyba servera pri ťahu."; } + broadcast(room); + return json(res, 200, err ? { error: err } : { ok: true }); + } + return json(res, 404, { error: "Neznáma adresa." }); + } + // statické súbory z public/ + let rel; try { rel = decodeURIComponent(u.pathname); } catch (e) { rel = "/"; } + const file = path.join(PUB, path.normalize(rel === "/" ? "/index.html" : rel)); + if (!file.startsWith(PUB + path.sep)) { res.writeHead(403); return res.end(); } + fs.readFile(file, (e, data) => { + if (e) { res.writeHead(404, { "Content-Type": "text/plain; charset=utf-8" }); return res.end("Nenájdené"); } + res.writeHead(200, { "Content-Type": MIME[path.extname(file).toLowerCase()] || "application/octet-stream", "Cache-Control": "no-cache" }); + res.end(data); + }); + } catch (e) { json(res, 400, { error: "Neplatná požiadavka." }); } +}); + +// udržiavanie spojení a upratovanie opustených miestností +setInterval(() => { for (const r of rooms.values()) for (const c of r.clients) c.res.write(": ping\n\n"); }, 25000); +setInterval(() => { for (const r of rooms.values()) if (!r.clients.size && Date.now() - r.touched > 30 * 60000) rooms.delete(r.id); }, 60000); + +server.listen(PORT, () => console.log(`Politické karty bežia na http://localhost:${PORT}`)); diff --git a/tests/smoke.js b/tests/smoke.js new file mode 100644 index 0000000..5db4d24 --- /dev/null +++ b/tests/smoke.js @@ -0,0 +1,38 @@ +"use strict"; +const assert = require("node:assert/strict"); +const E = require("../public/game.js"); + +const teams = [ + ["radacovsky", "babis", "sutaj", "meciar"], + ["radacovsky", "lenart", "mhodza", "mihal"], + ["radacovsky", "kazimir", "kamenicky", "horvath"] +]; + +for (const mode of ["fun", "balanced"]) { + const G = E.newGame(teams, [1, 1, 1], { + names: ["Test A", "Test B", "Test C"], + ai: [false, false, false], + mode + }); + assert.equal(G.p.length, 3); + assert.equal(G.mode, mode); + for (const p of G.p) { + assert.equal(p.table.length, 3); + assert.equal(p.reserve.length, 1); + } + if (mode === "balanced") { + const horvath = [...G.p[2].table, ...G.p[2].reserve].find(c => c.key === "horvath"); + assert.equal(horvath.hp, 250); + assert.equal(horvath.atk, 60); + } + const attackerSeat = G.turn; + const attacker = G.p[attackerSeat].table[0]; + const targetSeat = (attackerSeat + 2) % 3; + const target = G.p[targetSeat].table[0]; + const before = target.hp; + const err = E.applyAction(attackerSeat, { type: "attack", c: attacker.uid, t: target.uid }); + assert.equal(err, undefined); + assert.ok(target.hp < before, `${mode}: attack should hit a non-adjacent opponent`); +} + +console.log("Smoke test OK: 3-player FFA, team setup, Balanced/Fun and cross-table attacks.");